body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I just started learning python yesterday, I have prior experience of C++. So I think I am able to get most of it pretty fast. I wrote a duplicate file finder for testing and practicing. </p>
<p>Can you guys look on this and give me some opinion if I am doing this right?</p>
<pre><code>import argparse
import os
import fnmatch
import hashlib
class MyFile:
partHashSize = 0
def __init__(self, name):
self.name = name
self.size = os.path.getsize(self.name)
self._processed = False
self._partHash = None
self._fullHash = None
def __str__(self):
return '{} is {}'.format(self.name, self.size)
def __repr__(self):
return '<MyFile {}:{}>'.format(self.name, self.size)
def _getPartHash(self):
if self._partHash is None:
h = hashlib.sha1()
with open(self.name, 'rb') as f:
h.update(f.read(MyFile.partHashSize))
self._partHash = h.hexdigest()
return self._partHash
partHash = property(_getPartHash)
def _getFullHash(self):
if self._fullHash is None:
h = hashlib.sha256()
with open(self.name, 'rb') as f:
while True:
buf = f.read(MyFile.partHashSize)
if not buf:
break
h.update(buf)
self._fullHash = h.hexdigest()
return self._fullHash
fullHash = property(_getFullHash)
def findDuplicates(self, files):
if self._processed:
return list()
dup = list()
for f in files:
if f.size == self.size and not os.path.samefile(f.name, self.name):
if f.partHash == self.partHash and f.fullHash == self.fullHash:
f._processed = True
dup.append(f)
if len(dup) > 0:
dup.append(self)
return dup
def sizeParse(szstr):
suffix = ['GB', 'MB', 'KB', 'B']
for i, s in enumerate(suffix):
if szstr.endswith(s):
return int(szstr[0: len(szstr) - len(s)]) * (1024 ** (len(suffix) - i - 1))
return int(szstr)
def recursiveDir(dir, pattern, filter):
l = list()
for root, dirs, files in os.walk(dir):
for file in files:
if fnmatch.fnmatch(file, pattern):
f = MyFile(os.path.join(root, file))
if filter(f):
l.append(f)
return l
def getFiles(arg, filter):
if os.path.isfile(arg):
return [MyFile(arg)]
if os.path.isdir(arg):
return recursiveDir(arg, '*', filter)
[path, file] = os.path.split(arg)
if len(path) == 0:
path = '.'
return recursiveDir(path, file, filter)
def main():
parser = argparse.ArgumentParser(description='Duplicate File Finder')
parser.add_argument('--min-size', dest= 'minsize', default='1KB', help='minimum file size, supports suffixes GB, MB, KB, B')
parser.add_argument('--max-size', dest= 'maxsize', default='1024GB', help='maximum file size, supports suffixes GB, MB, KB, B')
parser.add_argument('--hash-size', dest= 'hashsize', default='64KB', help='file hash size used for preliminary checking')
parser.add_argument('dirs', metavar='dirs', type=str,
nargs='*', help='dirs or globs or files, supports glob patterns')
args = parser.parse_args()
MyFile.partHashSize = sizeParse(args.hashsize)
MinimumSize = sizeParse(args.minsize)
MaximumSize = sizeParse(args.maxsize)
Files = list()
[Files.extend(getFiles(x, lambda x: x.size > MinimumSize and x.size < MaximumSize)) for x in args.dirs]
p = False
for f in Files:
dup = f.findDuplicates(Files)
if len(dup) > 0:
if not p:
print("Following are the duplicates:")
p = True
print([x.name for x in dup])
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T17:32:51.410",
"Id": "440231",
"Score": "1",
"body": "I don't know why there's a close vote; this seems fine to me."
}
] |
[
{
"body": "<h2>Formatting</h2>\n\n<p>There are some minor issues that would not pass PEP8. You should run a linter or inspector over your code, and it will suggest that you should change some whitespace.</p>\n\n<p>Another formatting suggestion is that you write <code>PART_HASH_SIZE</code> instead of <code>partHashSize</code> for constants, and <code>size_parse</code> instead of <code>sizeParse</code> for function names and variables.</p>\n\n<h2>Disposable comprehensions</h2>\n\n<p>There's not really a point to making this a list comprehension:</p>\n\n<pre><code>[Files.extend(getFiles(x, lambda x: x.size > MinimumSize and x.size < MaximumSize)) for x in args.dirs]\n</code></pre>\n\n<p>You're better off to just <code>for .. in</code>.</p>\n\n<h2>Units</h2>\n\n<p>1 MB == 1,000,000 bytes. 1 MiB == 1,048,576 bytes. You're using the latter, so you need to add some 'i' letters to your unit names.</p>\n\n<h2>Return unpacking</h2>\n\n<p>This:</p>\n\n<pre><code>[path, file] = os.path.split(arg)\n</code></pre>\n\n<p>doesn't need the square brackets.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:24:04.737",
"Id": "226509",
"ParentId": "226502",
"Score": "2"
}
},
{
"body": "<p>Python has some neat features, some of which might seem familiar from C++ and some not. The Python standard library is also very powerful. These comments are meant to be complementary to the <a href=\"https://codereview.stackexchange.com/a/226509/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/25834/reinderien\">@Reinderlein</a>, I will not repeat the useful advice given there.</p>\n\n<ul>\n<li>You can <a href=\"https://www.geeksforgeeks.org/chaining-comparison-operators-python/\" rel=\"nofollow noreferrer\">compare multiple things</a>: <code>MINIMUM_SIZE < x.size < MAXIMUM_SIZE</code>.</li>\n<li><p>The <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module: </p>\n\n<pre><code>from itertools import chain\nfiles = list(chain.from_iterable(\n get_files(x, lambda x: MINIMUM_SIZE < x.size < MAXIMUM_SIZE)) for x in args.dirs))\n</code></pre></li>\n<li><p><a href=\"https://realpython.com/primer-on-python-decorators/\" rel=\"nofollow noreferrer\">Decorators</a>, which makes code involving getters easy with <code>property</code>, which you are already using, but not to it's full potential:</p>\n\n<pre><code>@property\ndef part_hash(self):\n if self._part_hash is None:\n h = hashlib.sha1()\n with open(self.name, 'rb') as f:\n h.update(f.read(self.part_hash_size))\n self._part_hash = h.hexdigest()\n return self._part_hash\n</code></pre>\n\n<p>Note that <code>self.part_hash_size</code> is the same as <code>MyFile.part_hash_size</code>, unless you overwrite it in the instance (and be careful of mutating mutable objects). This gives you additional flexibility.</p></li>\n<li><p>(Python 3.6+) <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">Format strings</a>, which utilize the <code>format</code> syntax and make it even better:</p>\n\n<pre><code>def __str__(self):\n return f\"{self.name} is {self.size}\"\n\ndef __repr__(self):\n return f\"<{self.__class__.__name__} {self.name}:{self.size}>\"\n</code></pre></li>\n<li><p>(Python 3.8+) <a href=\"https://www.python.org/dev/peps/pep-0572\" rel=\"nofollow noreferrer\">Assignment expressions</a>, which allow you to shorten some <code>while</code> loops:</p>\n\n<pre><code>@property\ndef full_hash(self):\n if self._full_hash is None:\n h = hashlib.sha256()\n with open(self.name, 'rb') as f:\n while buf := f.read(self.part_hash_size):\n h.update(buf)\n self._full_hash = h.hexdigest()\n return self._full_hash\n</code></pre></li>\n<li><p>Truthiness of non-empty containers: <code>if l</code> is the same as <code>if len(l) > 0</code> for any container in the standard library (and should also be the same for any custom classes you create).</p></li>\n<li><p>Modules are automatically in their own namespace. No need to come up with names like <code>MyFile</code>, just call it <code>File</code>. You should avoid overwriting built-in names, but everything else is fair game, since you can always import them from another module and prefix them with the module name.</p></li>\n<li><p>List comprehensions are nice, but sometimes the functions in <a href=\"https://docs.python.org/3/library/operator.html\" rel=\"nofollow noreferrer\"><code>operator</code></a> give you more readability. Not really in this case, but as a demonstration: </p>\n\n<pre><code>from operator import attrgetter\na = [x.name for x in dup] # in your code\nb = [getattr(x, \"name\") for x in dup] # if the attribute name is a variable\nc = map(attrgetter(\"name\"), dup) # using operator instead\nassert a == b == list(c)\n</code></pre></li>\n<li><p><a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">Generators</a> allow you to get rid of storing the full result in a list only to then operate on every item of the list. Instead, generate the next item whenever you are done processing the previous one:</p>\n\n<pre><code>def recursive_dir(dir, pattern, filter):\n for root, dirs, files in os.walk(dir):\n for file in files:\n if fnmatch.fnmatch(file, pattern):\n if filter(f := File(os.path.join(root, file))):\n yield f\n</code></pre>\n\n<p>Or, with a generator expression added and using the <a href=\"https://docs.python.org/3/whatsnew/3.3.html#pep-380\" rel=\"nofollow noreferrer\"><code>yield from</code></a> keyword:</p>\n\n<pre><code>def recursive_dir(dir, pattern, filter):\n for root, dirs, files in os.walk(dir):\n yield from (f for file in files\n if fnmatch.fnmatch(file, pattern)\n and filter(f := File(os.path.join(root, file))))\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>As to your actual algorithm, you want to group together \"equal\" items, for some measure of equality. Currently you are comparing each file against each other file, so your algorithm is <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>. Instead, just define how two files compare and what the hash should be:</p>\n\n<pre><code>def __eq__(self, other):\n if not isinstance(other, self.__class__):\n return False\n return self.part_hash == other.part_hash and self.full_hash == other.full_hash\n\ndef __hash__(self):\n return int(self.part_hash, base=16)\n</code></pre>\n\n<p>Then you can just put them into a dictionary, which is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, because you only need to iterate over the files once:</p>\n\n<pre><code>from collections import defaultdict\n\ndef groupby_hash(files):\n duplicates = defaultdict(list)\n for f in files:\n duplicates[f].append(f)\n return duplicates\n\ndef files_with_duplicates(files):\n groups = groupby_hash(files).values()\n return list(filter(lambda x: len(x) > 1, groups))\n</code></pre>\n\n<p>This uses the fact that when putting a hashable object into a dictionary, it is not just put into a slot according to its hash. If two objects have the same hash, they are also compared by equality. This way only the <code>part_hash</code> should be used if there are no duplicates of it and the <code>full_hash</code> is used to make sure they are actually full duplicates. Sometimes the <code>full_hash</code> will still be calculated anyway because of regular collisions. You can test that this is the case for example like this:</p>\n\n<pre><code>files = list(recursive_dir(\".\", \"*\", lambda f: os.path.isfile(f.name)))\nlen(files)\n# 1448\nd = groupby_hash(files)\n\n# There are files which are unique and their `full_hash` has never been computed\nsum(map(lambda f: f._full_hash is None and len(d[f]) == 1, files)))\n# 759\n\n# The `full_hash` has been computed for all files with duplicates\nsum(map(lambda f: f._full_hash is not None and len(d[f]) > 1, files))\n# 93\nsum(map(lambda f: f._full_hash is None and len(d[f]) > 1, files))\n# 0\n\n# But there are some files without duplicates, whose `full_hash` has been computed\nsum(map(lambda f: f._full_hash is not None and len(d[f]) == 1, files))\n# 596\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T08:25:47.137",
"Id": "226555",
"ParentId": "226502",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226555",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T16:34:18.677",
"Id": "226502",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"windows"
],
"Title": "Duplicate File Finder in python"
}
|
226502
|
<p>I am working on SEPA XML generator in F#.</p>
<p>I developed two solutions that are roughly equivalent, one relies on the <code>XmlSerializer</code> while the other relies on <code>XmlProvider</code>, I am wondering what is the most idiomatic one?</p>
<p>Using the <code>XmlSerializer</code>:</p>
<pre><code>module SepaConversion.SepaXmlA
open System
open System.Collections.ObjectModel
open System.IO
open System.Xml.Serialization
open SepaConversion.Models
open SepaConversion.Common
[<AutoOpen>]
module Serialization =
[<CLIMutable>]
[<XmlRoot(ElementName="InitgPty")>]
type InitiatingParty = {
[<XmlElement(ElementName="Nm")>]
Name: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="GrpHdr")>]
type GroupHeader = {
[<XmlElement(ElementName="MsgId")>]
MessageId: string
[<XmlElement(ElementName="CreDtTm")>]
CreationDateTime: string
[<XmlElement(ElementName="NbOfTxs")>]
TransactionCount: string
[<XmlElement(ElementName="CtrlSum")>]
ControlSum: string
[<XmlElement(ElementName="InitgPty")>]
InitiatingParty: InitiatingParty
}
[<CLIMutable>]
[<XmlRoot(ElementName="SvcLvl")>]
type ServiceLevel = {
[<XmlElement(ElementName="Cd")>]
Code: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="PmtTpInf")>]
type PaymentTypeInformation = {
[<XmlElement(ElementName="InstrPrty")>]
InstructionPriority: string
[<XmlElement(ElementName="SvcLvl")>]
ServiceLevel: ServiceLevel
}
[<CLIMutable>]
[<XmlRoot(ElementName="Dbtr")>]
type Debtor = {
[<XmlElement(ElementName="Nm")>]
Name: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="Id")>]
type AccountId = {
[<XmlElement(ElementName="IBAN")>]
Iban: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="DbtrAcct")>]
type DebtorAccount = {
[<XmlElement(ElementName="Id")>]
AccountId: AccountId
[<XmlElement(ElementName="Ccy")>]
Currency: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="FinInstnId")>]
type FinancialInstitutionId = {
[<XmlElement(ElementName="BIC")>]
Bic: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="DbtrAgt")>]
type DebtorAgent = {
[<XmlElement(ElementName="FinInstnId")>]
FinancialInstitutionId: FinancialInstitutionId
}
[<CLIMutable>]
[<XmlRoot(ElementName="PmtId")>]
type PaymentIdentification = {
[<XmlElement(ElementName="EndToEndId")>]
EndToEndId: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="InstdAmt")>]
type InstructedAmount = {
[<XmlAttribute(AttributeName="Ccy")>]
Currency: string
[<XmlText>]
Amount: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="Amt")>]
type Amount = {
[<XmlElement(ElementName="InstdAmt")>]
InstructedAmount: InstructedAmount
}
[<CLIMutable>]
[<XmlRoot(ElementName="CdtrAgt")>]
type CreditorAgent = {
[<XmlElement(ElementName="FinInstnId")>]
FinancialInstitutionId: FinancialInstitutionId
}
[<CLIMutable>]
[<XmlRoot(ElementName="Cdtr")>]
type Creditor = {
[<XmlElement(ElementName="Nm")>]
Name: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="CdtrAcct")>]
type CreditorAccount = {
[<XmlElement(ElementName="Id")>]
AccountId: AccountId
}
[<CLIMutable>]
[<XmlRoot(ElementName="RmtInf")>]
type RemittanceInformation = {
[<XmlElement(ElementName="Ustrd")>]
Unstructured: string
}
[<CLIMutable>]
[<XmlRoot(ElementName="CdtTrfTxInf")>]
type CreditTransferTransactionInformation = {
[<XmlElement(ElementName="PmtId")>]
PaymentIdentification: PaymentIdentification
[<XmlElement(ElementName="Amt")>]
Amount: Amount
[<XmlElement(ElementName="CdtrAgt")>]
CreditorAgent: CreditorAgent
[<XmlElement(ElementName="Cdtr")>]
Creditor: Creditor
[<XmlElement(ElementName="CdtrAcct")>]
CreditorAccount: CreditorAccount
[<XmlElement(ElementName="RmtInf")>]
RemittanceInformation: RemittanceInformation
}
[<CLIMutable>]
[<XmlRoot(ElementName="PmtInf")>]
type PaymentInformation = {
[<XmlElement(ElementName="PmtInfId")>]
PaymentInformationId: string
[<XmlElement(ElementName="PmtMtd")>]
PaymentMethod: string
[<XmlElement(ElementName="NbOfTxs")>]
TransactionCount: string
[<XmlElement(ElementName="CtrlSum")>]
ControlSum: string
[<XmlElement(ElementName="PmtTpInf")>]
PaymentTypeInformation: PaymentTypeInformation
[<XmlElement(ElementName="ReqdExctnDt")>]
RequestedExecutionDate: string
[<XmlElement(ElementName="Dbtr")>]
Debtor: Debtor
[<XmlElement(ElementName="DbtrAcct")>]
DebtorAccount: DebtorAccount
[<XmlElement(ElementName="DbtrAgt")>]
DebtorAgent: DebtorAgent
[<XmlElement(ElementName="ChrgBr")>]
ChargeBearer: string
[<XmlElement(ElementName="CdtTrfTxInf")>]
CreditTransferTransactionInformation: CreditTransferTransactionInformation[]
}
[<CLIMutable>]
[<XmlRoot(ElementName="CstmrCdtTrfInitn")>]
type CustomerCreditTransferInitialization = {
[<XmlElement(ElementName="GrpHdr")>]
GroupHeader: GroupHeader
[<XmlElement(ElementName="PmtInf")>]
PaymentInformation: PaymentInformation
}
[<CLIMutable>]
[<XmlRoot(ElementName="Document", Namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03")>]
type Document = {
[<XmlElement(ElementName="CstmrCdtTrfInitn")>]
CustomerCreditTransferInitialization: CustomerCreditTransferInitialization
}
[<AutoOpen>]
module private Impl =
[<Literal>]
let TransferAdvicePaymentMethod = "TRF"
[<Literal>]
let SepaServiceCode = "SEPA"
[<Literal>]
let HighInstructionPriority = "HIGH"
[<Literal>]
let DebtorChargeBearer = "SLEV"
let createAmount (amount: decimal) currency = {
InstructedAmount = {
Currency = currency
Amount = amount |> string
}
}
let createPaymentIdentification id = {
EndToEndId = id
}
let createCreditorAgent bic = {
FinancialInstitutionId = {
Bic = bic
}
}
let createCreditor name = {
Name = name
}
let createCreditorAccount iban = {
AccountId = {
Iban = iban
}
}
let createRemittanceInformation reason = {
Unstructured = reason
}
let createInitiatingParty name : InitiatingParty = {
Name = name
}
let createDebtorAccount iban currency = {
AccountId = {
Iban = iban
}
Currency = currency
}
let createDebtorAgent bic : DebtorAgent = {
FinancialInstitutionId = {
Bic = bic
}
}
let createGroupHeader (creationDateTime: DateTimeOffset) information = {
MessageId = newHexGuid()
CreationDateTime = creationDateTime.ToString("o")
TransactionCount = information.CreditTransactions.Count |> string
ControlSum = information.CreditTransactions
|> Seq.map (fun x -> x.Amount)
|> Seq.sum
|> string
InitiatingParty = createInitiatingParty information.Debtor.Name
}
let createCreditTransferTransactionInformation (creditTransactions : ReadOnlyCollection<SepaCreditTransactionInformation>) currency =
creditTransactions
|> Seq.map(fun x ->
{
PaymentIdentification = createPaymentIdentification (newHexGuid())
Amount = createAmount x.Amount currency
CreditorAgent = createCreditorAgent x.Bic
Creditor = createCreditor x.Name
CreditorAccount = createCreditorAccount x.Iban
RemittanceInformation = createRemittanceInformation x.Reason
})
|> Seq.toArray
let createPaymentInformation messageId (requestedExecutionDate: DateTime) information creditTransferTransactionInformation = {
PaymentInformationId = messageId
PaymentMethod = TransferAdvicePaymentMethod
TransactionCount = information.CreditTransactions.Count |> string
ControlSum = information.CreditTransactions
|> Seq.map (fun x -> x.Amount)
|> Seq.sum
|> string
PaymentTypeInformation = {
InstructionPriority = HighInstructionPriority
ServiceLevel = {
Code = SepaServiceCode
}
}
RequestedExecutionDate = requestedExecutionDate.ToString("o")
Debtor = {
Name = information.Debtor.Name
}
DebtorAccount = createDebtorAccount information.Debtor.Iban information.Currency
DebtorAgent = createDebtorAgent information.Debtor.Bic
ChargeBearer = DebtorChargeBearer
CreditTransferTransactionInformation = creditTransferTransactionInformation
}
let generateSepaXml (information: SepaInformation) =
let creationTime = DateTimeOffset.UtcNow
let groupHeader = createGroupHeader creationTime information
let requestedExecutionDate = creationTime.UtcDateTime.AddDays(1.0)
let creditTransferTransactionInformation = createCreditTransferTransactionInformation
information.CreditTransactions
information.Currency
let paymentInformation = createPaymentInformation
groupHeader.MessageId
requestedExecutionDate
information
creditTransferTransactionInformation
let document = {
CustomerCreditTransferInitialization = {
GroupHeader = groupHeader
PaymentInformation = paymentInformation
}
}
let xmlSerializer = XmlSerializer(typeof<Document>)
use stringWriter = new StringWriter()
xmlSerializer.Serialize(stringWriter, document)
stringWriter |> string
</code></pre>
<p>Using the <code>XmlProvider</code> with a XSD file: <a href="https://github.com/perrich/sepawriter/blob/master/SepaWriter/Xsd/pain.001.001.03.xsd" rel="nofollow noreferrer"><code>pain.001.001.03.xsd</code></a>:</p>
<pre><code>module SepaConversion.SepaXmlB
open System
open FSharp.Data
open SepaConversion.Models
open SepaConversion.Common
[<AutoOpen>]
module private Impl =
type Sepa = XmlProvider<Schema="pain.001.001.03.xsd", EmbeddedResource="SepaConversion, pain.001.001.03.xsd">
[<Literal>]
let TransferAdvicePaymentMethod = "TRF"
[<Literal>]
let SepaServiceCode = "SEPA"
[<Literal>]
let HighInstructionPriority = "HIGH"
[<Literal>]
let SepaChargeBearer = "SLEV"
let sepaServiceLevel =
Sepa.SvcLvl(cd = Some SepaServiceCode,
prtry = None)
let createInitiatingParty name =
Sepa.InitgPty(nm = Some name,
pstlAdr = None,
id = None,
ctryOfRes = None,
ctctDtls = None)
let emptyAuthorizations = [||]
let paymentTypeInformation =
Sepa.PmtTpInf(instrPrty = Some HighInstructionPriority,
svcLvl = Some sepaServiceLevel,
lclInstrm = None,
ctgyPurp = None)
let createFinancialInstitutionId bic =
Sepa.FinInstnId(bic = Some bic,
clrSysMmbId = None,
nm = None,
pstlAdr = None,
othr = None)
let createIbanId iban =
Sepa.Id2(iban = Some iban, othr = None)
let createDebtorAgent bic =
Sepa.DbtrAgt(finInstnId = createFinancialInstitutionId bic,
brnchId = None)
let createDebtorAccount iban currency =
Sepa.DbtrAcct(id = createIbanId iban,
tp = None,
ccy = Some currency,
nm = None)
let createDebtor name =
Sepa.Dbtr(nm = Some name,
pstlAdr = None,
id = None,
ctryOfRes = None,
ctctDtls = None)
let createGroupHeader messageId creationTime (transactionCount : int32) controlSum initiatingParty =
Sepa.GrpHdr(msgId = messageId,
creDtTm = creationTime,
authstns = emptyAuthorizations,
nbOfTxs = (transactionCount |> string),
ctrlSum = Some controlSum,
initgPty = initiatingParty,
fwdgAgt = None)
let createPaymentId id =
Sepa.PmtId(instrId = None,
endToEndId = id)
let createInstructedAmount amount currency =
Sepa.InstdAmt(ccy = currency,
value = amount)
let createAmount amount currency =
Sepa.Amt(instdAmt = Some (createInstructedAmount amount currency),
eqvtAmt = None)
let createCreditorAgent bic =
Sepa.CdtrAgt(finInstnId = createFinancialInstitutionId bic,
brnchId = None)
let createCreditorAccount iban =
Sepa.CdtrAcct(id = createIbanId iban,
tp = None,
ccy = None,
nm = None)
let createCreditor name =
Sepa.Cdtr(nm = Some name,
pstlAdr = None,
id = None,
ctryOfRes = None,
ctctDtls = None)
let createRemittanceInformation reason =
Sepa.RmtInf(ustrds = [| reason |], strds = null)
let createCreditTransferTransactionInformation creditTransaction currency =
Sepa.CdtTrfTxInf(pmtId = createPaymentId (newHexGuid()),
pmtTpInf = None,
amt = createAmount creditTransaction.Amount currency,
xchgRateInf = None,
chrgBr = None,
chqInstr = None,
ultmtDbtr = None,
intrmyAgt1 = None,
intrmyAgt1Acct = None,
intrmyAgt2 = None,
intrmyAgt2Acct = None,
intrmyAgt3 = None,
intrmyAgt3Acct = None,
cdtrAgt = Some (createCreditorAgent creditTransaction.Bic),
cdtrAgtAcct = None,
cdtr = Some (createCreditor creditTransaction.Name),
cdtrAcct = Some (createCreditorAccount creditTransaction.Iban),
ultmtCdtr = None,
instrForCdtrAgts = [||],
instrForDbtrAgt = None,
purp = None,
rgltryRptgs = [||],
tax = None,
rltdRmtInfs = [||],
rmtInf = Some (createRemittanceInformation creditTransaction.Reason))
let createCreditTransferTransactionInformationArray creditTransactions currency =
creditTransactions
|> Seq.map(fun x -> createCreditTransferTransactionInformation x currency)
|> Seq.toArray
let createPaymentInformation messageId (transactionCount: int32) controlSum requestedExecutionDate information =
Sepa.PmtInf(pmtInfId = messageId,
pmtMtd = TransferAdvicePaymentMethod,
btchBookg = None,
nbOfTxs = Some (transactionCount |> string),
ctrlSum = Some controlSum,
pmtTpInf = Some paymentTypeInformation,
reqdExctnDt = requestedExecutionDate,
poolgAdjstmntDt = None,
dbtr = createDebtor information.Debtor.Name,
dbtrAcct = createDebtorAccount information.Debtor.Iban information.Currency,
dbtrAgt = createDebtorAgent information.Debtor.Bic,
dbtrAgtAcct = None,
ultmtDbtr = None,
chrgBr = Some SepaChargeBearer,
chrgsAcct = None,
chrgsAcctAgt = None,
cdtTrfTxInfs = createCreditTransferTransactionInformationArray
information.CreditTransactions
information.Currency)
let createCustomerCreditTransferInitialization groupHeader paymentInformation =
new Sepa.CstmrCdtTrfInitn(grpHdr = groupHeader,
pmtInfs = [| paymentInformation |])
let createDocument (customerCreditTransferInitialization: Sepa.CstmrCdtTrfInitn) =
Sepa.Document(customerCreditTransferInitialization)
let generateSepaXml information =
let messageId = newHexGuid()
let creationTime = DateTimeOffset.UtcNow
let requestedExecutionDate = creationTime.UtcDateTime.AddDays(1.0)
let transactionCount = information.CreditTransactions.Count
let controlSum = information.CreditTransactions
|> Seq.map (fun x -> x.Amount)
|> Seq.sum
let initiatingParty = createInitiatingParty information.Debtor.Name
let groupHeader = createGroupHeader
messageId
creationTime
transactionCount
controlSum
initiatingParty
let paymentInformation = createPaymentInformation
messageId
transactionCount
controlSum
requestedExecutionDate
information
let customerCreditTransferInitialization = createCustomerCreditTransferInitialization
groupHeader
paymentInformation
let document = createDocument customerCreditTransferInitialization
document.XElement |> string
</code></pre>
<p>The <code>XmlProvider</code> way seems more FP-ish and does not require to maintain a set of record types to generation the XML. However, the ctors generated by the provider are quite lengthy, I was surprised that I had to fill up everything and I was expecting that additional ctors would be generated of the fly, for example setting <code>None</code> option arguments so that not everything needs to be filled which would have made the experience a bit more convenient. Also it's a bit more cryptic in a sense that the maintainer has to know the meaning of each xml tags. </p>
<p>Surely I can add more wrapper functions to add some meanings, or literals /constants like:</p>
<pre><code>[<Literal>]
let private PaymentMethod = "TRF"
[<Literal>]
let private SepaCode = "SEPA"
[<Literal>]
let private InstructionPriority = "NORM"
</code></pre>
<p>Not sure if it's just a matter of taste, or if there is a real and clear benefit using one method over the other.</p>
<p>[EDIT]</p>
<p>Another issue with the <code>XmlProvider</code>, the need to copy to the output the schema file when building. Embedded resource only works xml samples =/</p>
<p>Another cons for <code>XmlSerializer</code>, it cannot serializer internal classes without a lof trickeries.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T16:49:54.483",
"Id": "226504",
"Score": "3",
"Tags": [
"xml",
"f#",
"serialization",
".net-core"
],
"Title": "F# XML Generation in .NET Core: XmlSerializer or XmlProvider"
}
|
226504
|
<blockquote>
<p>Write a function that will format a string and return it</p>
</blockquote>
<p>A fixed length of string is malloc-ed. <code>snprintf</code> is used to format the string and then the buffer is returned.</p>
<pre><code>const char *format_string(void)
{
char *buf = malloc(128);
snprintf(buf, 128, "%s/%d/%s/path", "here", 69, "is the");
return buf;
}
</code></pre>
<p><code>format_string()</code> can be later used like this:</p>
<pre><code>int main(void)
{
char *str = strdup(format_string());
printf("%s\n", str);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T17:41:39.517",
"Id": "440234",
"Score": "4",
"body": "The task \"format a string and return it\" sounds silly and is way too unspecific to be of any use."
}
] |
[
{
"body": "<p>regarding:</p>\n\n<pre><code>char *str = strdup(format_string());\n</code></pre>\n\n<p>The memory returned from <code>format_string()</code> is already allocated from the heap. The posted code has two memory leaks.</p>\n\n<ol>\n<li>the allocated memory in the function: <code>format_string()</code> is never passed to <code>free()</code></li>\n<li>the allocated memory in the function: <code>strdup()</code> is never passed to <code>free()</code></li>\n</ol>\n\n<p>suggest:</p>\n\n<pre><code>char *str = format_string()); \nprintf(\"%s\\n\", str);\nfree( str );\n</code></pre>\n\n<p>The call to <code>malloc()</code> should be checked to assure it was successful. Suggest:</p>\n\n<pre><code>char *buf = malloc(128);\nif( !buf )\n{\n perror( \"malloc failed\" );\n exit( EXIT_FAILURE );\n}\n</code></pre>\n\n<p>Note: <code>perror()</code> is exposed in the header file: <code>stdio.h</code></p>\n\n<p>Note: <code>exit()</code> and <code>EXIT_FAILURE</code> are exposed in the header file: <code>stdlib.h</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T22:24:13.123",
"Id": "440283",
"Score": "0",
"body": "Concerning \"the allocated memory in the function: `format_string()` is never passed to `free()`\". `buf` lives until it's content is being returned. I understand it stays unfreed. But how do I free `*buf`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T21:37:41.083",
"Id": "440450",
"Score": "0",
"body": "the pointer to the allocated memory is being passed back from: `format_string()` so, in `main()`, after calling `printf()`, call `free( str );` BTW: the pointer in `buf` is all that dies, the actual allocated memory is still allocated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T21:46:16.473",
"Id": "440451",
"Score": "0",
"body": "regarding: *and then the buffer is returned.* No, the buffer is NOT returned, Only a pointer to the buffer is returned"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:10:38.620",
"Id": "226508",
"ParentId": "226505",
"Score": "3"
}
},
{
"body": "<p><code>malloc</code>ed memory has to be <code>free</code>d at some point. <a href=\"http://www.man7.org/linux/man-pages/man3/free.3.html\" rel=\"nofollow noreferrer\"><code>free()</code></a> needs a pointer to non-<code>const</code> data as argument. Therefore, <code>format_string()</code> has to return a pointer to non-<code>const</code> data, so that it can be passed to <code>free()</code> later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:31:49.853",
"Id": "226517",
"ParentId": "226505",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T16:57:39.287",
"Id": "226505",
"Score": "-1",
"Tags": [
"c",
"strings",
"formatting"
],
"Title": "Format and return a string from a function in C"
}
|
226505
|
<p>I have designed a compile time Finite State Machine generator. I have chosen to use some of the features of C++17 such as parameter pack expansion, fold expressions and lambdas to keep the complexity of this class structure and its hierarchy as simple and readable as possible. </p>
<p>It is currently in its infancy as I have only just created the basic shell, needed constructors and functionality to add transition states to previous existing states. </p>
<p>My design by intent is that the size of the FSM has to be known at compile time and the States have to be created before hand as the FSM class's constructor requires the appropriate amount of states to be constructed. </p>
<p>Once the FSM is constructed, its size can not be changed nor can any other states be added or removed from the fsm. </p>
<p>I chose to do it this way since a Finite State Machine has a "Finite" amount of states; otherwise it would just be an Arbitrary State Machine. </p>
<hr>
<p>Here is my test application, source code and output:</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <string>
#include "FSM.h"
int main() {
const u16 size = 7;
State<size> Idle("Idle", 0), Init("Init", 1), Fetch("Fetch", 2),
Load("Load", 3), Read("Read", 4), Write("Write", 5),
Stop("Stop", 6);
FiniteStateMachine<size> fsm( Idle, Init, Fetch, Load, Read, Write, Stop );
fsm.addStateTransition(Idle, Init, Fetch, Load);
fsm.addStateTransition(Init, Idle, Load, Read);
fsm.addStateTransition(Fetch, Read, Load, Write, Idle);
fsm.addStateTransition(Load, Read, Write, Fetch, Idle, Stop);
fsm.addStateTransition(Read, Load, Fetch, Idle, Stop);
fsm.addStateTransition(Write, Idle);
fsm.addStateTransition(Stop, Idle);
for (auto& state : fsm.states_) {
std::cout << "State " << state.id_ << " (" << state.value_.to_string() <<
") has a transitions to: \n";
for (auto& next : state.nextStates_) {
std::cout << "\t" << next->id_ << " (" << next->value_.to_string() << ")\n";
}
}
std::cout << '\n';
return 0;
}
</code></pre>
<p><strong>FSM.h</strong></p>
<pre><code>#pragma once
#include <algorithm>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
using u16 = std::uint16_t;
// Used to define the size of the bitset to represent
// all possible states with the fewest amount of binary digits.
constexpr unsigned numBits(unsigned n) {
return n < 2 ? n : 1 + numBits(n >> 1);
}
template<u16 N>
class State {
public:
const std::string id_;
std::bitset<numBits(N)> value_;
std::vector<std::shared_ptr<State<N>>> nextStates_;
State(const std::string id, const u16 value) : id_{ id }, value_{ value } {}
// Function to all of this state's next states it is public for now
// but in a furture revision I plan on making this private and
// a friend to the FSM class as it will only be callable from with
// that class. The user would use the FSM's addStateTransition() function
// for its public interface.
template<typename... States>
void addTransitions(const States& ... states) {
// Use a Lambda to create a shared_ptr<State> and to add it
// to the corresponding vector
auto transition = [&](auto state) {
auto ptr = std::make_shared<State>(state);
nextStates_.emplace_back(std::forward<std::shared_ptr<State>>(ptr));
return true;
};
const bool success = (transition( states ) && ...);
if (!success)
std::cout << "Failed to add transition states.\n";
}
// Operator== is needed for the FSM class, if both the
// string id_ and the bitset value_ are equal then it is the same state.
bool operator==(const State<N>& other) {
return ((id_ == other.id_) && (value_ == other.value_));
}
};
template<u16 N>
class FiniteStateMachine {
public:
std::vector<State<N>> states_;
// There is no default constructor!
FiniteStateMachine() = delete;
// The parameter pack size must be equal to the number of States provided by N
template<typename... States>
FiniteStateMachine(States&&... states) : states_{ std::move(states)... } {
static_assert((sizeof...(states) == N), "The number of states passed in does not match this State Machines size.");
// Let's keep the vector as small as possible!
states_.shrink_to_fit();
}
// Public interface function to add transition states.
// The first state passed is the current state and the parameter pack
// is all of that state's next states
template<typename Current, typename... NextStates>
void addStateTransition(const Current& currentState, const NextStates& ... nextStates) {
// First check if all of the states passed in exist within our container
// if any one of them fails then it is an invalid State for this State machine
// and return early. The use of a lambda here is quite practicle since I'm
// using fold expressions and recursion to check and add all of the state transitions.
auto current = std::find(states_.begin(), states_.end(), currentState);
if (current == states_.end()) {
std::cout << "Could not find the current state: " << current->id_ << " in this State Machine.";
return;
}
auto lookup = [&](auto state) {
// single find
auto it = std::find(states_.begin(), states_.end(), state);
if (it == states_.end()) {
std::cout << "Could not find " << state.id_ << " in this State Machine.";
return false;
}
return true;
};
bool const allFound = (lookup(nextStates) && ...);
if (!allFound) {
return;
}
current->addTransitions(nextStates...);
}
};
</code></pre>
<p><strong>Output</strong></p>
<pre><code>State Idle (000) has a transitions to:
Init (001)
Fetch (010)
Load (011)
State Init (001) has a transitions to:
Idle (000)
Load (011)
Read (100)
State Fetch (010) has a transitions to:
Read (100)
Load (011)
Write (101)
Idle (000)
State Load (011) has a transitions to:
Read (100)
Write (101)
Fetch (010)
Idle (000)
Stop (110)
State Read (100) has a transitions to:
Load (011)
Fetch (010)
Idle (000)
Stop (110)
State Write (101) has a transitions to:
Idle (000)
State Stop (110) has a transitions to:
Idle (000)
</code></pre>
<hr>
<p>I know I can wrap this in a namespace so I don't need that as a suggestion, but I would like to know the following about my code:</p>
<ul>
<li>I'd like to know your thoughts and concerns about this code. </li>
<li>Do you think it is readable, manageable, explicit in its intent, etc.? </li>
<li>Are there any code smells, gotchas, missed corner cases, etc.? </li>
<li>Is there anything that can be done to improve this? </li>
</ul>
<p>These are future plans that I have:</p>
<ul>
<li><strong>-Note-</strong> *I do know that FSM's sometimes have conditions for a specific state to transition to another when their input relies on their current state such as the difference between a Moore and a Mealy machine.</li>
<li>The ability for a state to add input values that may or may not change their state. For this the states would also have to have a condition variable added to their core component. </li>
<li>The ability to return its data which may or may not effect any of the states it points to. </li>
<li>I may add another vector that would represent previous states so that a current active state is aware of what state activated it. For example: Init goes to Idle, Load and Read by my example. If we are now in the Load state it could of been Idle, Fetch, or Read that triggered it. It might be useful to have this backtracking history available for future references.</li>
</ul>
<p>To finish up; I would also be interested in your suggestions of what kind of features, functionality and support you would like to see in this kind of class
structure, application. </p>
<hr>
<p>Just a little bit on the side note:</p>
<p><em>Not included here but within the same project I have another small lightweight class template that takes 2 unsigned values for its template parameters one to represent the amount of inputs, and the other to represent the amount of binary logical functions to be performed on that set of inputs. The class will then generate a table with the corresponding inputs and outputs in binary and will display a canonical truth table. Each of my binary functions can take any number of inputs, they are independent functions that are separate from the Binary Truth Table Generator. I haven't posted it here on Code Review just yet as I'm still currently working on it. However, I may end up combining the two in order to try and generate transition tables, and K-Maps!</em></p>
<hr>
<p><strong>-Edit-</strong> </p>
<p>After looking at the code and considering the overall structure of what a finite state machine is I have determined that one could add two states with the same name as long as their values are different for example: A state machine may have an <code>Idle</code> state that is represented by say both <code>000</code> and <code>111</code>, on the other hand what would be invalid would be having two states with the same value with different string names or ids! For example: having something like <code>Go Right(010)</code> and <code>Go Left(010)</code> would be invalid as two different states can not share the same value or bit representation since this would cause ambiguity! This will be considered under the list of future plans.</p>
|
[] |
[
{
"body": "<h1>Avoid declaring <code>u16</code>.</h1>\n\n<p>You are defining <code>u16</code> to be equal to <code>std::uint16_t</code>. Is this because you just want to save some keystrokes, or is it because the <code>u16</code> represents something distinct in your class? If you want it to be a value representing the number of states or index of a state, then make this more explicit:</p>\n\n<pre><code>using state_size_t = std::uint16_t;\n</code></pre>\n\n<p>Now when you ever decide to change the amount of bits used for state sizes/indices, you only have to change one line.</p>\n\n<p>Another issue with <code>u16</code> is that it's a very generic name, and by just declaring it in the global namespace, you risk conflicting with other libraries that potentially make the same mistake.</p>\n\n<h1>Avoid exposing implementation details to the global namespace</h1>\n\n<p><code>numBits()</code> is some function you just want to use in some of the member functions of <code>class State</code>. Similar to <code>u16</code>, you don't want this in the global namespace where it could cause conflicts. Just make it part of <code>State</code>:</p>\n\n<pre><code>template<u16 N>\nclass State {\n static constexpr unsigned numBits(u16 n) {...}\n\npublic:\n ...\n};\n</code></pre>\n\n<p>Even better would be to declare a namespace for your library, and put everything in that namespace, including the <code>using</code> declaration.</p>\n\n<h1>There's no need to write <code>State<N></code> inside <code>State</code> itself</h1>\n\n<p>Inside a templated class, you don't have to add the template parameters each time you use the type. So just write:</p>\n\n<pre><code>std::vector<std::shared_ptr<State>> nextStates_;\n</code></pre>\n\n<p>Note that you already use the type <code>State</code> without <code><N></code> in many places.</p>\n\n<h1>Don't use a <code>std::bitset<></code> with only one bit set</h1>\n\n<p>When you create a <code>State</code>, you copy the <code>u16 value</code> to a <code>std::bitset<></code> that might be very large (8 kilobytes if <code>N</code> equals 65535). But it's just a copy of the value, so store it as a <code>u16</code>.</p>\n\n<h1>Avoid pointer references for the list of transitions</h1>\n\n<p>With pointers, you always have to worry about ownership, and whether they are valid or not. They also restrict moving and copying of variables. And in this case, you don't need pointers to refer to states, since they already have unique identifiers in the form of a <code>u16</code>. So just write:</p>\n\n<pre><code>std::vector<u16> nextStates_;\n</code></pre>\n\n<p>Or, if you expect the transition table to be dense, it might make sense to make this a bitset:</p>\n\n<pre><code>std::bitset<numBits(N)> nextStates_;\n</code></pre>\n\n<p>And in <code>addTransition()</code>, write:</p>\n\n<pre><code>nextStates_.set(state.value_);\n</code></pre>\n\n<h1>Use <code>std::array<></code> instead of <code>std::vector<></code> if you know the size up front</h1>\n\n<p>In <code>class FiniteStateMachine</code>, you already know the number of states you are going to support. So just write:</p>\n\n<pre><code>std::array<State, N> states_;\n</code></pre>\n\n<p>This has the advantage that it doesn't require heap allocations, and you don't have to shrink to fit in the constructor.</p>\n\n<h1>Can states be reused in different state machines?</h1>\n\n<p>One issue with your design is that you can declare a <code>State</code>, and it is not tied to a state machine. However, when creating a state machine and adding state transitions, those transitions are actually stored inside the <code>State</code> variable, not inside the <code>FiniteStateMachine</code>. So this effectively makes reusing states impossible.</p>\n\n<p>You could make states reusable, by moving the list of possible transitions to <code>FiniteStateMachine</code> itself. There are various ways possible, for example you could do:</p>\n\n<pre><code>template<u16 N>\nclass FiniteStateMachine {\npublic:\n std::vector<std::pair<State, std::vector<State>>> states_;\n ...\n</code></pre>\n\n<p>So each element of <code>states_</code> is a <code>State</code> plus a vector of other <code>State</code>s it can transition to. Or if you have dense transition tables:</p>\n\n<pre><code> std::vector<std::pair<State, std::bitset<numBits(N)>>> states_;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:07:46.413",
"Id": "440263",
"Score": "0",
"body": "As for the `u16` I use that quite often in my own libraries of functions and classes. I use it with my Register classes, my Binary Truth Table generator, and others. I do have them inside of my own namespace; I omit the namespace here since for my own understanding it is \"understood\", I explicitly mentioned: \"I know I can wrap this in a namespace so I don't need that as a suggestion, but I would like to know the following about my code:\" This also goes to the point you mentioned about voiding global name space; I almost always have all of my code in my own namespace or set of namespaces..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:10:15.013",
"Id": "440264",
"Score": "0",
"body": "You had mentioned: \"Can states be reused in different state machines?\nOne issue with your design is that you can declare a State, and it is not tied to a state machine. However, when creating a state machine and adding state transitions, those transitions are actually stored inside the State variable, not inside the FSM. So this effectively makes reusing states impossible. You could make states reusable, by moving the list of possible transitions to FSM itself. There are various ways possible, for example you could do:\" This is a very good point and was my initial attempt when designing it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:13:52.207",
"Id": "440266",
"Score": "0",
"body": "I however had changed its location to get the class's to compile while using fold expressions over lambdas. I do however like the idea that a State knows or has references to its transitions instead of being completely agnostic to them. I could however have the FSM hold the shared_ptrs for all of the states and their associated transitions while each state itself can store a vector of id's or values to the ones they transition to..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:15:46.047",
"Id": "440267",
"Score": "0",
"body": "As for using `array` over vector that was my original first choice but again when trying to get the fold expressions over lambdas to compile with the parameter pack expansions a long with storing the shared_ptr in the container, I found it was easier to work with vectors at first. Now that I have it working; I can always swap the containers and make the minimal modifications needed..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:24:06.727",
"Id": "440268",
"Score": "0",
"body": "Can States be reused? In truth I don't see why not, however a State in one FSM may or may not be exactly the same as a similar state in another FSM. Let's say we have a `Load` with a value of `(101)` in one FSM as its 6th state and you might `Load` again with a value of (011)` in another FSM as its 4th state. The two machines are independent and even though they both have a `Load`, and these `Load` States not the same. Another thing is the one FSM could be a Moore while the other a Mealy where one state transition depends on its input and current state and the other doesn't..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:26:52.123",
"Id": "440269",
"Score": "0",
"body": "As for the function that calculates the `ceil(log2(N)` I think I'd rather leave outside of the class as it could be a useful function in many other places and cases!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:30:14.650",
"Id": "440270",
"Score": "0",
"body": "All in all I do appreciate all of your feed back and positive constructive criticism and the time and effort you put into this. I will take many of those things into consideration such as swap out the vector for an array since it is finite. Being careful with shared_ptrs, etc. but this is why it's called a rough draft or a shell! This is the bare bones part and would some insight before I started to add a whole bunch more features, functionalities, and capabilities. ^^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T21:03:42.520",
"Id": "440276",
"Score": "0",
"body": "I'm glad you appreciate the feedback. As for the namespace: please don't omit this next time. Even if you yourself do not need it reviewed, it helps both reviewers to see that you have already thought of such things, and it helps other visitors that want to learn from your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T21:36:12.880",
"Id": "440278",
"Score": "0",
"body": "I understand what you are saying about the `namespace` part, however I did explicitly state that in the post inferring that I have my code in a namespace!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:23:15.220",
"Id": "226516",
"ParentId": "226506",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T17:59:17.010",
"Id": "226506",
"Score": "2",
"Tags": [
"c++",
"generics",
"c++17",
"state-machine"
],
"Title": "A Simplistic Finite State Machine Generator"
}
|
226506
|
<p>A short script to make a CSRF token to be used in my html elements such as inputs, file-uploads, scripts, iframes & svgs.</p>
<pre><code><?php
session_start();
if (NULL || empty($_SESSION['csrf_token'])){ // Cross Site Request Forgery ::(Token.).
$_SESSION['csrf_token']= bin2hex(random_bytes(28).openssl_random_pseudo_bytes(7));
}
?>
</code></pre>
<p>Above Is the Old Version that was Posted Last Year,
Just Revisited this Project and Added some to to this.
Posted Below.</p>
<pre><code><?php
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *'); // Remove this when Uploaded to live server. only here for CORS Warnings.
session_start();
$GuestUsr = "BaseUsr";
session_register('GuestUsr');
if (NULL || undefined || empty($_SESSION['csrf_token'])){ // Cross Site Request Forgery ::(Token.).
$_SESSION['csrf_token'] = bin2hex(random_bytes(28).openssl_random_pseudo_bytes(7));
} // Shouldn't use MD5 anymore apparently.
$_SESSION['hits']++; // Increment a very Basic Page Counter.
$_SESSION['in_Session'] = '1';
$_SESSION["is_guest"] = true;
$_SESSION["loggedIn"] = false;
$_SESSION["has_priv"] = false;
if($SESSION["is_guest"] = true){
$_SESSION["loggedIn"] = false;
} elseif ($_SESSION["loggedIn"] = true) {
$_SESSION["is_guest"] = false;
$_SESSION["has_priv"] = 1; // Will be different privaledge levels. 1>7...
};
$csrf = bin2hex(16);
$cookie = bin2hex(32);
$hashish_cookie = bin2hex(64);
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
</code></pre>
<p>Also Just Downloaded Some generic Code from PhpJabbers,
But Noticed when studying there code they have included:
@session_start() instead of the normal session_start()
that I see everywhere else. Does anybody Know what the @ does? Appart from Suppressing Warnings and Errors...
Google or PHP Docs have no reference to this?</p>
<p>Can this be made better? I saw a very complex one using regex but this is my implementation so far.</p>
<p>Having Just Read These Answers:<br>
<a href="https://codereview.stackexchange.com/questions/92263/csrf-token-implementation">CSRF implementation => SO Quest.</a><br>
I might change it to use: <code>openssl_random_pseudo_bytes(16)</code> or a combination of both.</p>
<p>Questions that I have which I still don't understand in PHP.</p>
<p>1) Is <code>$_SESSION['Tokens'];</code> a fixed list of variables
that I can call upon to do certain jobs?
Or can I make my own Up like <code>$_SESSION['MyStoredSumthing']</code>?</p>
<p>2) Are all <code>$_UPPERCASE</code> considered GLOBAL.</p>
<p>3) Currently I have My CSRF & Cookie Codes, in the head of my document,
That is included in every single page. Is this bad practice as every time a page is requested its going to be running through my php script & creating or over-riding The CSRF and/or cookie with either the same value or a different new value. if its being stored in the SESSION which makes it available to all subsequent pages. Then calling this php every page load is wrong? is this correct? I'm trying to build my pages more towards MVC but still gotta go through and get rid of all the mysql_functions.</p>
<p>4) All Mysql_functions are deprecated. Does this include mysqli?</p>
<p> Another tutorial that I watched used <code>uniqid()</code> wrapped inside of an MD5 hashing function, but from the Documents and articles that I have read MD5 is deprecated & wrapping uniqid inside of a hashing function destroys the purpose and intent of <code>uniqid()</code> which is to create a guid or as close to possible to a one time unique number..
Another part used <code>mcrypt_create_iv()</code> which is also deprecated...</p>
<p>Other Questions That I can find related to CSRF & Token generation:<br>
Update Soon. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:37:58.157",
"Id": "440257",
"Score": "1",
"body": "For this purpose I don't think you need such a complex token. Something like `random_bytes(16)` (64 bits) should be enough. I won't downvote your question, but for Code Review, there is very little code in your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:39:32.033",
"Id": "440258",
"Score": "0",
"body": "I know. I mainly just put it here because I added The NULL Part and have no way of testing if its NULL What would happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:33:19.710",
"Id": "440272",
"Score": "2",
"body": "The `NULL ||` bit doesn't do anything. You can leave it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T23:43:05.120",
"Id": "465484",
"Score": "0",
"body": "@KIKO Software Surely it is better to check whether the value is NULL or Undefined otherwise an attacker could set it to either one of these and then the part of the code that builds the csrf token would never run? ie it would just skip straight past that if statement? No?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T11:26:42.787",
"Id": "465549",
"Score": "0",
"body": "No. There is no check when you use `NULL ||` or `undefined ||`. They represent constant values which will *always* evaluate to `FALSE`. So when you say: `NULL || undefined || empty($_SESSION['csrf_token'])`, you could as well say: `FALSE || FALSE || empty($_SESSION['csrf_token'])`, or shorter: `empty($_SESSION['csrf_token'])`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T15:33:32.810",
"Id": "465580",
"Score": "0",
"body": "@KIKO Software, Ok Thank you for the Clarrification, wasn't sure if the whole if statement could just be bypassed by setting the ($SESSION['csrf_token']) value to undefined..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T15:41:08.587",
"Id": "468068",
"Score": "0",
"body": "@KIKOSoftware 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)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:01:56.877",
"Id": "226507",
"Score": "2",
"Tags": [
"php",
"security",
"web-services"
],
"Title": "CSRF script in Php"
}
|
226507
|
<p>I am writing a console application. CRUD functionality.I would like to try to apply the pattern. Is it possible to apply a "state" pattern? In the <code>AddCustomer</code> () method at the end, the call to the <code>InputMenu</code> () method, I do not think that this is correct. I would like to remake the "InputMenu", is it possible to apply the state pattern? Can I get rid of the switch case this way?</p>
<pre><code> public class DataFunction
{
readonly DataContext _dataContext = new DataContext();
public DataFunction()
{
}
public void AddCustomer()
{
Console.WriteLine("Input Name");
string _name = Console.ReadLine();
Console.WriteLine("Input Adress");
string _adress = Console.ReadLine();
_dataContext.Customers.Add(
new Customer
{
Name = _name,
Adress = _adress
});
_dataContext.SaveChanges();
InputMenu();
}
public void ShowAllCustomers()
{
Console.WriteLine("All customers in database");
Console.WriteLine();
foreach (var customer in _dataContext.Customers)
{
Console.WriteLine("ID - {0} Name - {1}, Adress - {2}", customer.CustomerId, customer.Name, customer.Adress);
}
InputMenu();
}
public void ShowAllCustomersForRemoveMethod()
{
Console.WriteLine("All customers in database");
Console.WriteLine();
foreach (var customer in _dataContext.Customers)
{
Console.WriteLine("ID - {0} Name - {1}, Adress - {2}", customer.CustomerId, customer.Name, customer.Adress);
}
}
public void RemoveCustomer()
{
Console.WriteLine();
ShowAllCustomersForRemoveMethod();
Console.WriteLine();
Console.WriteLine("Enter the number to delete the user");
Console.WriteLine();
int _id = int.Parse(Console.ReadLine());
Console.WriteLine();
Customer customer = _dataContext.Customers.Find(_id);
_dataContext.Customers.Remove(customer);
_dataContext.SaveChanges();
Console.WriteLine();
InputMenu();
}
public void InputMenu()
{
Console.WriteLine("Add Customer? --- 1, Remove customer? --- 2, Show All Customer? --- 3");
string _value = Console.ReadLine();
switch (_value)
{
case "1":
AddCustomer();
break;
case "2":
RemoveCustomer();
break;
case "3":
ShowAllCustomers();
break;
default:
Console.WriteLine("You clicked an unknown letter");
break;
}
}
}
static void Main(string[] args)
{
DataFunction dataFunction = new DataFunction();
dataFunction.InputMenu();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:43:26.133",
"Id": "440241",
"Score": "4",
"body": "Could you add the code of the remaining methods as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:46:49.807",
"Id": "440243",
"Score": "2",
"body": "I’ve voted to close this until the rest of the code is in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:56:37.963",
"Id": "440245",
"Score": "1",
"body": "I added all the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:14:31.537",
"Id": "440250",
"Score": "5",
"body": "There is one thing about your question I don't like. You are specifically requesting for a rewrite of the code to introduce the _state pattern_. This is a site for reviewing code, not for implementing patterns for you, I'm afraid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T00:25:22.590",
"Id": "440287",
"Score": "0",
"body": "Sorry, you misunderstood me, I ask if this can be done in this case? Apply State pattern? I implement everything myself"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T07:28:18.740",
"Id": "440312",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T23:33:05.510",
"Id": "440459",
"Score": "0",
"body": "@Gefest, sorry for misleading comment. I misunderstood you in the way that i thought some nicely written code needed, and that the question not necessarily related to state pattern. Not sure, but may be the state one doesn't fit 100% because next state is always same. I think that `visitor` pattern could be ok, as given in the second answer to your other question. And yes, state pattern CAN be used in this case. Sorry, may be chat room better? As it now feels like answering one bigger Q is harder then answering several smaller questions. Needed 20rep is possible as you have good Qs there."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:26:30.220",
"Id": "226510",
"Score": "1",
"Tags": [
"c#",
"design-patterns",
".net",
"console"
],
"Title": "What pattern can I use to write CRUD functionality?"
}
|
226510
|
<p>Could be useful?</p>
<pre><code>OrdinalIgnoreCase s1 = "a";
OrdinalIgnoreCase s2 = "A";
Assert.AreEqual(s1, s2);
</code></pre>
<p>Where:</p>
<pre><code>public class OrdinalIgnoreCase : IEquatable<OrdinalIgnoreCase>
{
public static StringComparer Comparer { get; } = StringComparer.OrdinalIgnoreCase;
public static implicit operator OrdinalIgnoreCase(string s) => new OrdinalIgnoreCase(s);
public static implicit operator string(OrdinalIgnoreCase s) => s.Text;
public OrdinalIgnoreCase(string text) => Text = text;
public string Text { get; }
public override int GetHashCode() => Comparer.GetHashCode(Text);
public override bool Equals(object obj) => Equals(obj as OrdinalIgnoreCase);
public virtual bool Equals(OrdinalIgnoreCase other) => Comparer.Equals(Text, other.Text);
public static bool operator ==(OrdinalIgnoreCase left, OrdinalIgnoreCase right) =>
Equals(left, right);
public static bool operator !=(OrdinalIgnoreCase left, OrdinalIgnoreCase right) =>
!Equals(left, right);
public override string ToString() => Text;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:46:17.857",
"Id": "440242",
"Score": "2",
"body": "It's super useful. I call it a [`SoftString`](https://github.com/he-dev/reusable/blob/dev/Reusable.Core/src/SoftString.cs) and also trim the input. I hate bugs caused by case sensitivity and leading/trailing whitespace. This prevents a lot of trouble."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:54:26.580",
"Id": "440244",
"Score": "2",
"body": "I wish to have String<TComparer> but there is no dedicated StringComparer specialization types in .NET for things like OrdinalIgnoreCase and C# support for static class API in templates is really bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:56:50.383",
"Id": "440246",
"Score": "3",
"body": "My only comment would be that the implicit cast to `string` means it may be possible to use it in a situation where it isn't ordinal and ignoring case by accident, so I'd be tempted to remove it (but then I'd probably complain about how much effort it is to call `ToString()`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T06:02:17.123",
"Id": "440308",
"Score": "3",
"body": "@VisualMelon that's exactly the reason why I removed it from my implementation. It would be too easy to _downgrade_ this class into a normal string and transparently loose all the benfits. It'd be also unconventional to do so because implicitly casting to string would mean to _loose precision_. It's the same with `double --> int`, there is also no implicit conversion. You have to actively cast it. Using `ToString` is indeed not pretty but better less pretty then full of weird bugs ;-]"
}
] |
[
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>I see no reason not to seal this class. No need for virtual methods.</li>\n<li>You prefer readability over argument checks: <code>Comparer.Equals(Text, other.Text)</code></li>\n<li>I would make <code>!=</code> the opposite of <code>==</code> as blackbox: <code>!(left == right);</code></li>\n<li>If you want to be a bit more resilient to unicode shenanigans, you should do <code>text.Normalize();</code> (<code>á</code> is not always <code>á</code>, unless you normalize)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:58:16.620",
"Id": "440247",
"Score": "1",
"body": "@t3chb0t this last step might be something for your SoftString. Don't know if you work with unicode.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T05:59:08.147",
"Id": "440307",
"Score": "2",
"body": "I always hope I can get away with _not exactly knowing how encodigs work_ - I'll keep the normalization in mind in case it should bite me one day ;-]"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:41:04.147",
"Id": "226513",
"ParentId": "226511",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226513",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T18:31:25.963",
"Id": "226511",
"Score": "3",
"Tags": [
"c#"
],
"Title": "OrdinalIgnoreCase helper"
}
|
226511
|
<p>I have this code that asks the user for inputs and validates the inputs if they are Integers (no other inputs are allowed). I'd like to ask for some help in terms of elegance of the code or performance, or just the overall code. </p>
<p>Also, I have found myself repeating these lines of code </p>
<pre><code>Console.Write("Enter weight of parcel: ");
string input = Console.ReadLine();
</code></pre>
<p>and I think I really need to refactor the code because of this, but can't think of a simple and straightforward way to refactor it.</p>
<p>Here is my code below:</p>
<pre><code>class Program
{
private static int _depth = 0;
private static int _height = 0;
private static int _weight = 0;
private static int _width = 0;
private static bool _isInvalidInput = true;
static void Main(string[] args)
{
GetWeightInput();
GetHeightInput();
GetWidthInput();
GetDepthInput();
Console.ReadLine();
}
private static void GetWeightInput()
{
while(_isInvalidInput)
{
Console.Write("Enter weight of parcel: ");
string input = Console.ReadLine();
#region User Weight Input Validation
if (int.TryParse(input, out _weight))
{
_isInvalidInput = false;
//TODO: Add More Validations of User Input
}
else
{
Console.WriteLine("***Only Integer Inputs Are Allowed***");
_isInvalidInput = true;
}
#endregion User Weight Input Validation
}
_isInvalidInput = true;//reset value to true
}
private static void GetHeightInput()
{
while (_isInvalidInput)
{
Console.Write("Enter weight of parcel: ");
string input = Console.ReadLine();
#region User Weight Input Validation
if (int.TryParse(input, out _height))
{
_isInvalidInput = false;
//TODO: Add More Validations of User Input
}
else
{
Console.WriteLine("***Only Integer Inputs Are Allowed***");
_isInvalidInput = true;
}
#endregion User Weight Input Validation
}
_isInvalidInput = true;//reset value to true
}
private static void GetWidthInput()
{
while (_isInvalidInput)
{
Console.Write("Enter weight of parcel: ");
string input = Console.ReadLine();
#region User Weight Input Validation
if (int.TryParse(input, out _width))
{
_isInvalidInput = false;
//TODO: Add More Validations of User Input
}
else
{
Console.WriteLine("***Only Integer Inputs Are Allowed***");
_isInvalidInput = true;
}
#endregion User Weight Input Validation
}
_isInvalidInput = true;//reset value to true
}
private static void GetDepthInput()
{
while (_isInvalidInput)
{
Console.Write("Enter weight of parcel: ");
string input = Console.ReadLine();
#region User Weight Input Validation
if (int.TryParse(input, out _width))
{
_isInvalidInput = false;
//TODO: Add More Validations of User Input
}
else
{
Console.WriteLine("***Only Integer Inputs Are Allowed***");
_isInvalidInput = true;
}
#endregion User Weight Input Validation
}
_isInvalidInput = true;//reset value to true
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:25:54.150",
"Id": "440252",
"Score": "4",
"body": "Are you familiar with method parameters and return values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:28:31.193",
"Id": "440253",
"Score": "0",
"body": "yeah, I tried that but unfortunately,I made it messier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:54:26.607",
"Id": "440275",
"Score": "3",
"body": "As you grow as a programmer, you may want to consider adding things like units of measure. \"Enter weight of parcel:\" would that be ounces, grams, or pounds? Also, why not double instead of integer. What if something is 1.5 ounces?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T02:49:53.790",
"Id": "440299",
"Score": "0",
"body": "well yeah @Rick Davin, I actually thought about using double instead of integer but the criteria and scope of this sample code is to use integer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T12:48:18.350",
"Id": "440349",
"Score": "1",
"body": "Somehow similar: https://codereview.stackexchange.com/q/104184/13424"
}
] |
[
{
"body": "<p>As you suggested, you have a lot of redundant code. And rightfully so you want to adhere to the DRY principle.</p>\n\n<p>All these input methods have the same pattern internally..</p>\n\n<blockquote>\n<pre><code>static void Main(string[] args)\n{\n GetWeightInput();\n GetHeightInput();\n GetWidthInput();\n GetDepthInput();\n\n Console.ReadLine();\n}\n</code></pre>\n</blockquote>\n\n<h3>Road to DRY</h3>\n\n<p>..ideally you would like to be able to call them like this:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var weight = AskInteger(\"Enter weight of parcel: \");\n var height = AskInteger(\"Enter height of parcel: \");\n var width = AskInteger(\"Enter width of parcel: \");\n var depth = AskInteger(\"Enter depth of parcel: \");\n\n Console.WriteLine(\"press any key to terminate the application..\");\n Console.ReadKey(true);\n}\n</code></pre>\n\n<h3>Advanced road to DRY</h3>\n\n<p>Or if you would provide a complex object <code>Request</code> with 4 properties and a lambda to provide both a message to the user as a setter expression to materialise the request:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var request = new Request();\n AskInteger(request, x => x.Weight);\n AskInteger(request, x => x.Height);\n AskInteger(request, x => x.Width);\n AskInteger(request, x => x.Depth);\n\n Console.WriteLine(\"press any key to terminate the application..\");\n Console.ReadKey(true);\n}\n</code></pre>\n\n<p>How you would implement <code>AskInteger</code> is a challenge I leave to you.</p>\n\n<hr>\n\n<h3>Misc</h3>\n\n<ul>\n<li>Don't pollute your code with regions that have no added value. <code>#region User Weight Input Validation</code></li>\n<li>Try to avoid meaningless comments <code>_isInvalidInput = true;//reset value to true</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:35:18.463",
"Id": "440256",
"Score": "2",
"body": "woahhh,dude I really appreciate this one. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:42:55.497",
"Id": "440260",
"Score": "2",
"body": "Beat me to it as usual, but you should use `ReadKey(true)` if you want to press any key to terminate ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:53:06.457",
"Id": "440261",
"Score": "0",
"body": "@VisualMelon Well, if I have to chase you, I rarely catch you ;-) I'll take a break now :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:51:57.933",
"Id": "440274",
"Score": "1",
"body": "@doctorWeird Next challenge for you would be to modify these methods to include a low and high limit for when you might modify your app to say \"Enter a number between 1 and 10:\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T05:56:14.027",
"Id": "440306",
"Score": "1",
"body": "@VisualMelon _`true` to not display the pressed key_ - what a logic ;-] I would expect `false` to have this effect."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:32:10.147",
"Id": "226518",
"ParentId": "226515",
"Score": "11"
}
},
{
"body": "<p>In <code>GetWidthInput</code> the prompt is: \"enter weight of parcel:\". This is clearly wrong.</p>\n\n<p>To see whether it's worth merging all the code into a single function you should first fill in the missing TODOs for validating the numbers to see whether the code structure stays the same. It probably does. After that, the custom validation code can be added via an anonymous function as well, as explained in the other answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T06:15:52.877",
"Id": "226542",
"ParentId": "226515",
"Score": "3"
}
},
{
"body": "<p>There are already good reviews, but there are some other points that should be addressed.</p>\n\n<p>You don't need to use global <code>static</code> variables in your case. Your methods should only use local variables because you always reset your variables in your methods, which makes the global variables useless. A method named <code>Get...</code> should always return something, it just makes sense.</p>\n\n<p>Second, it's a bad practice to have boolean variables that represent negative conditions. I mean that it's confusing to have <code>isInvalidInput = false</code> instead of <code>isValidInput = true</code>. It's most of the time clearer to use positive variables. If you used the <code>break</code> keyword, you could skip the use of the <code>isInvalidInput</code> <em>and</em> remove the else in your code. You can also (assuming you're using C#7) use <code>out int width</code> instead of declaring <code>int width</code> then use the <code>out</code> variable. Lastly, the word <code>integer</code> means something to developers, but not that much to non-IT people. If your program is used by non IT people, you should consider rephrasing it.</p>\n\n<p>Final version : </p>\n\n<pre><code>private static int GetDepthInput()\n{\n while (true)\n {\n Console.Write(\"Enter weight of parcel: \");\n string input = Console.ReadLine();\n\n if (int.TryParse(input, out int width))\n {\n break;\n }\n\n Console.WriteLine(\"***The input is invalid. (Decimal numbers aren't allowed)***\");\n }\n\n return input;\n}\n</code></pre>\n\n<p>I didn't address the other points that are written in the other 2 reviews but I also think they should be implemented.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T17:38:39.893",
"Id": "226580",
"ParentId": "226515",
"Score": "2"
}
},
{
"body": "<p>To me, since a parcel is an object, you should make it an <code>Object</code>:</p>\n\n<pre><code>class Parcel\n{\n int Weight { get; set; }\n int Height { get; set; }\n int Width { get; set; }\n int Depth { get; set; }\n public Parcel() { }\n\n\n}\n</code></pre>\n\n<p>One way to gather the inputs and fill the object with them, is to use a <code>Builder</code>. </p>\n\n<p>To cut down on a lot of the repetition, you can store the prompts in a string array:</p>\n\n<pre><code>private static readonly string[] DimensionsPrompts = new string[]\n{\n \"Enter weight of parcel: \",\n \"Enter height of parcel: \",\n \"Enter width of parcel: \",\n \"Enter depth of parcel: \"\n};\n</code></pre>\n\n<p>To facilitate the builder you'll also need a constructor that takes an int[].</p>\n\n<p>The builder could look like this:</p>\n\n<pre><code>public static Parcel BuildParcel(string[] prompts, TextWriter sOut, TextReader sIn)\n{\n if (prompts.Length < 4)\n {\n throw new ArgumentException(\"`prompts` must have 4 elements\");\n }\n int[] values = new int[4];\n for(int i = 0; i < 4; ++i)\n {\n sOut.Write(prompts[i]);\n bool correct = false;\n while (!correct)\n {\n correct = int.TryParse(sIn.ReadLine(), out values[i]);\n if (!correct)\n {\n sOut.WriteLine(\"Input must an integer, Try again\");\n }\n }\n }\n return new Parcel(values);\n}\n</code></pre>\n\n<p>The whole thing could look like this:</p>\n\n<pre><code>class Parcel\n{\n int Weight { get; set; }\n int Height { get; set; }\n int Width { get; set; }\n int Depth { get; set; }\n public Parcel() { }\n public Parcel(params int[] values)\n {\n if(values.Length < 4)\n {\n throw new ArgumentException(\"`values` must have 4 elements\");\n }\n Weight = values[0];\n Height = values[1];\n Width = values[2];\n Depth = values[3];\n }\n\n public static Parcel BuildParcel(string[] prompts, TextWriter sOut, TextReader sIn)\n {\n if (prompts.Length < 4)\n {\n throw new ArgumentException(\"`values` must have 4 elements\");\n }\n int[] values = new int[4];\n for(int i = 0; i < 4; ++i)\n {\n sOut.Write(prompts[i]);\n bool correct = false;\n while (!correct)\n {\n correct = int.TryParse(sIn.ReadLine(), out values[i]);\n if (!correct)\n {\n sOut.WriteLine(\"Input must an integer, Try again\");\n }\n }\n }\n return new Parcel(values);\n }\n}\n\nprivate static readonly string[] DimensionsPrompts = new string[]\n{\n \"Enter weight of parcel: \",\n \"Enter height of parcel: \",\n \"Enter width of parcel: \",\n \"Enter depth of parcel: \"\n};\n</code></pre>\n\n<p>One advantage to using a class like this, you can easily add a method that will calculate the base cost, based on its properties</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T18:42:47.047",
"Id": "226585",
"ParentId": "226515",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:14:24.607",
"Id": "226515",
"Score": "10",
"Tags": [
"c#",
"validation",
"console"
],
"Title": "Repetitive validation of Console inputs"
}
|
226515
|
<p>Today after watching a getting started course about React, I tried to code my very first React component, a "treeview" as the title says. It does work, but as a newbie I know there are many improvement that can be done. </p>
<p>It receives a data array like the one below:</p>
<pre><code>[{
descp: 'UNE',
url: '/tree/une',
icon: 'icon-list',
children: [
{
descp: 'ATI',
url: '/tree/une/ati',
icon: 'icon-layers',
children: [{
descp: 'ATI-VC',
url: '/tree/une/ati/ativc',
icon: 'icon-pin',
children: []
},
{
descp: 'ATI-CMG',
url: '/tree/une/ati/aticmg',
icon: 'icon-pin',
children: []
}
]
},
{
descp: 'EMGEF',
url: '/tree/une/emgef',
icon: 'icon-layers',
children: []
},
{
descp: 'ECIE',
url: '/tree/une/ecie',
icon: 'icon-layers',
children: []
},
{
descp: 'GEYSEL',
url: '/tree/une/geysel',
icon: 'icon-layers',
children: []
}
]
}]
</code></pre>
<p>Maybe the data format can be improve as well but the real deal is the component:</p>
<pre><code>const MyTree = (props) => {
const { list } = props;
return (
list.map((child,i)=>
<MyTreeNestedItems key={i} data={child} />
)
);
};
const MyTreeNestedItems = (props) => {
const { data } = props;
const createChildren = (list) => {
return (
list.map((child,i)=>
<MyTreeNestedItems key={i} data={child} />
)
)
}
let children = null;
if (data.children.length) {
children = createChildren(data.children);
}
return (
<li className="nav-item">
<a className="nav-link" href="#">
<span className={data.icon}></span> {" "}
{ data.descp }
</a>
<ul style={{listStyleType:"none"}}>{children}</ul>
</li>
);
};
render(<MyTree list={tree} />,document.querySelector('.js-mytree'));
</code></pre>
<p>Any tips would be gratefully appreciated.</p>
|
[] |
[
{
"body": "<p>You might notice that <code>createChildren</code> is almost the same as <code>MyTree</code> -- the only difference is that <code>createChildren</code> takes its argument directly instead of as a props object. So with a small change we can remove <code>createChildren</code> entirely:</p>\n\n<pre><code>const MyTreeNestedItems = (props) => {\n const { data } = props;\n\n let children = null;\n if (data.children.length) {\n children = <MyTree list={data.children} />;\n }\n\n return (\n <li className=\"nav-item\">\n <a className=\"nav-link\" href=\"#\">\n <span className={data.icon}></span> {\" \"}\n { data.descp }\n </a>\n <ul style={{listStyleType:\"none\"}}>{children}</ul>\n </li>\n );\n}\n</code></pre>\n\n<p>This can be a bit more compact as so:</p>\n\n<pre><code>const MyTreeNestedItems = ({ data }) => {\n return (\n <li className=\"nav-item\">\n <a className=\"nav-link\" href=\"#\">\n <span className={data.icon}></span> {\" \"}\n { data.descp }\n </a>\n <ul style={{listStyleType:\"none\"}}>\n {data.children.length ? <MyTree list={data.children} /> : null}\n </ul>\n </li>\n );\n};\n</code></pre>\n\n<hr>\n\n<p>Currently this code renders invalid HTML -- it renders with a <code><li></code> as the top level element but <code><li></code> should only be contained in a <code><ul></code>, <code><ol></code>, or <code><menu></code>.</p>\n\n<p>Looking at the code so far, <code><MyTree></code> is rendered in two places -- it may be tempting to just add another <code><ul></code> around <code><MyTree list={tree} /></code> in the <code>render()</code> call. But then we would have two occurrences of a structure like this: <code><ul><MyTree/></ul></code>. It'd be easier to just move the <code><ul></code> into the <code><MyTree/></code>.</p>\n\n<p>With that, the code now looks like this:</p>\n\n<pre><code>const MyTree = ({ list }) => {\n return (\n <ul style={{listStyleType:\"none\"}}>\n {list.map((child,i)=> <MyTreeNestedItems key={i} data={child} />)}\n </ul>\n );\n};\n\nconst MyTreeNestedItems = ({ data }) => {\n return (\n <li className=\"nav-item\">\n <a className=\"nav-link\" href=\"#\">\n <span className={data.icon}></span> {\" \"}\n { data.descp }\n </a>\n {data.children.length ? <MyTree list={data.children} /> : null}\n </li>\n );\n};\n\nrender(<MyTree list={tree} />, document.querySelector('.js-mytree'));\n</code></pre>\n\n<hr>\n\n<p>From here it's a matter of taste. Both of the components are just directly returning a value, so we can use short arrow function syntax now: <code>(...) => (value)</code> instead of <code>(...) => { return (value); }</code></p>\n\n<p>Also, the components are now simple enough that I would just combine the two.</p>\n\n<p>All in, that leaves us with this final version of the code:</p>\n\n<pre><code>const MyTree = ({ list }) => (\n <ul style={{listStyleType:\"none\"}}>\n {list.map(({icon, descp, children}, i) => (\n <li className=\"nav-item\" key={i}>\n <a className=\"nav-link\" href=\"#\">\n <span className={icon} /> {descp}\n </a>\n {children.length ? <MyTree list={children} /> : null}\n </li>\n ))}\n </ul>\n);\n\nrender(<MyTree list={tree} />, document.querySelector('.js-mytree'));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T11:21:39.290",
"Id": "440339",
"Score": "0",
"body": "Thanks a lot George, that's a great improvement of my code and explanation. Now in a few days I will be focusing on implementing collapse/expand functionality to the component."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T07:34:55.017",
"Id": "226548",
"ParentId": "226521",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226548",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T19:52:47.083",
"Id": "226521",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"jsx"
],
"Title": "Implementing a Treeview component using React"
}
|
226521
|
<p>After taking advice from <a href="https://codereview.stackexchange.com/users/25834/reinderien">Reinderien</a>, I have completely rewritten the code for my <code>Window()</code> subclass.</p>
<p>EDIT *reason for posting was unclear:</p>
<p>I would like for someone to suggest improvements or other features to add to this subclass. Either that, or give a general review.</p>
<p>EDIT *compatibility bug:</p>
<p>In <code>root.config()</code>, I changed <code>root.title</code> to <code>root.title_string</code> because it replaced the <code>title()</code> function, which is used by other tkinter widget functions (eg. <code>tkinter.simpledialog.askstring()</code>)</p>
<h1>Features:</h1>
<ul>
<li><p>settings-file interaction for persistent application settings</p></li>
<li><p>fullscreen functionality using F11, can be persistent or defaulted</p></li>
<li><p>removes the need for multiple <code>root.configure()</code> statements</p></li>
<li><p>removes the need for <code>root.title()</code> and <code>root.row/columnconfigure()</code></p></li>
</ul>
<p>You can adjust the default window by calling it using the <code>Window()</code> class, and then you can use two methods to adjust the settings file (which will be named <code>settings.ini</code> by default).</p>
<ul>
<li><p><code>root.set()</code> configures all of the software options found in <code>settings.ini</code> in realtime.</p></li>
<li><p><code>root.get()</code> returns a list with the settings you want to reference from <code>settings.ini</code></p></li>
<li><p>you can supply multiple arguments to both of these methods</p></li>
</ul>
<p>One thing that this subclass fixes is the need for multiple <code>root.configure()</code> statements. It uses a new method, <code>root.config()</code>, that loops through each keyword argument supplied and runs the appropriate configurations.</p>
<ul>
<li>this method also handles the <code>title()</code> and <code>row/columnconfigure()</code> functions in this format:</li>
</ul>
<pre class="lang-py prettyprint-override"><code>root = Window()
root.config(bg = 'black', title = 'My Window', row = (0, 1), col = (0, 1))
root.mainloop()
</code></pre>
<p>This creates a basic window with a black background, a title ("My Window"), and row 0 and column 0 are set to weight = 1.</p>
<h1>Changes:</h1>
<ul>
<li><p>comment convention has been improved</p></li>
<li><p>Exceptions are printed if present</p></li>
<li><p>files are handled in a cleaner fashion</p></li>
<li><p>default <code>settings.ini</code> contents are now a dictionary</p></li>
<li><p><code>root.get()</code> no longer requires pointing to a dictionary key, as it now returns a list</p></li>
<li><p>string-booleans are fixed as a result of the above change</p></li>
<li><p>less return functions are used</p></li>
<li><p>new <code>shortHand()</code> function to prevent ridiculous copy/pasting in <code>root.set()</code></p></li>
<li><p><code>args</code> in <code>root.get()</code> are now handled via a dictionary</p></li>
<li><p>no <code>except: pass</code></p></li>
<li><p>new options: <code>instaquit=False</code> and <code>fullscreenable=True</code></p></li>
</ul>
<p><b>The code for this <code>Window()</code> class is below, along with an example setup. You can simply copy/paste this into your editor and it'll run as a standalone.</b></p>
<pre class="lang-py prettyprint-override"><code>import tkinter as tk
from tkinter import messagebox
import os
class Window(tk.Tk):
def __init__(self, settings_file = './settings.ini'):
self.window = super(); self.window.__init__()
self.window.protocol('WM_DELETE_WINDOW', self.close)
# the settings file is where your window properties are held
# you can change the file name and type when you create a Window()
self.file = settings_file
# create your default settings file here
# give section markers a value of None
default_settings = {
'; ux settings': None,
'instaquit': False,
'; display settings': None,
'fullscreenable': True,
'fullscreen': False,
'resolution': '720x480',
'screenres': f'{self.winfo_screenwidth()}'
f'x{self.winfo_screenheight()}',
'resizex': False,
'resizey': False,
'; font settings': None,
'fontfamily': 'TkDefaultFont',
'fontsize': 12
}
# checking if settings file exists
with open(self.file, 'a+') as f:
def writeDefaults():
# write/format default settings from dictionary
for key, value in default_settings.items():
# if a value exists, get it as a string
if value != None: value = str(value)
# if value is None, section off with new lines
else: value = '\n'; key = '\n' + key
# case a: no value - surround in new lines
# case b: value - add equals sign and write pair
formatted_content = (
f'''{key}{
'=' if not
value.isspace()
else ''
}{value}'''
+ '\n'
)
# add formatted settings to self.settings and file
self.settings = [].append(formatted_content)
f.write(formatted_content)
# if the file is empty, write the default contents
if not bool(f.tell()):
writeDefaults()
# read file contents
f.seek(0)
self.settings = f.readlines()
#print('settings loaded:\n', ''.join(self.settings))
self.update()
# this function refreshes the window and its properties
def update(self):
with open(self.file) as f:
self.settings = f.readlines()
self.font = (self.get('fontf'),
self.get('fonts'))
self.window.resizable(self.get('rx'),
self.get('ry'))
self.window.geometry(self.get('res'))
self.window.overrideredirect(0)
# check if the window is fullscreen
if self.get('fs'):
self.window.geometry(self.get('screenres'))
self.toggleFullscreen(None)
# check if the window is allowed to switch modes
if self.get('fsable'):
self.window.bind('<F11>', self.toggleFullscreen)
else:
self.window.bind('<F11>', None)
# this function toggles the window to fullscreen or normal
def toggleFullscreen(self, event=None):
# if the user pressed F11
if event:
if self.get('fs'):
# set fullscreen to False
self.set(fs = False)
self.window.overrideredirect(0)
else:
# set fullscreen to True
self.set(fs = True)
self.window.overrideredirect(1)
self.window.geometry(self.get('screenres') + '+0+0')
# if the toggle was hard-coded
else:
if self.get('fs'):
self.window.overrideredirect(1)
self.window.geometry(self.get('screenres') + '+0+0')
else:
self.window.overrideredirect(0)
self.window.update()
# last-minute cleanup before closing the window
def close(self, event=None):
# instaquit not recommended for most programs, but the option is there
if not self.get('iquit'):
if messagebox.askokcancel('Exit Program',
'Are you sure you want to exit?'):
self.window.destroy()
self.window.destroy()
#
# set the values in the settings file
def set(self, **kwargs):
# shorthands for the set command
def shortHand(short_name, long_name):
if short_name in kwargs:
kwargs[long_name] = kwargs.pop(short_name)
shortHand('iquit', 'instaquit'); shortHand('fsable', 'fullscreenable')
shortHand('fs', 'fullscreen'); shortHand('res', 'resolution')
shortHand('rx', 'resizex'); shortHand('ry', 'resizey')
for i in kwargs:
for n, j in enumerate(self.settings):
if j.lower()[:j.find('=')] == i:
j = j.replace(
j[j.find('=')+1:],
str(kwargs[i]) + '\n'
)
self.settings[n] = j
with open(self.file, 'w') as f:
for i in self.settings:
f.write(i)
self.update()
# search through settings and pull chosen values
def get(self, *args):
# shorthands for the get command
shorthands = {
'iquit': 'instaquit',
'fsable': 'fullscreenable',
'fs': 'fullscreen',
'res': 'resolution',
'rx': 'resizex',
'ry': 'resizey',
'fontf': 'fontfamily',
'fonts': 'fontsize'
}
args = [shorthands.get(x, x) for x in args]
results = []
for value in args:
for i, j in enumerate(self.settings):
# check for matching text before equals sign
if j[:j.find('=')] == value:
# append value of match
results.append(j[j.find('=')+1:].strip())
if len(results) == 1:
return (results[0] if results[0]
not in ['True', 'False']
else eval(results[0]))
return results
def config(self, **kwargs):
# title the window
if 'title' in kwargs:
self.title_string = kwargs['title']
self.window.title(kwargs.pop('title'))
# row configure
if 'row' in kwargs:
self.window.rowconfigure(kwargs['row'][0],
weight = kwargs['row'][1])
kwargs.pop('row')
# column configure
if 'column' in kwargs or 'col' in kwargs:
try:
kwargs['column'] = kwargs.pop('col')
except Exception as e: print(e)
self.window.columnconfigure(kwargs['column'][0],
weight = kwargs['column'][1])
kwargs.pop('column')
self.window.configure(**kwargs)
# the following is an example to show how this class is used
root = Window()
root.set(fs=False, res='240x160',
rx=False, ry=False,
fsable=True, iquit=True,
fonts=32)
root.config(bg='black',
bd=12,
relief=tk.SUNKEN,
title='Window')
label = tk.Label(root, text='test', fg='white',
bg=root['bg'], font=root.font)
label.pack(fill = tk.BOTH, expand=True)
root.mainloop()
</code></pre>
<p>So many changes were made today that I didn't pick up on much that I seek to immediately improve, but you may find something I've missed, so please let me know!</p>
<p>As I said in my last post, I wanted to make this as a way of speeding up the rudimentary GUI creation process, and hopefully it can be used to get the ugly stuff out of the way faster.</p>
|
[] |
[
{
"body": "<p>Some improvement, but there's still more :)</p>\n\n<h2>Don't semicolon-delimit statements</h2>\n\n<pre><code>self.window = super(); self.window.__init__()\n</code></pre>\n\n<p>There's nearly never a good reason to do this. Just use two lines.</p>\n\n<h2>.ini support</h2>\n\n<p><a href=\"https://docs.python.org/3/library/configparser.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/configparser.html</a> is what you should be using instead of manual parsing for an actual .ini file.</p>\n\n<h2>Inline functions</h2>\n\n<p>Your <code>writeDefaults</code> is a closure: it's a function that can access the variables in the scope of its parent function. There are some scenarios where that's called for, but this isn't one of them. You're better off moving it to a <code>write_defaults</code> (Python doesn't recommend camelCase) on the class. If there is any state it requires to function, such as <code>default_settings</code>, put that either in the function itself or as a member of the class.</p>\n\n<h2><code>None</code> comparison</h2>\n\n<p>This:</p>\n\n<pre><code>if value != None: value = str(value)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if value is not None:\n value = str(value)\n</code></pre>\n\n<h2>f-strings</h2>\n\n<p>...are great, but there's a limit to the amount of stuff that you should actually do in interpolation blocks. This:</p>\n\n<pre><code> formatted_content = (\n f'''{key}{\n\n '=' if not\n value.isspace()\n else ''\n\n }{value}'''\n\n + '\\n'\n )\n</code></pre>\n\n<p>should really just set a variable first, and invert its logic, i.e.</p>\n\n<pre><code>sep = '' if value.isspace() else '='\nformatted_content = f'{key}{sep}{value}\\n'\n</code></pre>\n\n<p>...but that all goes away when you use <code>configparser</code>.</p>\n\n<h2>List literals</h2>\n\n<p>This:</p>\n\n<pre><code>[].append(formatted_content)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>[formatted_content]\n</code></pre>\n\n<h2>Casting to bool</h2>\n\n<p>In this context there's no need:</p>\n\n<pre><code>if not bool(f.tell()):\n</code></pre>\n\n<p>simply write</p>\n\n<pre><code>if not f.tell():\n</code></pre>\n\n<h2>Use <code>split</code></h2>\n\n<pre><code>j.lower()[:j.find('=')] == i:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>j.lower().split('=', 1)[0] == i:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T11:50:21.100",
"Id": "440342",
"Score": "0",
"body": "Cool, thanks again for your help! I implemented all of the changes you described, and I only left out ```configparser``` since I don't know if the end-user will always use INI files. You've been a huge help, thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T21:38:41.757",
"Id": "226526",
"ParentId": "226523",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226526",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:00:05.230",
"Id": "226523",
"Score": "2",
"Tags": [
"python",
"gui",
"tkinter",
"framework",
"tk"
],
"Title": "Adding more functionality to tkinter for projects (Revised)"
}
|
226523
|
<p>i have the following json object</p>
<pre><code> const file = [
{
"seatNumber": "1A",
"price": "£19.99",
"available": true,
"disabilityAccessible": true
},
{
"seatNumber": "2A",
"price": "£19.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "3A",
"price": "£19.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "4A",
"price": "£19.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "5A",
"price": "£19.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "1B",
"price": "£12.99",
"available": true,
"disabilityAccessible": true
},
{
"seatNumber": "2B",
"price": "£12.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "3B",
"price": "£12.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "4B",
"price": "£12.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "5B",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "1C",
"price": "£12.99",
"available": true,
"disabilityAccessible": true
},
{
"seatNumber": "2C",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "3C",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "4C",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "5C",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "1D",
"price": "£12.99",
"available": true,
"disabilityAccessible": true
},
{
"seatNumber": "2D",
"price": "£12.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "3D",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "4D",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "5D",
"price": "£12.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "1E",
"price": "£8.99",
"available": true,
"disabilityAccessible": true
},
{
"seatNumber": "2E",
"price": "£8.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "3E",
"price": "£8.99",
"available": false,
"disabilityAccessible": false
},
{
"seatNumber": "4E",
"price": "£8.99",
"available": true,
"disabilityAccessible": false
},
{
"seatNumber": "5E",
"price": "£8.99",
"available": false,
"disabilityAccessible": false
}
]
</code></pre>
<p>I am trying to display <code>seatNumber</code> of the cheapest objects. so far i have the following which works but would like to know if there is a better way following big o notation in es6 format</p>
<pre><code>const seats = file.filter( seat => seat.price.replace(/[^0-9.-]+/g,"") == Math.min(...file.map(function ( seat ) { return Number(seat.price.replace(/[^0-9.-]+/g,"")) }) ) ).map(seat => seat.seatNumber);
console.log(seats)
</code></pre>
<p>output is </p>
<p><code>[ '1E', '2E', '3E', '4E', '5E' ]</code></p>
|
[] |
[
{
"body": "<h2>Following the little big O.</h2>\n<p>You ask</p>\n<blockquote>\n<p><em>"...if there is a better way following big o notation..."</em> (?)</p>\n</blockquote>\n<p>Big O notation is a formalized mathematical convention used to express how a function (mathematical function) behaves as it approaches infinity.</p>\n<p>It is used in computer science to classify an algorithms complexity in regard to a definable input metric, usually the size of the input array when dealing with arrays.</p>\n<p>You can not "follow" big O notation as it provides no insight into how to reduce an algorithms complexity apart from a comparison.</p>\n<h2>Find the big O</h2>\n<p>To classify your function using Big O, first we need to make it at least readable, and convert it to a function. See snippet.</p>\n<p>Now count the number of times the function loops over each item in the input array data. Experience lets you do this in your head, but to demonstrate we modify the function to count every time you handle an item in the input array.</p>\n<p>Because we need to fit a curve we need at least 3 different input sizes which I do with some random data.</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 bestSeats(data) {\n var c = 0; // the counter\n const seats = data.filter( seat => \n (c++, // count the filter iterations\n seat.price.replace(/[^0-9.-]+/g, \"\") == Math.min(\n ...data.map(function ( seat ) { \n c += 2; // this counts as two\n // once each to map to the arguments of Math.min\n // once each to find the min \n return Number(seat.price.replace(/[^0-9.-]+/g, \"\")) \n }\n )\n ))).map(seat => (\n c++, // count each result\n seat.seat\n )); \n return \"O(n) = O(\" + data.length + \") = \" + c;\n}\n\nfunction randomData(size) { \n const data = [];\n while (size--) { data.push({seat:size, price: \"$\"+(Math.random() * 100 | 0)})}\n return data;\n}\nconsole.log(\"Eval complexity A:\" + bestSeats(randomData(10)));\nconsole.log(\"Eval complexity B:\" + bestSeats(randomData(100)));\nconsole.log(\"Eval complexity C:\" + bestSeats(randomData(500)));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The 3 points we can use to find the curve that best fits</p>\n<pre><code> O(10) ~= 211\n O(100) ~= 20,102\n O(500) ~= 500,005\n</code></pre>\n<p>Experience tells me it's a polynomial of some (not too high) order. Using a graphing calculator I found a reasonable fits at 2.15 making your functions big O complexity</p>\n<h2><span class=\"math-container\">\\$O(n^{2.15})\\$</span></h2>\n<p>Which is insanely inefficient. OMDG!!!!</p>\n<p>So keeping</p>\n<blockquote>\n<p><em>"...in es6 format"</em> (?)</p>\n</blockquote>\n<p>in mind a cleaner more readable, less CO2 producing sea level rising approach is to do a two pass scan of the seats. The first pass finds the min price, the second extracts the min price seat numbers.</p>\n<p>This example uses <code>for of</code> loops rather than the <code>Array</code> methods like <code>filter</code> and <code>map</code>, because these array methods have a nasty way of blinding people to the insane level of complexity of what they do, and <code>for of</code> is a little quicker and often allows better optimizations than the array methods, so it's win win for <code>for of</code></p>\n<h2>Examples in <span class=\"math-container\">\\$O(n)\\$</span> linear time.</h2>\n<pre><code> function bestSeats(seats) {\n var min = Infinity, minVal;\n const result = [];\n for (const seat of seats) {\n const price = Number(seat.price.slice(1));\n if (price < min) {\n min = price;\n minVal = seat.price;\n }\n }\n for (const seat of seats) {\n if (seat.price === minVal) { result.push(seat.seatNumber) }\n }\n return result;\n }\n</code></pre>\n<p>And if you must use the array methods.</p>\n<pre><code> function bestSeats(seats) {\n const price2Num = seat => Number(seat.price.slice(1));\n const min = (min, seat) => price2Num(seat) < min ? price2Num(seat) : min;\n const minPrice = "$" + seats.reduce(min, Infinity);\n return seats.filter(seat => seat.price === minPrice).map(seat => seat.seatNumber);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T04:35:25.633",
"Id": "440301",
"Score": "0",
"body": "Wouldn't it be possible to cache the seats with min value as we go in the first loop making it O(n)? Now it looks O(2*n) to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T10:52:55.730",
"Id": "440335",
"Score": "2",
"body": "@dfhwze O(2n) is the same as O(n), both are linear and the scalar 2 is never included in Big O notation as it becomes insignificant as we approach infinity.Yes a single pass O(n) solution can use a `Map` to hold each price category filing in the cats as you check each value, returning the min cat. Personally that should be part of the data query (pre processed index by price) and then searching only prices categories could make it O(n^c) 0<c<1 (being less complex than O(n)) if price category count had that relationship to seat count. Could even be O(1) if the price categories count is fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T10:54:08.010",
"Id": "440336",
"Score": "0",
"body": "Thanks for this thorough clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:51:29.923",
"Id": "440412",
"Score": "0",
"body": "should i use the above answer? @Blindman67 confused me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T19:45:36.387",
"Id": "440443",
"Score": "0",
"body": "@shorif2000 You are under no obligation to accept an answer, you are free to undo accepted answers if you feel the answer has not helped you. A question without an accepted answer is much more likely to get another answer, an answer that may better address your needs, which is after-all what this site is for. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T01:33:53.843",
"Id": "226536",
"ParentId": "226524",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226536",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T20:38:24.527",
"Id": "226524",
"Score": "1",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Finding the objects with the cheapest seats"
}
|
226524
|
<p>This is my first project using Go to study, I've built a simple utility to export output of commands or other scripts in the Prometheus metrics format.</p>
<p>The utility basically get's the output of a command or from a script and stores it into a map, which I'll later use to re-format the output to the Prometheus metric standard output and expose it in a given port.</p>
<p>I feel that I'm not doing the best use of channels to protect it from data races... would very much appreciate any feedback about different approaches or best practices I might have missed.</p>
<p>Thanks a lot in advance!</p>
<pre class="lang-golang prettyprint-override"><code>// Package go-custom-exporter provides an easy way to export metrics from custom scripts or
// commands to Prometheus without having to worry about doing much code.
//
// The goal is that any routine which can return data in a expected output can be easily
// exported as a Gauge metric with a single command.
package main
import (
"bufio"
"fmt"
"log"
"net/http"
"os/exec"
"strings"
"time"
"github.com/fsilveir/go-custom-exporter/pkg/utils"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func main() {
script, _port, timeout := utils.GetArgs()
port := fmt.Sprintf(":%v", utils.StringToInteger(_port))
path := "/metrics"
// Initialize the first level of the map of strings to store command output
m := map[int]map[string]string{}
// Execute command once out of a loop in order to get the required fields
cmd := exec.Command(script)
ch := make(chan struct{})
go updateMap(cmd, ch, m)
ch <- struct{}{}
cmd.Start()
<-ch
if err := cmd.Wait(); err != nil {
fmt.Println(err)
}
utils.CheckEmptyMap(m)
gauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: "prom",
Subsystem: "custom",
Name: "exporter",
Help: "Prometheus Gauge Metrics from Custom script/command exporter",
},
[]string{
// Name of the metric
"system",
"subsystem",
"metric",
},
)
// Start to serve the data on the target port
http.Handle(path, promhttp.Handler())
prometheus.MustRegister(gauge)
for range m {
fmt.Println(fmt.Sprintf("INFO: Successfully exposing metrics on port %s", (_port)))
go func() {
for {
i := 0
go executeCmd(script, m)
for range m {
go updateMap(cmd, ch, m)
gauge.With(prometheus.Labels{
"system": m[i]["system"],
"subsystem": m[i]["subsystem"],
"metric": m[i]["metric"]}).
Set(utils.StringToFloat64(m[i]["value"]))
i++
}
time.Sleep(utils.StringToSeconds(timeout))
}
}()
log.Fatal(http.ListenAndServe(port, nil))
}
}
// executeCmd will execute a custom scrip or command as a goroutine and return the output to a map
func executeCmd(script string, m map[int]map[string]string) {
cmd := exec.Command(script)
ch := make(chan struct{})
go updateMap(cmd, ch, m)
ch <- struct{}{}
cmd.Start()
<-ch
if err := cmd.Wait(); err != nil {
fmt.Println(err)
}
utils.CheckEmptyMap(m)
}
// updateMap will get the values from the custom script or command executed by executeCmd method
// and update a map that will be used to set the values to be exported my main funcion
func updateMap(cmd *exec.Cmd, ch chan struct{}, m map[int]map[string]string) (cmdOutput map[int]map[string]string) {
defer func() { ch <- struct{}{} }()
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
<-ch
scanner := bufio.NewScanner(stdout)
i := 0
for scanner.Scan() {
s := strings.Split(scanner.Text(), ",")
utils.CheckCmdOutput(s)
// Initialize the second level of the map of strings to store the command output
m[i] = map[string]string{}
m[i]["system"] = strings.TrimSpace(s[0])
m[i]["subsystem"] = strings.TrimSpace(s[1])
m[i]["metric"] = strings.TrimSpace(s[2])
m[i]["value"] = strings.TrimSpace(s[3])
i++
}
return m
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T10:24:58.410",
"Id": "445247",
"Score": "0",
"body": "can you share a fully executable example with test data and run commands ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T23:49:23.633",
"Id": "445344",
"Score": "0",
"body": "Hi @ferada, inside the repository I've included an example shell script and the arguments required to use the utility with it, they can be found at the [following link](https://github.com/fsilveir/go-custom-exporter#setting-up-your-own-scripts). Thanks"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T21:49:41.227",
"Id": "226528",
"Score": "1",
"Tags": [
"go"
],
"Title": "Prometheus exporter for custom scripts (Golang)"
}
|
226528
|
<p><a href="https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/" rel="noreferrer">https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/</a></p>
<p><a href="https://i.stack.imgur.com/udRGR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/udRGR.png" alt="enter image description here"></a></p>
<p>In Pascal's triangle, each number is the sum of the two numbers directly above it.</p>
<p>Example:</p>
<pre><code>Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
</code></pre>
<p>Please review for performance.</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RecurssionQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/
/// </summary>
[TestClass]
public class PascalTriangleTest
{
[TestMethod]
public void TestMethod1()
{
IList<IList<int>> result = PascalTriangle.Generate(5);
IList<IList<int>> expected = new List<IList<int>>();
expected.Add(new List<int> { 1 });
expected.Add(new List<int> { 1, 1 });
expected.Add(new List<int> { 1, 2, 1 });
expected.Add(new List<int> { 1, 3, 3, 1 });
expected.Add(new List<int> { 1, 4, 6, 4, 1 });
for (int i = 0; i < expected.Count; i++)
{
CollectionAssert.AreEqual(expected[i].ToList(), result[i].ToList());
}
}
}
public class PascalTriangle
{
public static IList<IList<int>> Generate(int numRows)
{
IList<IList<int>> result = new List<IList<int>>();
if (numRows == 0)
{
return result;
}
List<int> row = new List<int>();
row.Add(1);
result.Add(row);
if (numRows == 1)
{
return result;
}
for (int i = 1; i < numRows; i++)
{
var prevRow = result[i - 1];
row = new List<int>();
row.Add(1);
for (int j = 0; j < prevRow.Count - 1; j++)
{
row.Add(prevRow[j] + prevRow[j + 1]);
}
row.Add(1);
result.Add(row);
}
return result;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T05:04:42.687",
"Id": "440302",
"Score": "1",
"body": "To calculate the _n_ th row, you need the _n-1_ th row to be calculated. This means your algorithm can only calculate top-down, and can not be extended to calculate a section or a single row. You might want to read about it here: https://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_a_row_or_diagonal_by_itself."
}
] |
[
{
"body": "<p>I wouldn't bother with the <code>numRows == 1</code> special case (it is redundant and just adds code), but you should be checking that <code>numRows >= 0</code> and throwing an argument exception if it is not (and ideally testing for that as well); currently it treats <code>numRows < 0</code> as <code>numRows == 1</code> which makes no sense at all.</p>\n\n<hr />\n\n<p>As always, this would benefit from inline documentation, qualifying what the method does, and what it expects of the caller (e.g. a non-negative number of rows).</p>\n\n<hr />\n\n<p>You might consider <code>var</code> for <code>result</code> and <code>row</code>. Within the method it is fine for <code>result</code> to be <code>List<Ilist<int>></code>, and will have the nice side-effect of removing a little unnecessary indirection (I'm assuming the CLR won't/can't optimise that away).</p>\n\n<hr />\n\n<p>You might consider using the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.-ctor?view=netframework-4.8#System_Collections_Generic_List_1__ctor_System_Int32_\" rel=\"noreferrer\"><code>List(int)</code></a> constructor to improve the memory characteristics of your method, since you know in an advance how large each list will be. Alternatively, if performance matters enough that you will actually benchmark this, then consider an immutable return type (<code>IReadOnlyList<IReadOnlyList<int>></code>) and use arrays directly.</p>\n\n<hr />\n\n<p>I don't like the spacing in your code: I would at the very least separate the <code>== 0</code> and <code>== 1</code> cases with an empty line. They are logically distinct, and having them mushed together fails to convey this.</p>\n\n<hr />\n\n<p><code>TestMethod1</code> is a poor name, and the text fails to check that the length of the output is correct (it could return 6 rows and you'd never know). Tests for edge cases (<code>0</code>, <code>1</code>) and invalid arguments (<code>-1</code>) are important.</p>\n\n<hr />\n\n<p>Your <code>row</code> variable is all over the place. I would put it inside the loop, and add the first one directly as <code>result.Add(new List<int>() { 1 })</code>. As it is, you could use <code>prevRow = row</code>, which would avoid a lookup.</p>\n\n<hr />\n\n<p>Again, if you really care about performance, you should be benchmarking it with a realistic use case (unfortunately those don't exist for such tasks, and optimisation is basically pointless), but you could avoid making 2 lookups from the previous row for the 'inner' entries. Something like this should work:</p>\n\n<pre><code>// inside for (i...)\nint left = 0;\nfor (int j = 0; j < i - 1; j++)\n{\n int right = prevRow[j];\n row.Add(left + right);\n left = right;\n}\nrow.Add(1);\nresults.Add(row)\n</code></pre>\n\n<p>This would also allow you to remove the <code>numRows == 1</code> special case, which would be amusing. Alternatively you could start at <code>j = 1</code> and bake the <code>row.Add(1)</code> first entry.</p>\n\n<hr />\n\n<p>You might also consider a lazy version producing an <code>IEnumerable<IReadOnlyList<int>></code>: this would probably be slower than a non-lazy version for small inputs, but would enable you to handle larger triangles when you would otherwise run out of memory (would be linear rather than quadratic), and the improved memory characteristics may even lead to better performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T05:07:50.620",
"Id": "440303",
"Score": "1",
"body": "I am not sure whether we could gain performance for the bigger rows with this, but since each row is reflective around its centre, perhaps we should only calculate half the row and reflect the other half .. https://planetmath.org/pascalstriangleissymmetricalalongitscentralcolumn"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T07:46:50.153",
"Id": "440313",
"Score": "3",
"body": "+1. Some quick testing shows that using a list's capacity can make things 20-50% faster (less gain for higher numbers of rows), whereas using arrays directly is consistently more than 80% faster. Caching the previous row's left value is about 10-20% faster, and making use of the reflective nature of rows can yield another 10% improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T08:42:29.840",
"Id": "440323",
"Score": "0",
"body": "@PieterWitvoet would you mind sharing your benchmark code? (since you've bothered to test it, that would be worthy of an answer in my book). I'm most surprised by the array performance: I didn't expect that much overhead from `List<T>` (or was that `IList<T>`?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T09:47:31.327",
"Id": "440329",
"Score": "0",
"body": "@VisualMelon: sure, here you go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T10:15:59.717",
"Id": "440333",
"Score": "1",
"body": "You guys are great! Thanks"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T22:40:29.917",
"Id": "226531",
"ParentId": "226529",
"Score": "9"
}
},
{
"body": "<p>Something I ran into while making my own implementation:</p>\n\n<p>After 34 rows, the highest number in the row will be two <code>1166803110</code>s. Adding these for row 35 exceeds the maximum value for ints, resulting in integer-overflow.</p>\n\n<p>You might consider putting the line that does the addition into a <code>checked</code> block, so that an <code>OverflowException</code> is properly thrown:</p>\n\n<pre><code>for (int j = 0; j < prevRow.Count - 1; j++)\n{\n checked \n {\n row.Add(prevRow[j] + prevRow[j + 1]);\n }\n}\n</code></pre>\n\n<p>As mentioned in the comments, the values in the rows grow almost exponentially. This means that switching from <code>int</code> to <code>long</code> as datatype in the lists will only roughly double the amount of rows that can be supported before these too overflow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T09:01:28.983",
"Id": "440325",
"Score": "2",
"body": "+1 I probably should have though about this before even mentioning memory..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T13:44:25.100",
"Id": "440362",
"Score": "0",
"body": "@VisualMelon thanks, it actually surprised me how quickly the values grew. The maximum for each row nearly doubles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T23:38:15.457",
"Id": "440461",
"Score": "0",
"body": "@JAD From the binomial theorem, when $n$ is even the biggest term is n! / [(n/2)! (n/2)!], and using Stirling's approximation for factorials, that is the same order as 2^n. That is almost obvious, because when you have a row with two equal \"biggest terms\", the biggest term in the next row is the sum of two the equal numbers, i.e. twice as big."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T05:31:50.003",
"Id": "440470",
"Score": "0",
"body": "@alephzero yeah, when I thought about it more carefully, it made sense :) Each term grows by a factor `n / ceil(n/2)`, which is 2 when `n` is even, and approaches 2 as `n` grows."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T08:15:56.480",
"Id": "226552",
"ParentId": "226529",
"Score": "12"
}
},
{
"body": "<p>VisualMelon already said everything I wanted to say and more, but at his request, here are the variants I tested. Using list capacity is about 20-50% faster (less gain for higher numbers of rows), while using arrays is consistently more than 80% faster. Left-value caching is about 10-20% faster, and making use of the reflective nature of rows (as mentioned by dfhwze) yields another 10% improvement.</p>\n\n<p>It's also possible to calculate the contents of a row without first calculating all previous rows. It's roughly twice as slow per row because it involves multiplication and division instead of addition, but it's a lot more efficient if you only need a specific row.</p>\n\n<pre><code>// Original approach, modified to cache the previous row's left value:\npublic static IList<IList<int>> Generate_Improved(int numRows)\n{\n IList<IList<int>> result = new List<IList<int>>();\n if (numRows == 0)\n {\n return result;\n }\n List<int> row = new List<int>();\n row.Add(1);\n result.Add(row);\n if (numRows == 1)\n {\n return result;\n }\n\n for (int i = 1; i < numRows; i++)\n {\n var prevRow = result[i - 1];\n row = new List<int>();\n var left = 0;\n for (int j = 0; j < prevRow.Count; j++)\n {\n int right = prevRow[j];\n row.Add(left + right);\n left = right;\n }\n row.Add(1);\n result.Add(row);\n }\n return result;\n}\n\n// Original approach, modified to use list capacities:\npublic static IList<IList<int>> Generate_Capacity(int numRows)\n{\n IList<IList<int>> result = new List<IList<int>>(numRows);\n if (numRows == 0)\n {\n return result;\n }\n List<int> row = new List<int>(1);\n row.Add(1);\n result.Add(row);\n if (numRows == 1)\n {\n return result;\n }\n\n for (int i = 1; i < numRows; i++)\n {\n var prevRow = result[i - 1];\n row = new List<int>(i + 1);\n row.Add(1);\n for (int j = 0; j < prevRow.Count - 1; j++)\n {\n row.Add(prevRow[j] + prevRow[j + 1]);\n }\n row.Add(1);\n result.Add(row);\n }\n return result;\n}\n\n// Original approach, modified to use list capacities and caching the previous row's left value:\npublic static IList<IList<int>> Generate_Capacity_Improved(int numRows)\n{\n IList<IList<int>> result = new List<IList<int>>(numRows);\n if (numRows == 0)\n {\n return result;\n }\n List<int> row = new List<int>(1);\n row.Add(1);\n result.Add(row);\n if (numRows == 1)\n {\n return result;\n }\n\n for (int i = 1; i < numRows; i++)\n {\n var prevRow = result[i - 1];\n row = new List<int>(i + 1);\n var left = 0;\n for (int j = 0; j < prevRow.Count; j++)\n {\n int right = prevRow[j];\n row.Add(left + right);\n left = right;\n }\n row.Add(1);\n result.Add(row);\n }\n return result;\n}\n\n// Using arrays instead of lists:\npublic static IList<IList<int>> Generate_Array(int numRows)\n{\n var result = new int[numRows][];\n if (numRows == 0)\n return result;\n\n result[0] = new int[] { 1 };\n if (numRows == 1)\n return result;\n\n for (int i = 1; i < numRows; i++)\n {\n var prevRow = result[i - 1];\n var row = new int[i + 1];\n row[0] = 1;\n for (int j = 0; j < i - 1; j++)\n row[j + 1] = prevRow[j] + prevRow[j + 1];\n row[i] = 1;\n result[i] = row;\n }\n return result;\n}\n\n// Using arrays instead of lists, and caching the previous row's left value:\npublic static IList<IList<int>> Generate_Array_Improved(int numRows)\n{\n var result = new int[numRows][];\n if (numRows == 0)\n return result;\n\n result[0] = new int[] { 1 };\n if (numRows == 1)\n return result;\n\n for (int i = 1; i < numRows; i++)\n {\n var prevRow = result[i - 1];\n var row = new int[i + 1];\n\n var left = 0;\n for (int j = 0; j < i; j++)\n {\n int right = prevRow[j];\n row[j] = left + right;\n left = right;\n }\n row[i] = 1;\n result[i] = row;\n }\n return result;\n}\n\n// Using arrays instead of lists, caching the previous row's left value, and using row reflection:\npublic static IList<IList<int>> Generate_Array_Improved_Reflective(int numRows)\n{\n var result = new int[numRows][];\n if (numRows == 0)\n return result;\n\n result[0] = new int[] { 1 };\n if (numRows == 1)\n return result;\n\n for (int i = 1; i < numRows; i++)\n {\n var prevRow = result[i - 1];\n var row = new int[i + 1];\n\n var left = 0;\n var mid = (i / 2) + 1;\n for (int j = 0; j < mid; j++)\n {\n int right = prevRow[j];\n var sum = left + right;\n row[j] = sum;\n row[i - j] = sum;\n left = right;\n }\n result[i] = row;\n }\n return result;\n}\n\n// Using arrays, calculating each row individually:\npublic static IList<IList<int>> Generate_PerRow(int numRows)\n{\n var result = new int[numRows][];\n for (int i = 0; i < numRows; i++)\n {\n var row = new int[i + 1];\n row[0] = 1;\n for (int j = 0; j < i; j++)\n row[j + 1] = row[j] * (i - j) / (j + 1);\n result[i] = row;\n }\n return result;\n}\n\n// Using arrays, calculating each row individually, using row reflection:\npublic static IList<IList<int>> Generate_PerRow_Reflective(int numRows)\n{\n var result = new int[numRows][];\n for (int i = 0; i < numRows; i++)\n {\n var row = new int[i + 1];\n row[0] = 1;\n row[i] = 1;\n var mid = i / 2;\n for (int j = 0; j < mid; j++)\n {\n var value = row[j] * (i - j) / (j + 1);\n row[j + 1] = value;\n row[i - j - 1] = value;\n }\n result[i] = row;\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T09:50:38.023",
"Id": "440330",
"Score": "0",
"body": "I wonder how much of the benefit from arrays is because it doesn't indirect through `IList`; does swapping `IList<IList<int>> result = new List<IList<int>>();` for `var result = new List<IList<int>>();` make any difference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T09:57:00.317",
"Id": "440331",
"Score": "0",
"body": "@VisualMelon: good point. `IList<IList<int>> result` is twice as slow compared to `int[][] result`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T09:46:48.547",
"Id": "226558",
"ParentId": "226529",
"Score": "8"
}
},
{
"body": "<p>After my initial disappointment with the performance of the previous implementation below, I got to thinking. Now that we have a generator function why do allocation at all?</p>\n\n<p>The other good answers allocate memory to the triangle as a necessity, this enables back referencing to calculate future values. If you have a generator function, you don't need to back reference the triangle and therefore it is no longer necessary to store the previous values to calculate the next (except for the one, immediately previous in the row.)</p>\n\n<p>When it comes to performance, the allocation of bytes becomes quite expensive. If you don't need to access values out of sequence this approach avoids the allocation overhead. Further note, that any given row can be generated by calling the <code>Row</code> function directly.</p>\n\n<pre><code>public static class JodrellMk2Pascal\n{\n public static IEnumerable<IEnumerable<int>> Triangle(int n)\n {\n for (var i = 0; i < n; i++)\n {\n yield return Row(i);\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static IEnumerable<int> Row(int n)\n {\n var last = 1;\n yield return last;\n\n for (var k = 0; k < n; k++)\n {\n yield return last = last * (n - k) / (k + 1);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>If performance is your goal you'd be better off with an identity function and better memory management.</p>\n\n<p>The additional benefit here, is that you can jump to the 53rd line <code>Line(52)</code> without having to calculate the preceding triangle.</p>\n\n<pre><code>public static class Pascal\n{\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static ReadOnlySpan<long[]> Triangle(int n)\n {\n if (n < 1)\n {\n return ReadOnlySpan<long[]>.Empty;\n }\n\n Span<long[]> triangle = new long[n][];\n\n for (var r = 0; r < n; r++)\n {\n triangle[r] = Line(r).ToArray();\n }\n\n return triangle;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static ReadOnlySpan<long> Line(int n)\n {\n if (n < 0)\n {\n return ReadOnlySpan<long>.Empty;\n }\n\n if (n == 0)\n {\n return (ReadOnlySpan<long>)new long[]\n {\n 1L\n };\n }\n\n Span<long> result = new long[n + 1];\n\n result[0] = 1L;\n for (var k = 0; k < n; k++)\n {\n result[k + 1] = result[k] * (n - k) / (k + 1);\n }\n\n return result;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T15:44:47.787",
"Id": "440384",
"Score": "1",
"body": "I don't understand the use of `ReadOnlySpan`: I think it will only add overhead. A quick benchmark (for n=10, on my machine, etc.) sees a version which just works with `long[]` running in about 80% of the time. The computing of the row independently also seems to be slower in practise according to Peter (I don't see a consistent advantage on my machine), but his implementation seems to be about twice as fast as your implementation (which I figure will be down to his exploiting symmetry and not performing the `result[k]` lookup)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T15:51:37.650",
"Id": "440385",
"Score": "1",
"body": "@VisualMelon, interesting, are you using https://github.com/dotnet/BenchmarkDotNet? There is obviously a hit to using long, re: memory allocation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:08:48.147",
"Id": "440390",
"Score": "2",
"body": "New data: https://gist.github.com/VisualMelon/0c169ba3a3c23c53c0a4a28ff3af7bd4#gistcomment-3004558"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T12:45:06.017",
"Id": "440491",
"Score": "0",
"body": "@VisualMelon, took a different tack, see edit above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T13:11:47.883",
"Id": "440496",
"Score": "3",
"body": "Nice to see someone implement the lazy version properly, but you should probably add some explanation of why you might want to do this (code alone doesn't make for a very good review)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T13:29:05.110",
"Id": "440498",
"Score": "1",
"body": "@VisualMelon advice taken."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T15:14:44.050",
"Id": "226567",
"ParentId": "226529",
"Score": "4"
}
},
{
"body": "<p>You use lists, which are great when you have a flexible number of elements in it and you might add/remove some, but in your case, you know exactly how many elements each list would contain and there is no possibility for it to change. In this case, you are using the wrong data structure because the list has unnecessary overhead. You need an array or arrays. The creation logic looks like this : </p>\n\n<pre><code>int[][] rows = new int[n][];\nfor (i = 0; i < n; i++)\n{\n rows[i] = new int[i + 1];\n}\n</code></pre>\n\n<p>This way, you already have your structure created, all you need to do is fill it. The other advantage is that you take exactly the amount of memory you're supposed to use, so you don't have any overhead.</p>\n\n<p>You also know that every first and last element of a row is one, so why not do this at the same time?</p>\n\n<pre><code>int[][] rows = new int[n][];\nfor (i = 0; i < n; i++)\n{\n rows[i] = new int[i + 1];\n rows[i][0] = 1;\n\n // This is an unnecessary operation for i = 0, but that's a very small problem.\n rows[i][rows[i].Length - 1] = 1;\n}\n</code></pre>\n\n<p>Now what's left is to fill the arrays and your code already does it pretty well, but now we're using arrays instead of lists so we can't use <code>Add</code>.</p>\n\n<pre><code>int[][] rows = new int[n][];\nfor (int i = 0; i < n; i++)\n{\n rows[i] = new int[i + 1];\n rows[i][0] = 1;\n\n // This is an unnecessary operation for i = 0, but that's a very small problem.\n rows[i][rows[i].Length - 1] = 1;\n\n if (i > 1)\n {\n // Notice that we start at 1 instead of zero and end one index before the end to preserve\n // the 1s that we added earlier.\n for (int j = 1; j < rows[i].Length - 1; j++)\n {\n var previousRow = rows[i - 1];\n\n rows[i][j] = previousRow[j - 1] + previousRow[j];\n }\n }\n}\n</code></pre>\n\n<p>The code above is pretty much the same as yours, but with arrays instead of lists.</p>\n\n<p>With this code, you also don't need to check for <code>n == 1</code>, the check will be made in the <code>for</code> loop where you wouldn't enter if <code>n == 1</code>. Using my version of the code, you also don't need to check for <code>n == 0</code>, because it will return an empty <code>int[][]</code> anyways.</p>\n\n<p><strong>Benchmarking</strong></p>\n\n<p>I've used <a href=\"https://github.com/dotnet/BenchmarkDotNet\" rel=\"nofollow noreferrer\">BenchmarkDotNet</a> to test both our solutions.</p>\n\n<p>The end result is (I wanted to add a table but I don't know if it's possible) : </p>\n\n<p>My method : 2.545us (mean time) +- 0.0504us (std)</p>\n\n<p>Your method : 20.766us (mean time) +- 0.4133us (err)</p>\n\n<p>The benchmark code is the following : </p>\n\n<pre><code>[RPlotExporter, RankColumn]\npublic class PascalTriangle\n{\n //The MyCode method is the code written above.\n [Benchmark]\n public int[][] myCode() => MyCode(33);\n\n //The YourCode method is literally your post.\n [Benchmark]\n public IList<IList<int>> yourCode() => yourCode(33);\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n var summary = BenchmarkRunner.Run<PascalTriangle>();\n Console.ReadKey();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:59:20.037",
"Id": "440416",
"Score": "1",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/97691/discussion-on-answer-by-ieatbagels-leetcode-pascals-triangle-c)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:05:11.603",
"Id": "226570",
"ParentId": "226529",
"Score": "3"
}
},
{
"body": "<h2>Types</h2>\n\n<p>The code uses <code>Int</code>. The largest <code>Int</code> in C# is ~2e9. This means that once a row has two cells each greater than 1e9, there will be an overflow. Even though using <code>uint</code> only means the code can calculate one more row prior to overflow, there's no reason to use a signed value. Using <code>long</code> puts overflow much further into the computation and <code>ulong</code> would again probably give us one more row than <code>long</code>. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?redirectedfrom=MSDN&view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>BigInteger</code></a> takes overflow off the table.</p>\n\n<h2>Memory</h2>\n\n<p>The memory of footprint of the proposed code is an area where performance can be improved. Without considering possible compiler optimization, it allocates O(n<sup>2</sup>) memory locations (n rows averaging n/2 length). </p>\n\n<h2>Hardening</h2>\n\n<p>Robustness could be improved by a streaming results as they are calculated. Consider the case:</p>\n\n<pre><code>PascalTriangle.Generate(int64.MaxValue); //9,223,372,036,854,775,807\n</code></pre>\n\n<p>The proposed code will probably <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.outofmemoryexception?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>OutOfMemoryException</code></a> without producing any work. It's not that a streaming solution will necessarily complete the task. But if we stream, we might have the last row before it crashed and that's enough to <strong>restart</strong> from where we were instead of being back at triangle one. </p>\n\n<p>The memory footprint of a streaming solution is O(n). We can quickly calculate row <strong>r<sub>i+1</sub></strong> by retaining row <strong>r<sub>i</sub></strong>. The maximum memory to calculate a row when streaming is 2n-1 memory locations.</p>\n\n<h2>Protocols</h2>\n\n<pre><code>[\n [1],\n [1,1],\n [1,2,1],\n [1,3,3,1],\n [1,4,6,4,1]\n]\n</code></pre>\n\n<p>Looks a lot like a protocol. The proposed code does not return the data in the format of its specification. It returns a C# object, instead. There's no basis to assume that the <em>consuming</em> code is under our control or even relies on .NET. </p>\n\n<p>Of course we have to assume something about the consuming code. Outputting a stream of <code>byte</code>s is traditionally a very low denominator for API's. The output can be encoded as ASCII characters. The example output (without whitespace) becomes:</p>\n\n<pre><code>91 91 49 93 44 91 49 44 49 93 44 91 49 44 50 44 49 93 44 91 49 44 51 44 51 44 49 93 44 91 49 44 52 44 54 44 52 44 49 93 93 \n</code></pre>\n\n<h2>Bandwidth</h2>\n\n<p>The streamed ASCII is 41 bytes. Naively, the proposed code uses 60 bytes (15 four byte integers). If <code>ulong</code>s were used the ASCII would tend to be more space efficient until the cell values in the Triange approached 10e6 (six ascii digits and a <code>,</code>) and approximately as efficient until cell values approached 10e7 (seven ascii digits and a <code>,</code>).</p>\n\n<p>A custom binary encoding would allow two characters per byte. We only need to encode 14 characters: <code>EOF</code>,<code>0-9</code>,<code>[</code>,<code>]</code>, and <code>,</code>. We still have bits left in our <a href=\"https://en.wikipedia.org/wiki/Nibble\" rel=\"nofollow noreferrer\">nibble</a> to include the space and newline characters and stream formatted output that matches the example.</p>\n\n<h2>Leetcode</h2>\n\n<p>The Leetcode problem looks a lot like Fizzbuzz. But unlike Fizzbuzz, the Leetcode problem isn't bounded from one to one hundred. The considerations I've listed in this review would be inappropriate to Fizzbuzz solutions. Fizzbuzz doens't have any unknown conditions. Fizzbuzz can't be <a href=\"https://en.wikipedia.org/wiki/Fuzzing\" rel=\"nofollow noreferrer\">fuzzed</a>. </p>\n\n<p>Leetcode questions have unknowns. They can be fuzzed. They scale beyond 'one to one hundred'. That's what makes them useful starting points for engineering analysis. Unlike Fizzbuzz, they <strong>can</strong> be used to answer important questions in addition to \"can the person write a loop and do they know the modulo operator?\". Leetcode solutions that look like Fizzbuzz solutions are at the low end of solution quality.</p>\n\n<h2>Remarks</h2>\n\n<ul>\n<li>It's good that within limits the proposed code works. </li>\n<li>A more thorough test suite would be a starting point to increase it's robustness. </li>\n<li>Because the code returns an .NET object, it is not clear that the code meets the specification.</li>\n<li>Documentation is absent. Even comments</li>\n<li>The code embodies assumptions about the input that may be unwarranted. </li>\n</ul>\n\n<h2>Laziness</h2>\n\n<p>Because the stream abstraction entails the idea of a consumer, a program using streams only needs to produce values as quickly as the consumer consumes them. The memory footprint can be reduced further by lazily calculating each value.</p>\n\n<p>Cell <code>i</code> in row <code>j</code> can be computed directly on an as needed basis using factorials. Factorials are slower (more computationally intensive) than simple addition. It's a tradeoff. That's engineering.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T13:36:39.597",
"Id": "440499",
"Score": "2",
"body": "The largest signed 32-bit integer is \\$2^{31} - 1 \\approx 2 \\times 10^9\\$. You've got an out-by-one error in the exponent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:10:29.817",
"Id": "440536",
"Score": "0",
"body": "@PeterTaylor Thanks, I made the edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T23:25:47.927",
"Id": "226604",
"ParentId": "226529",
"Score": "3"
}
},
{
"body": "<p>Just a small remark: your entire code is in a <code>namespace</code> called <code>RecurssionQuestions</code> [sic], but it is not recursive. That is confusing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:27:39.657",
"Id": "226640",
"ParentId": "226529",
"Score": "1"
}
},
{
"body": "<p>Musing on this question some more, it occurred to me that Pascals Triangle is of course completely constant and that generating the triangle more than once is in fact an overhead.</p>\n\n<p>Whatever function is used to generate the triangle, caching common values would save allocation and clock cycles.</p>\n\n<p>Something like this would help,</p>\n\n<pre><code>private static readonly int[] Row0 = { 1 };\nprivate static readonly int[] Row1 = { 1, 1 };\nprivate static readonly int[] Row2 = { 1, 2, 1 };\nprivate static readonly int[] Row3 = { 1, 3, 3, 1 };\nprivate static readonly int[] Row4 = { 1, 4, 6, 4, 1 };\nprivate static readonly int[] Row5 = { 1, 5, 10, 10, 5, 1 };\nprivate static readonly int[] Row6 = { 1, 6, 15, 20, 15, 6, 1 };\nprivate static readonly int[] Row7 = { 1, 7, 21, 35, 35, 21, 7, 1 };\nprivate static readonly int[] Row8 = { 1, 8, 28, 56, 70, 56, 28, 8, 1 };\nprivate static readonly int[] Row9 = { 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 };\n\nprivate static int[][] Triangle(byte n) =>\n n switch\n {\n 0 => new[] { Row0 },\n 1 => new[] { Row0, Row1 },\n 2 => new[] { Row0, Row1, Row2 },\n 3 => new[] { Row0, Row1, Row2, Row3 },\n 4 => new[] { Row0, Row1, Row2, Row3, Row4 },\n 5 => new[] { Row0, Row1, Row2, Row3, Row4, Row5 },\n 6 => new[] { Row0, Row1, Row2, Row3, Row4, Row5, Row6 },\n 7 => new[] { Row0, Row1, Row2, Row3, Row4, Row5, Row6, Row7 },\n 8 => new[] { Row0, Row1, Row2, Row3, Row4, Row5, Row6, Row7, Row8 },\n 9 => new[] { Row0, Row1, Row2, Row3, Row4, Row5, Row6, Row7, Row8, Row9 },\n _ => throw new ArgumentOutOfRangeException(nameof(n))\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T09:11:40.680",
"Id": "441704",
"Score": "2",
"body": "Lazy people let the code generate the data :-P I would never write anything like this when I can create a function to do it for me. In fact, I find this is a terrible suggestion :-\\ You're wasted when I tell you to add three more rows. I'd even say this is an anti-suggestion. It makes the code worse, not better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T11:05:12.170",
"Id": "441713",
"Score": "0",
"body": "This would make sense if (1) you've done some market research and came to the conclusion most consumers would require a solution for _n <= 9_ (2) you have, of course, generated the rows with a template like t4 (3) you'd povide a public entry point that would not throw the exception above, but calculates in place for _n > 9_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T08:54:16.257",
"Id": "441904",
"Score": "0",
"body": "@dfhwze, larger triangles require the earlier rows, so they could be reused, extrapolating further, you could apply caching for generated data too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T09:04:21.870",
"Id": "441906",
"Score": "0",
"body": "@t3chb0t My [original answer](https://codereview.stackexchange.com/a/226567/5244) implemented a very concise generator but, if performance is your goal, like in the question, than its better to do all you can to optimise performance; even if it costs some elegance and maintenance."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T09:03:20.210",
"Id": "227065",
"ParentId": "226529",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "226531",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T21:56:28.390",
"Id": "226529",
"Score": "11",
"Tags": [
"c#",
"programming-challenge"
],
"Title": "LeetCode: Pascal's Triangle C#"
}
|
226529
|
<p>A shipping company has a warehouse of Containers. Basically, a Container is a data structure with the following fields:</p>
<ul>
<li>price</li>
<li>commercial campaign id</li>
<li>a list of possible shipment countries (empty list allows all counties)</li>
<li>internal id</li>
</ul>
<p>The task is to implement a function taking the following parameters:</p>
<ul>
<li>a list of containers</li>
<li>a number of containers needed</li>
<li>a country of destination</li>
</ul>
<p>The function has to return a selection of Containers with the following criteria:</p>
<ul>
<li>commercial campaign id should be unique with in the result</li>
<li>should return containers only intended for the country of destination</li>
<li>a total cost should be the maximum for a given destination country</li>
</ul>
<p>A bonus to the solution would be to:</p>
<ul>
<li>add a possibility to add a selection filter (not only by country)</li>
<li>a possibility to add extra fields to prioritize Containers</li>
</ul>
<p>The code works, however: Is there anything in the code that could catch the eye of an experienced programmer? Is there a better way to approach the problem, perhaps by improving some parts of the code? What an potential employer may have not liked about this code? You see, I just want to improve and to learn from my mistakes to succeed the next time.</p>
<pre><code>#include <tuple>
#include <map>
#include <vector>
#include <functional>
#include <algorithm>
#include <string>
#include <iostream>
typedef std::map<int, std::string> CountryList; // int country_code, country_name
typedef std::tuple<long, long, CountryList, long> Container; // long price, long compain_id, CountryList, long id
typedef std::multimap<long, Container, std::greater<long>> ContainerList;
typedef std::pair<long, Container> ContainerValue;
typedef ContainerList::const_iterator Iterator;
typedef std::map<long, Iterator> ResultList;
struct SearchCriteria
{
typedef std::vector< std::function<bool(const ContainerValue & container)>> Filters;
SearchCriteria() {}
bool operator()(const ContainerValue & container) const
{
bool result = false;
for (auto & filter : filters)
{
result |= filter(container);
if (!result)
break;
}
return result;
}
Filters filters;
};
void SelectContainers(const ContainerList & container_list, size_t places_num, int country_code)
{
SearchCriteria s;
// *) add a possibility to add a selection filter (not only by country)
s.filters.push_back([country_code](const ContainerValue & container) {
const CountryList & cl = std::get<2>(container.second);
// 2) should return containers only intended for the country of destination
return !cl.size() || cl.find(country_code) != cl.end();
});
ResultList result;
for (Iterator i = container_list.begin(); i != container_list.end() && result.size() < places_num; ++i )
{
i = std::find_if(i, container_list.end(), s);
if (i != container_list.end())
{
// 1) commercial campaign id should be unique with in the result
result.insert(std::make_pair( std::get<1>((*i).second), i));
}
}
long totalSum = 0;
auto printout = [&totalSum](const std::pair<long, Iterator> & pair) {
std::cout << "Compain id=" << std::get<1>(pair.second->second)
<< " Container id=" << std::get<3>(pair.second->second)
<< " Price=" << std::get<0>(pair.second->second) << std::endl;
totalSum += std::get<0>(pair.second->second);
};
// 3) a total cost should be the maximum for a given destination country
std::for_each(result.begin(), result.end(), printout);
std::cout << "Total max sum=" << totalSum << std::endl;
}
```
My `main()` function and the test data:
```
int main()
{
// price,compain_id, CountryList, id
Container baner = std::make_tuple(1000, 1, CountryList{ { 643,"US" }, { 804,"UK" },{ 440,"Lithuania" } }, 100);
Container baner2 = std::make_tuple(2000, 1, CountryList{ { 643,"US" }, { 804,"UK" } }, 101);
Container baner3 = std::make_tuple(3000, 2, CountryList{ { 643,"US" }, { 112,"Mexico" } }, 102);
Container baner4 = std::make_tuple(6000, 3, CountryList{}, 103);
Container baner5 = std::make_tuple(4000, 4, CountryList{ { 804,"UK" } }, 104);
Container baner6 = std::make_tuple(3000, 5, CountryList{ { 643,"US" } }, 105);
Container baner7 = std::make_tuple(5000, 3, CountryList{ { 643,"US" } }, 106);
Container baner8 = std::make_tuple(9000, 6, CountryList{ { 804,"UK" } }, 107);
Container baner9 = std::make_tuple(5000, 7, CountryList{}, 108);
ContainerList container_list;
container_list.insert(std::make_pair(std::get<0>(baner), baner));
container_list.insert(std::make_pair(std::get<0>(baner2), baner2));
container_list.insert(std::make_pair(std::get<0>(baner3), baner3));
container_list.insert(std::make_pair(std::get<0>(baner4), baner4));
container_list.insert(std::make_pair(std::get<0>(baner5), baner5));
container_list.insert(std::make_pair(std::get<0>(baner6), baner6));
container_list.insert(std::make_pair(std::get<0>(baner7), baner7));
container_list.insert(std::make_pair(std::get<0>(baner8), baner8));
container_list.insert(std::make_pair(std::get<0>(baner9), baner9));
SelectContainers(container_list, 4, 804);
return 0;
}
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Compain id=3 Container id=103 Price=6000
Compain id=4 Container id=104 Price=4000
Compain id=6 Container id=107 Price=9000
Compain id=7 Container id=108 Price=5000
Total max sum=24000
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T23:05:05.590",
"Id": "440285",
"Score": "3",
"body": "Welcome to Code Review! Your post states \"_I have come up with the solution, which unfortunately was unsatisfactorily for unknown reasons._\" ... does that mean that the code does not work properly to the best of your knowledge? If so, the post is not [on-topic](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T11:22:27.963",
"Id": "440340",
"Score": "0",
"body": "The code does work. What I meant was that employer did not make any comments on the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T12:45:56.130",
"Id": "440347",
"Score": "0",
"body": "You should include the full code, otherwise it is impossible to really review it. What is the definition of container_list, etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T15:00:06.373",
"Id": "440376",
"Score": "0",
"body": "oops! I am very sorry, trimmed the begging while copying. Updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:21:19.957",
"Id": "440393",
"Score": "0",
"body": "Why is it bad if your employer didn't make any comments on the code?"
}
] |
[
{
"body": "<p>I can't say for sure what the interviewer thought, but here are some things that could be improved:</p>\n\n<p><strong>1) Use appropriate data types</strong></p>\n\n<p>CountryList is acceptable, but Container should be a class, not a tuple that requires referring to the (hopefully correct) comment to see what data get<1> is referring to. </p>\n\n<p>And what is ContainerList even indexing by? Based on the code, it appears to be the price, but I can only tell that from how it's being constructed in main. And it's not clear why this is a multimap by price rather than a vector. </p>\n\n<p>Edit: On further inspection, I see that's being used for the sorting to give the high-cost items priority. Since this is a concern of the algorithm rather than the caller, it shouldn't be the format that's provided as a parameter - rather SelectContainers should take a vector or iterator range and then sort it internally.</p>\n\n<p>Several of these typedefs are just used internally within SelectContainers, so they shouldn't be defined globally.</p>\n\n<p><strong>2) Interface design</strong></p>\n\n<p>SelectContainers should return a list of results that another method can print (or use in other ways), not do the printing itself.</p>\n\n<p>Having flexibility via SearchCriteria doesn't help if you don't have a way for the user of the function to change it. Make a SearchCriteria a parameter.</p>\n\n<p>SearchCriteria should take the filters as a constructor parameter; the current usage where it fails everything by default until filters are added is unintuitive.</p>\n\n<p><strong>3) Spelling and formatting</strong></p>\n\n<p>There are a number of misspellings and inconsistent formatting. Understandable if this was done in a short time frame, but people do judge on that. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T08:16:21.330",
"Id": "440480",
"Score": "0",
"body": "Thank you very much! All points are taken! However, sorting `Containers` internally in the function don't you think it will be a bit expensive considering that there could be a lot of data? Is it acceptable in terms of speed? And what do you think in terms of encapsulation is having all public members in `SearchCriteria` is acceptable?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T21:48:37.313",
"Id": "226599",
"ParentId": "226532",
"Score": "2"
}
},
{
"body": "<p>I want to expand on the idea that <code>tuple</code>s are a bad way to organize data. Programming languages have decades of history of making better ways to describe data that is more readable and easier to understand. <code>tuple</code> does away with those decades of work and makes code way more confusing and harder to understand. For example, let's look at your data types:</p>\n\n<pre><code>typedef std::map<int, std::string> CountryList; // int country_code, country_name\ntypedef std::tuple<long, long, CountryList, long> Container; // long price, long compain_id, CountryList, long id\ntypedef std::multimap<long, Container, std::greater<long>> ContainerList;\ntypedef std::pair<long, Container> ContainerValue;\ntypedef ContainerList::const_iterator Iterator;\ntypedef std::map<long, Iterator> ResultList;\n</code></pre>\n\n<p>If you have to add a comment to explain something, you probably haven't written it clearly in the first place. What's easier to use? Your definition of <code>Container</code> or a <code>struct</code> or <code>class</code> that names the elements like this:</p>\n\n<pre><code>struct Container {\n long price;\n long campaign_id;\n CountryList countries;\n long id;\n};\n</code></pre>\n\n<p>When you use the <code>struct</code>, you go from writing lines like this:</p>\n\n<pre><code>std::get<1>((*i).second)\n</code></pre>\n\n<p>to writing readable statements like this:</p>\n\n<pre><code>i->second.campaign_id;\n</code></pre>\n\n<p>The <code>i->second</code> is still annoying because you can't infer what value <code>second</code> refers to, but that's due to the design of <code>std::map</code> and not something you can change. But seeing the member name <code>campaign_id</code> is far clearer than figuring out what <code>std::get<1>()</code> gets.</p>\n\n<p>Even when you're forced to use a <code>tuple</code> or <code>pair</code> by the standard library, you can do better than you have. For example, you have:</p>\n\n<pre><code>typedef std::map<int, std::string> CountryList; // int country_code, country_name\n</code></pre>\n\n<p>You could remove the need for the comment by making named data types:</p>\n\n<pre><code>using country_code = int;\nusing country_name = std::string;\ntypedef std::map<country_code, country_name> CountryList;\n</code></pre>\n\n<p>Now you don't need the comment and it's clear what the types are.</p>\n\n<p>You also named something that's not a list a list. I would expect <code>CountryList</code> to be a <code>std::list</code>, or maybe a <code>std::vector</code> or <code>std::array</code>. I would probably remove the type from the name and just call it <code>Countries</code>.</p>\n\n<p>What is this loop attempting to do?</p>\n\n<pre><code> for (auto & filter : filters)\n {\n result |= filter(container);\n if (!result)\n break;\n }\n</code></pre>\n\n<p>Looking at it, if the first item in <code>filters</code> returns <code>true</code> it will iterate all the filters in the list of filters. But if the first item returns false, it will only iterate the first one. Is that the intent?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T07:44:54.390",
"Id": "440478",
"Score": "0",
"body": "Thank you! Yes, I can see now tuples are not something easily readable. I have used CountryList to be a map to have a faster search results in line `return !cl.size() || cl.find(country_code) != cl.end();`. However searching a `std::vector` or a `std::list` of only about 500 elements will only be slightly slower, correct? Yes, `filters` do iterate in this manner, only if all filters return `true` the search is successful. But, yes, in this case I suppose do not need `OR` operation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T06:05:04.100",
"Id": "226612",
"ParentId": "226532",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226599",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T22:41:41.563",
"Id": "226532",
"Score": "1",
"Tags": [
"c++",
"c++11"
],
"Title": "Container of data structure: a better solution to an interview task"
}
|
226532
|
<p>I'm relatively new to coding with PHP and mySQLi. I want to learn more but I'm really limited in resources. Most of my research went into W3Schools, PHP.net, and of course whatever I could find on StackOverflow. Now I'm trying to learn with practical projects like this account registration form.</p>
<p>Really I just want feedback on what I could improve, things I may have done wrong, and just overall a bit of feedback. </p>
<p><strong>Main Questions:</strong></p>
<ul>
<li><p>Am I on the right track or do I need to go back and put a bit more
research into what I'm doing. (if so, where did I go wrong?)</p></li>
<li><p>Is there anything that can be optimized, as in any unnecessarily long
or drawn out?</p></li>
</ul>
<p>There are lots of simple examples out there, but I tried to combine what I could find with what I had learnt together and create a fairly secure and robust form. It all works the way I want it to, but I keep looking at the code and wondering... is this even right?</p>
<p>I realize those are pretty broad questions, but I would accept even a fairly generic answer. Even if it's not what I want to hear (like my code sucks).</p>
<p><em>Note:</em> After pasting all the code, I found parts that got absolutely butchered by Code Reviews own indenting. I'm really sorry if it wasn't fixed, I tried to fix it all. </p>
<hr>
<p><strong>php/session.php</strong></p>
<p>Some of these vars are not really relevant to the registration page, they can probably be removed or moved elsewhere. <em>$date</em> and <em>$hideSelf</em> are used in the registration form. Otherwise, not relevant here. I left it all in just in case. </p>
<p>To explain the others, my main menu is based on the current directory in $curDir , depending on its value different menu items echo the $activePage var ... Could probably accomplish the same with JS but I was learning PHP... so why not? At one time I was also echoing the $curPage var on every page just as the page title. I eventually took that out and just typed out the name for each page so its pretty much unused.</p>
<p>$dateTime is my long way of displaying the current date and time for the user (immediately visible in the main menu) while $dateModified... obviously is the date modified (at the bottom of the page). Only relevant in the fact that they are displayed on the same page but not that they are used in the registration code.</p>
<pre><code><?php
session_start();
// Misc
date_default_timezone_set( "America/Edmonton" );
$activePage = " active";
$hideSelf = " d-none";
// Directories
$selfDir = $_SERVER[ 'PHP_SELF' ];
$curPage = ucfirst(basename($selfDir, ".php" ));
$curDir = dirname($selfDir);
// Dates/Times
$date = date('Y-m-j H:i:s');
$dateTime = date('M jS, Y - g:i A (T)');
$dateModified = date('M jS, Y', getlastmod());
</code></pre>
<p><strong>php/config.php</strong></p>
<pre><code><?php
// These are obviously changed for displaying purposes
define('DB_SERVER', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'name');
$con = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// CHECK CONNECTION
if($con->connect_error){
$dbStatus = "Error";
}else{
$dbStatus = "Connected";
}
</code></pre>
<p><strong>dashboard/register.php</strong></p>
<pre><code><?php
include '../php/session.php';
// REMOVE BAD CHARACTERS
function test_input($data){
if(!empty($data) || $data !== null){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}else{
$_SESSION['ERROR'] = "Empty Field";
header("Location: /dashboard/register.php");
exit();
}
}
// USER REGISTER
if(isset($_POST['register'])){
// -- Inputs -- //
$useremail = test_input($_POST['reg_email']);
$username = test_input($_POST['reg_username']);
$userfirst = test_input($_POST['reg_fname']);
$userlast = test_input($_POST['reg_lname']);
$userphone = test_input($_POST['reg_phone']);
$usergender = test_input($_POST['reg_gender']);
$userpass = test_input($_POST['reg_password']);
$userpasscheck = test_input($_POST['reg_password_confirm']);
// Filter through input regex conditions
// Input email //
if(!filter_var($useremail, FILTER_VALIDATE_EMAIL)){
$_SESSION['ERROR'] = "Invalid Email";
header("Location: /dashboard/register.php");
exit();
// Input username //
}elseif(!preg_match("/^[\w\d]{3,16}$/", $username)){
$_SESSION['ERROR'] = "Invalid Username";
header("Location: /dashboard/register.php");
exit();
// Input first name //
}elseif(!preg_match("/^[\w\d]{2,32}$/", $userfirst)){
$_SESSION['ERROR'] = "Invalid First Name";
header("Location: /dashboard/register.php");
exit();
// Input last name //
}elseif(!preg_match("/^[\w\d]{2,32}$/", $userlast)){
$_SESSION['ERROR'] = "Invalid Last Name";
header("Location: /dashboard/register.php");
exit();
// Input gender //
}elseif(!preg_match("/^[MF]{1}$/", $usergender)){
$_SESSION['ERROR'] = "Invalid Gender?";
header("Location: /dashboard/register.php");
exit();
// Input phone //
}elseif(!preg_match("/^[+]{0,1}[0-9]{1}[-0-9]{13}$/", $userphone)){
$_SESSION['ERROR'] = "Invalid Phone Number";;
header("Location: /dashboard/register.php");
exit();
// Input password //
}elseif($userpass !== $userpasscheck){
$_SESSION['ERROR'] = "Passwords do not match";
header("Location: /dashboard/register.php");
exit();
}elseif(!preg_match("/^[\w\d]{6,32}$/", $userpass)){
$_SESSION['ERROR'] = "Invalid Password";
header("Location: /dashboard/register.php");
exit();
}else{
// DB DEFINITIONS
include_once '../php/config.php';
// Check user name and email //
$sql = "SELECT user_name,user_email FROM _CPAN_users WHERE user_name = ? OR user_email = ?;";
if($stmt = mysqli_prepare($con, $sql)){
mysqli_stmt_bind_param($stmt, "ss", $username,$useremail);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) === 0){
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
// Encrypt Password
$hash = password_hash($userpass, PASSWORD_DEFAULT);
// Generate token
$token = bin2hex(openssl_random_pseudo_bytes(8));
// Add new user
$sql = "INSERT INTO _CPAN_users(user_name,user_email,user_pass,user_registered,user_token) VALUES (?, ?, ?, ?, ?);";
if($stmt = mysqli_prepare($con, $sql)){
mysqli_stmt_bind_param($stmt, "sssss",$username,$useremail,$hash,$date,$token);
mysqli_stmt_execute($stmt);
// Get key id of user for meta table
$usernum = mysqli_stmt_insert_id($stmt);
mysqli_stmt_close($stmt);
// Add user meta
$sql = "INSERT INTO _CPAN_usersmeta(meta_user,meta_fname,meta_lname,meta_phone,meta_gender) VALUES (?, ?, ?, ?, ?);";
if($stmt = mysqli_prepare($con, $sql)){
mysqli_stmt_bind_param($stmt, "issss",$usernum,$userfirst,$userlast,$userphone,$usergender);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($con);
// Generate Confirmation Email
$headers = "MIME-Version: 1.0"."\r\n";
$headers .= "Content-type:text/html;charset=UTF-8"."\r\n";
$headers .= "From: no-reply"."\r\n";
$subject = "Account Verification";
$message = "<strong>-- This is an automated message from: www.website.com. If this message was not meant for you please disregard and delete this email. --</strong>
<p>Please use this link below to verify your account!</p>
<a style='display:block;width:50%;padding:1.25em;margin-left:auto;margin-right:auto;background:#104F69;border:0px;border-radius:0.25em;color:#fff;text-align:center;text-decoration:none;font-weight:bold;' href='https://www.website.com/dashboard/confirmation.php?auth_username=".$username."&auth_token=".$token."'>VERIFY</a>";
// Send Email
$sendmail = mail($useremail, $subject, $message, $headers);
if($sendmail === TRUE){
$_SESSION['ERROR'] = "Verification email has been sent!";
header("Location: /dashboard/register.php");
exit();
}else{
// Send Email - Error
$_SESSION['ERROR'] = "There was a problem with your email. Please contact an admin!";
header("Location: /dashboard/register.php");
exit();
}
}else{
// SQL - Error
$_SESSION['ERROR'] = "Error : prepare,insert,meta";
mysqli_close($con);
header("Location: /dashboard/register.php");
exit();
}
}else{
// SQL - Error
$_SESSION['ERROR'] = "Error : prepare,insert,user";
mysqli_close($con);
header("Location: /dashboard/register.php");
exit();
}
}else{
// Username or Email taken - Error
$_SESSION['ERROR'] = "Username or email already taken";
mysqli_close($con);
header("Location: /dashboard/register.php");
exit();
}
}else{
// SQL - Error
$_SESSION['ERROR'] = "Error : prepare,select";
header("Location: /dashboard/register.php");
exit();
}
}
}
// END REGISTER
?>
</code></pre>
<p><strong>dashboard/register.php (HTML - on same page)</strong></p>
<p>I want to move the form action to a different page - Not sure why I haven't yet, it would make things so much cleaner. Really is it that big of a deal if it gets left at the top? Please don't scold me if it is... I honestly don't know any better... <em>yet</em>. </p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="Viewport" content="width=device-width, initial-scale=1">
<meta name="Description" content="redacted">
<meta name="Keywords" content="redacted">
<title>redacted| Register</title>
<link rel="icon" href="../imgs/logo_64.png">
<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/all.min.css">
<link rel="stylesheet" href="../css/framework.css">
</head>
<body data-spy="scroll" data-target="#context-nav" data-offset="75">
<?php include '../incs/template/header.php';?>
<div class="container-fluid mt-4">
<div class="row">
<div class="col mt-4">
<h1 class="display-4">Register</h1>
<div class="alert alert-primary<?php if(!isset($_SESSION['ERROR'])){echo $hideSelf;}?>"><strong>
<?php
if(isset($_SESSION['ERROR'])){
echo $_SESSION['ERROR'];
unset($_SESSION['ERROR']);
}
?>
</strong></div>
<?php include '../incs/template/register.php';?>
</div>
</div>
<?php include '../incs/template/footer.php';?>
</div>
<?php include '../incs/modals.php';?>
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/framework.js"></script>
</body>
</html>
</code></pre>
<p><strong>incs/template/register.php</strong></p>
<pre><code><div class="border bg-light border-secondary rounded-lg d-block w-75 p-4 mx-auto">
<form id="register_form" class="d-block w-50 mx-auto" method="post">
<div class="form-group mt-4">
<label for="reg_email"><strong>Email:</strong></label>
<input type="text" class="form-control" id="reg_email" name="reg_email" maxlength="64">
</div>
<div class="form-group mt-4">
<label for="reg_username"><strong>Desired Username:</strong></label>
<input type="text" class="form-control" id="reg_username" name="reg_username" maxlength="16">
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group mt-4">
<label for="reg_fname"><strong>First Name:</strong></label>
<input type="text" class="form-control" id="reg_fname" name="reg_fname" maxlength="32">
</div>
</div>
<div class="col-md-6">
<div class="form-group mt-4">
<label for="reg_lname"><strong>Last Name:</strong></label>
<input type="text" class="form-control" id="reg_lname" name="reg_lname" maxlength="32">
</div>
</div>
</div>
<hr>
<div class="form-group mt-4">
<label for="reg_phone"><strong>Phone:</strong></label>
<input type="text" class="form-control" id="reg_phone" name="reg_phone" maxlength="14">
</div>
<hr>
<div class="form-check">
<input type="radio" class="form-check-input" id="reg_gender_m" name="reg_gender" value="M">
<label class="form-check-label" for="reg_gender-m"><strong>Male</strong></label>
</div>
<div class="form-check">
<input type="radio" class="form-check-input" id="reg_gender_f" name="reg_gender" value="F">
<label class="form-check-label" for="reg_gender-f"><strong>Female</strong></label>
</div>
<hr>
<div class="row">
<div class="col-md-6">
<div class="form-group mt-4">
<label for="reg_password"><strong>Password:</strong></label>
<input type="password" class="form-control" id="reg_password" name="reg_password" maxlength="32">
</div>
</div>
<div class="col-md-6">
<div class="form-group mt-4">
<label for="login_password_confirm"><strong>Reenter Password:</strong></label>
<input type="password" class="form-control" id="reg_password_confirm" name="reg_password_confirm" maxlength="32">
</div>
</div>
</div>
<button type="submit" name="register" class="btn btn-secondary btn-block w-75 mx-auto my-4">Register</button>
</form>
</div>
</code></pre>
<p>Any feedback is appreciated as long it isn't condescending. Please be nice if my code sucks, I just want some constructive feedback. Just let me know if there's anything I missed including that seems relevant.</p>
|
[] |
[
{
"body": "<p>First off, this is a quite good a code for someone \"relatively new to coding\". This is definitely above average. There are no critical faults, just some misconceptions. Quite common misconceptions I would say, so let's sort them out. </p>\n\n<h3>The \"BAD CHARACTERS\" misconception.</h3>\n\n<p>This is a nasty one.<br>\nIn reality, there is no such thing as \"bad characters\", let alone your routine has very little to do with them, rather spoiling the input data. The whole test_input function is a cargo cult code snippet that bad tutorials copy from each other. </p>\n\n<p>See my <a href=\"https://security.stackexchange.com/a/200321/40115\">other answer</a> regarding a similar function.</p>\n\n<p>On a side note, the <code>if(!empty($data) || $data !== null)</code> is a collection of misplaced and repeated operators alone.</p>\n\n<ul>\n<li>using empty() for a variable that is deliberately set is useless. you only use this function if there is a possibility for a tested variable to be not set. Which is not the case, you are defining it right in the function definition. so you can use just <code>if(!$data)</code> instead.</li>\n<li>the second condition is useless as well, because empty() (as well as !$data) would test for the null already</li>\n<li>checking for the emptiness before trim is a bit ahead of time. What if after trim() it will become an empty string?</li>\n</ul>\n\n<p>so in the end you can safely just use trim() instead of test_input()</p>\n\n<h3>WET AKA \"Write Everything Twice\" code.</h3>\n\n<p>Well, actually you repeat the code to report an error not twice but a dozen times. </p>\n\n<p>Every time you see a repetition, think of creating a function. </p>\n\n<pre><code>function error($message, $location) {\n $_SESSION['ERROR'] = $message;\n header(\"Location: $location\");\n exit();\n}\n</code></pre>\n\n<p>then you can make it in one line instead of three</p>\n\n<pre><code>error (\"Invalid Email\", \"/dashboard/register.php\");\n</code></pre>\n\n<p>That's just for sake of demonstration though as you won't likely be using this function at all, as we will see a bit later</p>\n\n<p>The same goes for mysqli interaction. As you may noticed, it is quite laborious yet extremely repetitive. Why not to encapsulate all the repeated code into a function again? I have such a function of my own, a <a href=\"https://phpdelusions.net/mysqli/simple\" rel=\"nofollow noreferrer\">mysqli helper function</a>. Just compare the amount of code</p>\n\n<pre><code> $sql = \"SELECT user_name,user_email FROM _CPAN_users WHERE user_name = ? OR user_email = ?;\";\n $stmt = mysqli_prepare($con, $sql);\n mysqli_stmt_bind_param($stmt, \"ss\", $username,$useremail);\n mysqli_stmt_execute($stmt);\n mysqli_stmt_store_result($stmt);\n if(mysqli_stmt_num_rows($stmt) === 0){\n mysqli_stmt_free_result($stmt);\n mysqli_stmt_close($stmt);\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code> $sql = \"SELECT 1 FROM _CPAN_users WHERE user_name = ? OR user_email = ?\";\n $stmt = prepared_query($con, $sql, [$username,$useremail]);\n if(!$stmt->get_result()->fetch_row()){\n</code></pre>\n\n<p>The idea is to write only the meaningful code, encapsulating all the reprtitions into a function.</p>\n\n<h3>Torturous error reporting.</h3>\n\n<p>To be honest, the way this form is reporting errors is more like a torture, letting a user to fix only one error at a time. It's like cutting a dog's tail in chunks. Why not to verify <em>all inputs</em> at once and then give a user all error messages at once as well?</p>\n\n<p>Instead of your current approach, better collect all errors into array, and then verify whether this array is empty or not. If not - then process the user data. If yes, then store it in a session and do your redirect. </p>\n\n<pre><code>$errors = [];\nif(!filter_var($useremail, FILTER_VALIDATE_EMAIL)){\n $errors[] = \"Invalid Email\";\n}\nif(!preg_match(\"/^[\\w\\d]{3,16}$/\", $username)){\n $errors[] = = \"Invalid Username\";\n}\n</code></pre>\n\n<p>and so on. and then</p>\n\n<pre><code>if ($errors) {\n $_SESSION['ERROR'] = $errors;\n header(\"Location: /dashboard/register.php\");\n exit();\n}\n</code></pre>\n\n<h3>Program errors are not user errors.</h3>\n\n<p>Honestly, how do you think, what a site user is supposed to do when given an error message like <code>\"Error : prepare,select\"</code>? How do you suppose to get informed of this error (in order to be able to fix it)?</p>\n\n<p>That's a completely different kind of errors that has nothing to do with a site user but belongs to a programmer only. And thus have to be dealt with using a completely different approach. You can check my article on the <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting</a> basics.</p>\n\n<p>In a nutshell, you don't check every operation's result manually but make PHP to raise errors by itself. Then handle them all in a single place.</p>\n\n<h3>The code</h3>\n\n<p>As a result you will have a pretty neat piece of code (as a bonus you will get rid of this disgusting \"right shift\" when your code eventually moves off screen due to all these conditions) like this:</p>\n\n<pre><code>if(isset($_POST['register']))\n{\n $useremail = trim($_POST['reg_email']);\n ...\n\n\n $errors = [];\n if(!filter_var($useremail, FILTER_VALIDATE_EMAIL)){\n $errors[] = \"Invalid Email\";\n }\n if(!preg_match(\"/^[\\w\\d]{3,16}$/\", $username)){\n $errors[] = = \"Invalid Username\";\n }\n\n ...\n\n\n $sql = \"SELECT 1 FROM _CPAN_users WHERE user_name = ? OR user_email = ?\";\n $stmt = prepared_query($con, $sql, [$username,$useremail]);\n if(!$stmt->get_result()->fetch_row()){\n $errors[] = = \"Username or email already taken\";\n }\n\n if ($errors) {\n $_SESSION['ERROR'] = $errors;\n header(\"Location: /dashboard/register.php\");\n exit();\n }\n\n $hash = password_hash($userpass, PASSWORD_DEFAULT);\n $token = bin2hex(openssl_random_pseudo_bytes(8));\n\n $sql = \"INSERT INTO _CPAN_users(user_name,user_email,user_pass,user_registered,user_token) VALUES (?, ?, ?, ?, ?);\";\n $stmt = prepared_query($con, $sql, [$username,$useremail,$hash,$date,$token]);\n $usernum = mysqli_stmt_insert_id($stmt);\n\n $sql = \"INSERT INTO _CPAN_usersmeta(meta_user,meta_fname,meta_lname,meta_phone,meta_gender) VALUES (?, ?, ?, ?, ?);\";\n $stmt = prepared_query($con, $sql, [$usernum,$userfirst,$userlast,$userphone,$usergender]);\n\n // email stuff goes on\n\n}\n// END REGISTER\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T14:03:28.580",
"Id": "440365",
"Score": "0",
"body": "Wow! Thank you so much this is incredibly constructive, I may have under-sold myself yes... I have been coding in general for several years, but mainly just HTML and CSS... so nothing super complicated. I'm glad to hear I'm somewhat doing okay, I knew I had probably picked up a few misconceptions (which you point out wonderfully in your reply) @Your Common Sense. - I can't thank you enough :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T07:37:10.457",
"Id": "226549",
"ParentId": "226535",
"Score": "2"
}
},
{
"body": "<p>YCS didn't leave too many stones unturned, so I'll just mention some regex refinements as garnish to his great review:</p>\n\n<ul>\n<li><p><code>[\\w\\d]</code> is best written as <code>\\w</code>. The digits are included in the \"word\" metacharacter range.</p></li>\n<li><p><code>{1}</code> can safely be omitted, it is the default quantifier for whatever preceded it.</p></li>\n<li><p><code>[+]</code> is more simply written as <code>\\+</code></p></li>\n<li><p><code>{0,1}</code> is more simply written as <code>?</code></p></li>\n<li><p><code>[0-9]</code> is more simply written as <code>\\d</code></p></li>\n</ul>\n\n<hr>\n\n<p>Beyond the regex, I recommend:</p>\n\n<ul>\n<li><p>not declaring single-use variables like <code>$sendmail</code>; just check return value <code>=== true</code> and move on.</p></li>\n<li><p>if you are going to use <code>mysqli()</code>, try the object-oriented syntax-- it's tidier / less verbous.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T14:14:04.783",
"Id": "440367",
"Score": "0",
"body": "Awesome thank you! - That's one thing I'm still trying to wrap my head around, from what I can tell the procedural syntax is just... old?.. and I find more about object-oriented than procedural, its probably in my best interest to just switch before I get to absorbed into doing it this way. ... I can't even comment on my own regex because I know its not very good, its one of those things I started to look into but got overwhelmed so I just made a few simple ones and moved on. Excellent feedback :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T08:04:23.117",
"Id": "226551",
"ParentId": "226535",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226549",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T00:36:50.380",
"Id": "226535",
"Score": "3",
"Tags": [
"beginner",
"php",
"mysqli"
],
"Title": "Registration form using procedural MySQLi"
}
|
226535
|
<p><a href="https://i.stack.imgur.com/Moscd.png" rel="nofollow noreferrer">Dropdown Screenshot</a></p>
<p>I have 3 dropdowns with multiple components in the UI.
Have incorporated data driven java selenium framework, data is fetched from excel sheet:</p>
<p><a href="https://i.stack.imgur.com/7grYG.png" rel="nofollow noreferrer">Excel sheet- where data is fetched</a></p>
<p>This data I am taking in to main class:</p>
<pre><code>public class TC01_newDesign extends TestBase{
login obj_login;
createNewDesign obj_CreateNewDesign;
saveDesign obj_SaveDesign;
capacitorUnit obj_capacitorUnit;
logout obj_logout;
@Test (priority=1, description = "Login Functionality")
public void login() {
log.info("Open CapDes URL.");
driver.get(data.getProperty("base.url"));
obj_login = new login (driver);
ExcelBase.setExcelFileSheet("Capacitor_unit");
obj_login.enter_username(ExcelBase.getCellData(3,1));
obj_login.enter_password(ExcelBase.getCellData(3,2));
obj_login.select_login();
}
@Test (priority=2, description = "Create new Design")
public void createNewDesign() {
log.info("Create New Design");
obj_CreateNewDesign = new createNewDesign (driver);
obj_CreateNewDesign.select_newButton();
obj_CreateNewDesign.select_productDropDown();
obj_CreateNewDesign.wait_dropdown();
obj_CreateNewDesign.choose_productDropDown(ExcelBase.getCellData(3,4));
obj_CreateNewDesign.select_powerQCDropDown();
obj_CreateNewDesign.wait_dropdown();
obj_CreateNewDesign.choose_powerQCDropDown(ExcelBase.getCellData(3,5));
obj_CreateNewDesign.select_FeederFactoryDropDown();
obj_CreateNewDesign.wait_dropdown();
obj_CreateNewDesign.choose_FeederFactoryDropDown(ExcelBase.getCellData(3,6));
obj_CreateNewDesign.select_okButton();
obj_CreateNewDesign.wait_ok();
}
</code></pre>
<p>Then control goes to Page class - <strong>Here I want your valuable suggestion to improve the code</strong></p>
<pre><code>public class createNewDesign extends PageBase {
public createNewDesign(WebDriver driver) {
super(driver);
}
WebDriver driver;
// Web Element for New button in left panel
@FindBy(xpath = "//div[@class='v-panel-content v-scrollable']//div[2]//div[1]//div[1]//div[1]//span[1]//img[1]")
WebElement newButton;
// Web Element for Product drop down button
@FindBy(xpath = "//div[@class='v-filterselect v-widget v-filterselect-required v-required v-filterselect-prompt']//div[@class='v-filterselect-button']")
WebElement productDropDown;
/*******************************************************************************************/
// Web Element for chosen product(s) - Capacitor Unit
@FindBy(xpath = "//span[contains(text(),\"Capacitor Unit\")]")
WebElement productChoose1;
// Web Element for chosen product(s) - Capacitor Unit SC
@FindBy(xpath = "//span[contains(text(),\"Capacitor Unit SC\")]")
WebElement productChoose2;
// Web Element for chosen product(s) - Capacitor DC Unit
@FindBy(xpath = "//span[contains(text(),\"Capacitor DC Unit\")]")
WebElement productChoose3;
// Web Element for chosen product(s) - Surge Cap
@FindBy(xpath = "//span[contains(text(),\"Surge Cap\")]")
WebElement productChoose4;
// Web Element for chosen product(s) - QBank-A
@FindBy(xpath = "//span[contains(text(),\"QBank-A\")]")
WebElement productChoose5;
// Web Element for chosen product(s) - QBank-A SC
@FindBy(xpath = "//span[contains(text(),\"QBank-A SC\")]")
WebElement productChoose6;
// Web Element for chosen product(s) - QBank-AS
@FindBy(xpath = "//span[contains(text(),\"QBank-AS\")]")
WebElement productChoose7;
// Web Element for chosen product(s) - QBank-BS
@FindBy(xpath = "//span[contains(text(),\"QBank-BS\")]")
WebElement productChoose8;
// Web Element for chosen product(s) - QBank-CS
@FindBy(xpath = "//span[contains(text(),\"QBank-CS\")]")
WebElement productChoose9;
// Web Element for chosen product(s) - QBank-B
@FindBy(xpath = "//span[contains(text(),\"QBank-B\")]")
WebElement productChoose10;
// Web Element for chosen product(s) - QBank-C
@FindBy(xpath = "//span[contains(text(),\"QBank-C\")]")
WebElement productChoose11;
// Web Element for chosen product(s) - Q-Pole
@FindBy(xpath = "//span[contains(text(),\"Q-Pole\")]")
WebElement productChoose12;
// Web Element for chosen product(s) - QBank-PLC
@FindBy(xpath = "//span[contains(text(),\"QBank-PLC\")]")
WebElement productChoose13;
// Web Element for chosen product(s) - QBank-H
@FindBy(xpath = "//span[contains(text(),\"QBank-H\")]")
WebElement productChoose14;
/*******************************************************************************************/
// Web Element for Power Quality Center drop down
@FindBy(xpath = "//div[@class='v-filterselect v-widget v-filterselect-required v-required v-filterselect-prompt']//div[@class='v-filterselect-button']")
WebElement powerQCDropDown;
/*******************************************************************************************/
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose1;
// Web Element for Power Quality Center Option - 10th Of Ramadan, Egypt
@FindBy(xpath = "//span[contains(text(),\"10th Of Ramadan, Egypt\")]")
WebElement powerQCChoose2;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose3;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose4;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose5;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose6;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose7;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose8;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose9;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose10;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose11;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose12;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose13;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose14;
// Web Element for Power Quality Center Option - Ludvika, Sweden
@FindBy(xpath = "//span[contains(text(),\"Ludvika, Sweden\")]")
WebElement powerQCChoose15;
/*******************************************************************************************/
// Web Element for Feeder factory drop down
@FindBy(xpath = "//div[@class='v-filterselect v-widget v-filterselect-required v-required v-filterselect-prompt']//div[@class='v-filterselect-button']")
WebElement FeederFactoryDropDown;
// Web Element for Feeder factory Option - TBA
@FindBy(xpath = "//span[contains(text(),\"Xi'an, China\")]")
WebElement FeederFactoryChoose;
// Web Element for OK (Submit) button
@FindBy(xpath = "//div[@class='v-button v-widget primary v-button-primary']")
WebElement okButton;
// Web Element for waiting for drop down element
@FindBy(xpath = "//div[@class='v-filterselect-suggestmenu']")
WebElement waitdropdown;
// Web Element for waiting for OK
@FindBy(xpath = "//td[@class='v-formlayout-captioncell']//span[contains(text(),'Unit voltage (V)')]")
WebElement waitok;
/*******************************************************************************************
* All Methods for performing actions
* @return
*******************************************************************************************/
public void select_newButton(){
log.info("Select New design button");
newButton.click();
}
public void select_productDropDown(){
productDropDown.click();
}
public void choose_productDropDown(String data){
log.info("Product Selected: " + data);
if(data.contains("Capacitor Unit"))
{
productChoose1.click();
}
if(data.contains("Capacitor Unit SC"))
{
productChoose2.click();
}
if(data.contains("Capacitor DC Unit"))
{
productChoose3.click();
}
if(data.contains("Surge Cap"))
{
productChoose4.click();
}
if(data.contains("QBank-A"))
{
productChoose5.click();
}
if(data.contains("QBank-A SC"))
{
productChoose6.click();
}
if(data.contains("QBank-AS"))
{
productChoose7.click();
}
if(data.contains("QBank-BS"))
{
productChoose8.click();
}
if(data.contains("QBank-CS"))
{
productChoose9.click();
}
if(data.contains("QBank-B"))
{
productChoose10.click();
}
if(data.contains("QBank-C"))
{
productChoose11.click();
}
if(data.contains("Q-Pole"))
{
productChoose12.click();
}
if(data.contains("QBank-PLC"))
{
productChoose13.click();
}
if(data.contains("QBank-H"))
{
productChoose14.click();
}
else
log.error("Enter valid Product name");
}
public void select_powerQCDropDown(){
powerQCDropDown.click();
}
public void choose_powerQCDropDown(String data){
log.info("Power Quality Centre selected: "+ data);
if(data.contains("Ludvika, Sweden"))
{
powerQCChoose1.click();
}
if(data.contains("10th Of Ramadan, Egypt"))
{
powerQCChoose2.click();
}
}
public void select_FeederFactoryDropDown(){
FeederFactoryDropDown.click();
}
public void choose_FeederFactoryDropDown(String data){
log.info("Feeder Factory selected: "+data);
FeederFactoryChoose.click();
}
public void select_okButton(){
log.info("Select Ok button");
okButton.click();
}
public void wait_dropdown(){
TestBase.wait.until(ExpectedConditions.visibilityOf(waitdropdown));
}
public void wait_ok(){
TestBase.wait.until(ExpectedConditions.visibilityOf(waitok));
}
}
</code></pre>
<p>As I am again taking the same name in both xpaths of the drop down and in If loop for different drop down.</p>
<p>Basically what I want is the value from Excel once taken as input, has to be handled efficiently in the code.</p>
<p>Disclaimer: I am new to Java-Selenium, hence asking for this.</p>
|
[] |
[
{
"body": "<p>Your element selectors should be unique. For example, both of these elements contain text 'Capacitor Unit'. Maybe choose an ID or class to select them by. Or match the exact text:</p>\n\n<p>Your comments here is also wrong. It's not selected multiple products (<code>List<WebElement></code>) it's selecting 1 each:</p>\n\n<pre><code>// Web Element for chosen product(s) - Capacitor Unit\n@FindBy(xpath = \"//span[contains(text(),\\\"Capacitor Unit\\\")]\")\nWebElement productChoose1;\n\n// Web Element for chosen product(s) - Capacitor Unit SC\n@FindBy(xpath = \"//span[contains(text(),\\\"Capacitor Unit SC\\\")]\")\nWebElement productChoose2;\n</code></pre>\n\n<p><code>TC01_newDesign</code> is a bad name. It only has meaning to you.</p>\n\n<p>You seem to have your own naming styles for variables, classnames, methodnames. As a Java developer I am only use to seeing the standard lower camel case for variables, upper camel case for Classes and uppercase with underscores for static variables. It's very surprising to see any other style used for Java. I strongly suggest adapting standard naming conventions.</p>\n\n<p>I'd be interested in seeing the actual tests. Methods such as <code>choose_productDropDown</code> make it difficult to actually test anything. Why bother logging an error in a test? Fail the test with a message instead (You may want to do it in the actual test, outside of this method, but since you don't return anything how could you?)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T13:46:45.557",
"Id": "226565",
"ParentId": "226540",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T05:29:48.490",
"Id": "226540",
"Score": "1",
"Tags": [
"java",
"selenium",
"framework"
],
"Title": "Selenium - Java data driven Framework suggestion"
}
|
226540
|
<p>I've been working on a Google Pub/Sub client library for golang. Fairly new to golang and my intention is to learn the language. Not really sure what are the best practices, aiming to learn them over a period of time.</p>
<p>Let me get straight into what the library is trying to do:</p>
<ul>
<li>Create a topic.</li>
<li>Create a subscription.</li>
<li>Publish messages to a topic.</li>
<li>Use a pull subscriber to output individual topic messages.</li>
</ul>
<h2>Code</h2>
<pre class="lang-golang prettyprint-override"><code>// Creates a client, and exposes deleteTopic, topicExists and createSubscription though the client
package pubsubclient
import (
"context"
"log"
"time"
"cloud.google.com/go/pubsub"
"google.golang.org/api/iterator"
)
type pubSubClient struct {
psclient *pubsub.Client
}
// getClient creates a pubsub client
func getClient(projectID string) (*pubSubClient, error) {
client, err := pubsub.NewClient(context.Background(), projectID)
if err != nil {
log.Printf("Error when creating pubsub client. Err: %v", err)
return nil, err
}
return &pubSubClient{psclient: client}, nil
}
// topicExists checks if a given topic exists
func (client *pubSubClient) topicExists(topicName string) (bool, error) {
topic := client.psclient.Topic(topicName)
return topic.Exists(context.Background())
}
// createTopic creates a topic if a topic name does not exist or returns one
// if it is already present
func (client *pubSubClient) createTopic(topicName string) (*pubsub.Topic, error) {
topicExists, err := client.topicExists(topicName)
if err != nil {
log.Printf("Could not check if topic exists. Error: %+v", err)
return nil, err
}
var topic *pubsub.Topic
if !topicExists {
topic, err = client.psclient.CreateTopic(context.Background(), topicName)
if err != nil {
log.Printf("Could not create topic. Err: %+v", err)
return nil, err
}
} else {
topic = client.psclient.Topic(topicName)
}
return topic, nil
}
// deleteTopic Deletes a topic
func (client *pubSubClient) deleteTopic(topicName string) error {
return client.psclient.Topic(topicName).Delete(context.Background())
}
// createSubscription creates the subscription to a topic
func (client *pubSubClient) createSubscription(subscriptionName string, topic *pubsub.Topic) (*pubsub.Subscription, error) {
subscription := client.psclient.Subscription(subscriptionName)
subscriptionExists, err := subscription.Exists(context.Background())
if err != nil {
log.Printf("Could not check if subscription %s exists. Err: %v", subscriptionName, err)
return nil, err
}
if !subscriptionExists {
cfg := pubsub.SubscriptionConfig{
Topic: topic,
// The subscriber has a configurable, limited amount of time -- known as the ackDeadline -- to acknowledge
// the outstanding message. Once the deadline passes, the message is no longer considered outstanding, and
// Cloud Pub/Sub will attempt to redeliver the message.
AckDeadline: 60 * time.Second,
}
subscription, err = client.psclient.CreateSubscription(context.Background(), subscriptionName, cfg)
if err != nil {
log.Printf("Could not create subscription %s. Err: %v", subscriptionName, err)
return nil, err
}
subscription.ReceiveSettings = pubsub.ReceiveSettings{
// This is the maximum amount of messages that are allowed to be processed by the callback function at a time.
// Once this limit is reached, the client waits for messages to be acked or nacked by the callback before
// requesting more messages from the server.
MaxOutstandingMessages: 100,
// This is the maximum amount of time that the client will extend a message's deadline. This value should be
// set as high as messages are expected to be processed, plus some buffer.
MaxExtension: 10 * time.Second,
}
}
return subscription, nil
}
</code></pre>
<p>Here is the publisher code</p>
<pre class="lang-golang prettyprint-override"><code>package pubsubclient
import (
"context"
"encoding/json"
"cloud.google.com/go/pubsub"
)
// Publisher contract to be returned to the consumer
type Publisher struct {
topic *pubsub.Topic
}
// PublisherConfig to be provided by the consumer.
type PublisherConfig struct {
ProjectID string
TopicName string
}
// GetPublisher gives a publisher
func GetPublisher(config PublisherConfig) (*Publisher, error) {
client, err := getClient(config.ProjectID)
if err != nil {
return nil, err
}
topic, err := client.createTopic(config.TopicName)
if err != nil {
return nil, err
}
return &Publisher{
topic: topic,
}, nil
}
// Publish message to pubsub
func (publisher *Publisher) Publish(payload interface{}) (string, error) {
data, err := json.Marshal(payload)
if err != nil {
return ``, err
}
message := &pubsub.Message{
Data: data,
}
response := publisher.topic.Publish(context.Background(), message)
return response.Get(context.Background())
}
</code></pre>
<p>Here is the Subscriber code</p>
<pre class="lang-golang prettyprint-override"><code>package pubsubclient
import (
"context"
"log"
"sync"
"cloud.google.com/go/pubsub"
)
// SubscribeMessageHandler that handles the message
type SubscribeMessageHandler func(chan *pubsub.Message)
// ErrorHandler that logs the error received while reading a message
type ErrorHandler func(error)
// SubscriberConfig subscriber config
type SubscriberConfig struct {
ProjectID string
TopicName string
SubscriptionName string
ErrorHandler ErrorHandler
Handle SubscribeMessageHandler
}
// Subscriber subscribe to a topic and pass each message to the
// handler function
type Subscriber struct {
topic *pubsub.Topic
subscription *pubsub.Subscription
errorHandler ErrorHandler
handle SubscribeMessageHandler
cancel func()
}
// CreateSubscription creates a subscription
func CreateSubscription(config SubscriberConfig) (*Subscriber, error) {
client, err := getClient(config.ProjectID)
if err != nil {
return nil, err
}
topic, err := client.createTopic(config.TopicName)
if err != nil {
return nil, err
}
subscription, err := client.createSubscription(config.SubscriptionName, topic)
if err != nil {
return nil, err
}
return &Subscriber{
topic: topic,
subscription: subscription,
errorHandler: config.ErrorHandler,
handle: config.Handle,
}, nil
}
// Process will start pulling from the pubsub. The process accepts a waitgroup as
// it will be easier to orchestrate a use case where one application needs
// to subscribe to more than one topic
func (subscriber *Subscriber) Process(wg *sync.WaitGroup) {
log.Printf("Starting a Subscriber on topic %s", subscriber.topic.String())
output := make(chan *pubsub.Message)
go func(subscriber *Subscriber, output chan *pubsub.Message) {
defer close(output)
ctx := context.Background()
ctx, subscriber.cancel = context.WithCancel(ctx)
err := subscriber.subscription.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
output <- msg
})
if err != nil {
// The wait group is stopped or marked done when an error is encountered
subscriber.errorHandler(err)
subscriber.Stop()
wg.Done()
}
}(subscriber, output)
subscriber.handle(output)
}
// Stop the subscriber, closing the channel that was returned by Start.
func (subscriber *Subscriber) Stop() {
if subscriber.cancel != nil {
log.Print("Stopped the subscriber")
subscriber.cancel()
}
}
</code></pre>
<p>If this is a very big code review I will break it down. My main question is in the <code>Process()</code> method of the subscriber. Right now this method accepts a <code>waitGroup</code> and not really sure if that is a good design. To just show an example of how I envision to use the method:</p>
<pre class="lang-golang prettyprint-override"><code>// Process will start pulling from the pubsub. The process accepts a waitgroup as
// it will be easier for us to orchestrate a use case where one application needs
// more than one subscriber
var wg sync.WaitGroup
wg.Add(1)
go subscriber.Process(&wg)
publishMessages(publisher)
wg.Wait()
</code></pre>
<p>Is that the right way to design? Any other good design patterns that I might need to follow? Please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T23:40:57.297",
"Id": "440462",
"Score": "0",
"body": "Cross posted to reddit: [Go code review and feedback for pubsub client](https://www.reddit.com/r/golang/comments/cthipa/go_code_review_and_feedback_for_pubsub_client/)."
}
] |
[
{
"body": "<ul>\n<li><code>getClient</code>, I'm pretty sure you should pass through the <code>context</code>\nobject from the outside and not simply create a dummy with\n<code>Background</code>. Also, at some point doing both logging of an error\n<em>and</em> passing it back will bite you because you're going to end up\nwith two or more copies of the same error (unless you're 100% diligent\nabout only logging it at the origin).</li>\n<li>Same <code>context</code> comment goes for all other methods actually. As a user\nof the library I want to pass in <em>my</em> context, otherwise there's\nlittle point to it.</li>\n<li>The configurations in <code>createSubscription</code> look like they should be\ncoming from the outside, that is, have defaults, but let the user\noverride them. The comments are great though if they're not explained\nas part of the <code>pubsub</code> library already.</li>\n<li>In <code>Process</code>, the anonymous function doesn't have to have parameters,\nit'll simply capture the values of <code>subscriber</code> and <code>output</code>\nautomatically.</li>\n</ul>\n\n<p>I'd say the wait group is fine? Assuming that the <code>Stop</code> call will\ncause the appropriate error that shuts down the goroutine running\n<code>Process</code>. What's a bit vague to me is if it's intentional that the\n<code>errorHandler</code> is always called, even when the subscriber is terminated\nvia <code>Stop</code>? It's not the worst of problems of course.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T21:13:14.470",
"Id": "226596",
"ParentId": "226544",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T06:43:58.757",
"Id": "226544",
"Score": "4",
"Tags": [
"beginner",
"go"
],
"Title": "Google pubsub client in golang"
}
|
226544
|
<p>I'm trying to improve on examples from <em>Clean Code</em>* while re-implementing them in C++. This time it's the Sieve of Eratosthenes prime-computing example from pp. 71-74.</p>
<p>Below is the original adapted for C++, without improvements:</p>
<p>.h</p>
<blockquote>
<pre><code>class PrimeGenerator {
public:
PrimeGenerator() = default;
~PrimeGenerator() = default;
static std::vector<unsigned> generatePrimes(unsigned maxValue);
private:
static void uncrossIntegersUpTo(unsigned maxValue);
static void crossOutMultiples();
static unsigned determineIterationLimit();
static void crossOutMultiplesOf(unsigned i);
static bool notCrossed(unsigned i);
static void putUncrossedIntegersIntoResult();
static unsigned numberOfUncrossedIntegers();
static std::vector<bool> crossedOut;
static std::vector<unsigned> result;
};
</code></pre>
</blockquote>
<p>.cpp</p>
<blockquote>
<pre><code>std::vector<bool> PrimeGenerator::crossedOut;
std::vector<unsigned> PrimeGenerator::result;
std::vector<unsigned> PrimeGenerator::generatePrimes(unsigned maxValue)
{
if (maxValue < 2)
return {};
uncrossIntegersUpTo(maxValue);
crossOutMultiples();
putUncrossedIntegersIntoResult();
return result;
}
void PrimeGenerator::uncrossIntegersUpTo(unsigned maxValue)
{
crossedOut = std::vector<bool>(maxValue + 1, false);
crossedOut[0] = true;
crossedOut[1] = true;
}
void PrimeGenerator::crossOutMultiples()
{
unsigned limit = determineIterationLimit();
for (size_t i = 2; i <= limit; ++i)
{
if (notCrossed(i))
crossOutMultiplesOf(i);
}
}
unsigned PrimeGenerator::determineIterationLimit()
{
// Every multiple in the array has a prime factor that
// is less than or equal to the root of the array size,
// so we don't have to cross out multiples of numbers
// larger than that root.
double iterationLimit = std::sqrt(crossedOut.size());
return static_cast<unsigned>(iterationLimit);
}
void PrimeGenerator::crossOutMultiplesOf(unsigned i)
{
for (size_t multiple = 2 * i; multiple < crossedOut.size(); multiple += i)
{
crossedOut[multiple] = true;
}
}
bool PrimeGenerator::notCrossed(unsigned i)
{
return !crossedOut[i];
}
void PrimeGenerator::putUncrossedIntegersIntoResult()
{
result = std::vector<unsigned>(numberOfUncrossedIntegers());
size_t j = 0;
for (size_t i = 2; i < crossedOut.size(); ++i)
{
if (notCrossed(i))
result[j++] = i;
}
}
unsigned PrimeGenerator::numberOfUncrossedIntegers()
{
unsigned count = 0;
for (size_t i = 2; i < crossedOut.size(); ++i)
{
if (notCrossed(i))
count++;
}
return count;
}
</code></pre>
</blockquote>
<p>What we see here is a static class with static functions and members. We don't like these in C++, so it seems this code could be better served with a namespace and some free functions. Let's try - my improvement attempt coming below.</p>
<p>.h</p>
<pre><code>namespace PrimeGenerator
{
std::vector<unsigned> generatePrimes(unsigned maxValue);
}
</code></pre>
<p>.cpp</p>
<pre><code>namespace {
std::vector<bool> uncrossIntegersUpTo(int maxValue)
{
std::vector<bool> crossedOut(maxValue + 1, false);
crossedOut[0] = true;
crossedOut[1] = true;
return crossedOut;
}
unsigned determineIterationLimit(size_t size)
{
// Every multiple in the array has a prime factor that
// is less than or equal to the root of the array size,
// so we don't have to cross out multiples of numbers
// larger than that root.
double iterationLimit = std::sqrt(size);
return static_cast<unsigned>(iterationLimit);
}
void crossOutMultiplesOf(unsigned i, std::vector<bool>& crossedOut)
{
for (size_t multiple = 2 * i; multiple < crossedOut.size(); multiple += i)
{
crossedOut[multiple] = true;
}
}
void crossOutMultiples(std::vector<bool>& crossedOut)
{
unsigned limit = determineIterationLimit(crossedOut.size());
for (size_t i = 2; i <= limit; ++i)
{
if (!crossedOut[i])
crossOutMultiplesOf(i, crossedOut);
}
}
std::vector<unsigned> putUncrossedIntegersIntoResult(const std::vector<bool>& crossedOut)
{
std::vector<unsigned> result;
for (size_t i = 2; i < crossedOut.size(); ++i)
{
if (!crossedOut[i])
result.push_back(i);
}
return result;
}
}
namespace PrimeGenerator {
std::vector<unsigned> generatePrimes(unsigned maxValue)
{
if (maxValue < 2)
return {};
auto crossedOut = uncrossIntegersUpTo(maxValue);
crossOutMultiples(crossedOut);
return putUncrossedIntegersIntoResult(crossedOut);
}
}
</code></pre>
<p>A quick summary of changes:<br>
- I removed the class, leaving a single interface function in a <code>PrimeGenerator</code> namespace.<br>
- The <code>numberOfUncrossedIntegers()</code> function didn't seem to make much sense, so I refactored <code>putUncrossedIntegersIntoResult(...)</code> to get rid of the former.<br>
- <code>notCrossed(...)</code> would now need to have two parameters, so it stopped making sense either. It's gone now. </p>
<p>Now, I have two questions about my code. First of all, we now need to pass the <code>crossedOut</code> vector around, which is a downside compared to the previous design. Would you propose an alternative solution to mitigate this? Secondly, are there any extra places where I should have used <code>size_t</code> instead of <code>unsigned</code>?</p>
<p>Cheers!</p>
<p><strong>EDIT:</strong><br>
I'd like to stress I care more about good software engineering and coding style here rather than making this algorithm as fast as possible. Though of course it should be correct.</p>
<hr>
<p>* <em>Clean Code: A Handbook of Agile Software Craftsmanship</em>, Robert C. Martin</p>
|
[] |
[
{
"body": "<p>In general, we try to keep functions small and nice, but in your case, using so many functions is just weird. For example, are you sure the <code>uncrossedIntegersUpTo</code> function is needed at all? How about <code>determineIterationLimit</code>? You can just handle them in the main function.</p>\n\n<p>Also, <code>std::vector<bool></code> is not like the normal <code>vector</code>. It is not a container because it (usually) packs the <code>bool</code>s together to save space. This may result in a significant increase in runtime. (See Howard Hinnant's <a href=\"https://howardhinnant.github.io/onvectorbool.html\" rel=\"nofollow noreferrer\">On <code>vector<bool></code></a>) This is definitely a big mistake, but there is no trivial backwards compatible way to fix it at this stage. You may have to consider working around it with, say, <code>std::vector<char></code> in this case.</p>\n\n<p>Now let's talk about types. First, it is <code>std::size_t</code>, not <code>size_t</code>. Second, your use of <code>unsigned</code> everywhere is like a \"magic type\" (analogous to magic numbers) — it will help to define an alias like</p>\n\n<pre><code>using number_t = unsigned;\n</code></pre>\n\n<p>And I think something like <code>std::uint_fast32_t</code> will be better in this case. Also, <code>std::size_t</code> operates on sizes. Are you sure you want to use it for numbers?</p>\n\n<p><code>std::sqrt</code> operates on floating point numbers and may cause precision problems here. You may want to design some <code>isqrt</code> function for integers.</p>\n\n<p>Putting these together, your code may be as simple as something like: (not tested)</p>\n\n<pre><code>// generate primes less than max\nstd::vector<number_t> generate_primes(number_t max)\n{\n if (max < 2)\n return {};\n\n // You may need to use char or something like that\n std::vector<bool> table(max, false); // crossed out numbers\n table[0] = table[1] = true;\n\n const number_t limit = isqrt(max); // like that\n for (number_t i = 2; i < limit; ++i) {\n if (!table[i]) {\n for (number_t j = i * 2; j < max; ++j)\n table[j] = true;\n }\n }\n\n std::vector<number_t> result;\n for (number_t i = 2; i < max; ++i) {\n if (!table[i])\n result.push_back(i);\n }\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:39:24.423",
"Id": "440634",
"Score": "0",
"body": "Thanks for the valuable input! There are points I agree with, and some I disagree with, as in life :) Ad. Small functions. I do like small functions, and I don't think \"it's just weird\" is enough of a justification not to write them. Another thing I don't like are raw loops (S. Parent's talk on this is highly recommendable: https://youtu.be/W2tWOdzgXHA), so I'd insist on keeping `crossOutMultiples` along with `putUncrossedIntegersIntoResult` (but rename it). I do think you've got a point, though, and I'd include `crossOutMultiplesOf` in the former plus get rid of `determineIterationLimit`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:40:53.250",
"Id": "440635",
"Score": "0",
"body": "Ad. `std::vector<bool>`. I had a vague idea there was something wrong with it, but didn't know exactly what. Thanks!\n\nAd. `size_t` vs `std::size_t`. Oh right, `size_t` actually comes from the C compatibility header. True, we should prefer the namespaced one, though they're essentially the same, I think. `std::size_t` is not as convenient, however ;) Still, you're right.\n\nAd. `using number_t`. That's an interesting idea, thanks. Where *would you* use size_t, then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:43:05.770",
"Id": "440636",
"Score": "0",
"body": "Ad. `std::uint_fast32_t`. I didn't know about these types. Cool, thanks. Good for when you care about maximally optimising your algorithms for speed.\nAd. `isqrt`. I'm wondering if this is really necessary. I might be missing something, though, so could you clarify at what point do you see this becoming a problem?\nOverall, thanks for the comments, I learned something. If I may give you some feedback, then I missed some arguments justifying your suggestions, such as with writing short functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:43:38.603",
"Id": "440637",
"Score": "0",
"body": "I also have one comment to your own solution. Naming a vector or an array a 'table' doesn't really describe what it's for. `crossedOut`, which is not my idea, accomplishes this far better. Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:50:06.820",
"Id": "440692",
"Score": "0",
"body": "@SG_90 There is nothing wrong with raw loops whatsoever. What’s wrong is loops that really aren’t logically loops (e.g., zeroing a range). `std::size_t` is used when you are dealing with size, e.g., as the size of an array. The `fast` family of types are not directly related to speed ... There is no objective way to judge which type is “fast,” and I just consider them as the “natural” type to use. The alternative is the `least` family, which may actually incur performance overhead. And `std::sqrt` may compute the square root of large numbers wrongly, and may be inefficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:52:49.977",
"Id": "440695",
"Score": "0",
"body": "@SG_90 About short functions: everything good becomes bad when used to the extreme. In general, short and nice functions are great, but too many of them just feels a bit wrong IMO. In this case, you are logically doing one thing in this function, and things like cross tables aren’t a logically separate matter I think. I am glad to see my answer is being read so carefully!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T09:11:33.283",
"Id": "226557",
"ParentId": "226553",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>Starting cross-out from <code>size_t multiple = 2 * i</code> is a serious pessimization. Every multiple of <code>i</code> with other factor less than <code>i</code> has already been crossed out during previous passes, which dealt with these smaller primes. You should start with <code>size_t multiple = i * i</code>.</p></li>\n<li><p>Notice that computing <code>i * i</code> eliminates the need to compute <code>sqrt</code>. The outer loop written as</p>\n\n<pre><code>for (size_t i = 2; i * i < crossedOut.size(); ++i)\n</code></pre>\n\n<p>terminates in a very natural way. It may also be beneficial to store the square in a variable:</p>\n\n<pre><code>for (size_t i = 2; (square = i * i) < crossedOut.size(); ++i) {\n crossOutMultiplesOf(square, i, crossedOut);\n}\n</code></pre>\n\n<p>Now, passing both <code>i</code> and its square seems redundant. OTOH <em>not</em> passing the square forces the callee to recompute it. This is a very rare situation in which I'd advocate against factoring the loop into a function. Consider</p>\n\n<pre><code>for (size_t i = 2; (square = i * i) < crossedOut.size(); ++i) {\n for (size_t multiple = square; multiple < crossedOut.size(); multiple += i) {\n crossedOut[multiple] = true;\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:09:55.513",
"Id": "226573",
"ParentId": "226553",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T08:16:35.700",
"Id": "226553",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"primes"
],
"Title": "Computing the first n primes: an example from Clean Code revised for C++"
}
|
226553
|
<p>I've written a simple app that draws with a kaleidoscope effect in javascript, could someone please review the code? I'm especially interested in functional practices and design patterns.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const game = {
pi2: Math.PI*2,
sides: 12,
background: '125,125,125',
load: function () {
game.canvas = document.createElement('canvas');
game.ctx = game.canvas.getContext('2d');
document.body.appendChild(game.canvas);
document.body.style.overflow = 'hidden';
document.body.style.background = 'rgba('+game.background+',1)';
game.resize();
game.input = document.querySelector('input');
game.input.addEventListener('change', game.change);
game.change();
game.button = document.querySelector('button');
game.button.addEventListener('click', game.clear);
game.clear();
},
getPoint: function (event) {
return {
x: event.clientX - game.hw,
y: event.clientY - game.hh
};
},
mousedown: function (event) {
game.clicking = true;
},
mouseup: function (event) {
game.clicking = false;
},
draw: function (event) {
game.point = game.getPoint(event);
if (game.last) {
if (game.clicking) {
game.ctx.fillStyle = 'rgba('+game.background+',0.01)';
game.ctx.fillRect(0,0,innerWidth, innerHeight);
}
var angle1 = Math.atan2(game.last.y,game.last.x);
var angle2 = Math.atan2(game.point.y,game.point.x);
for (var i=0; i<game.sides; i++) {
angle1 += game.slice;
angle2 += game.slice;
var p1 = game.rotate(angle1, game.last);
var p2 = game.rotate(angle2, game.point);
var h = Math.round((angle1*360)/game.pi2);
var color = 'hsl('+h+',5%,50%)';
game.ctx.lineWidth = 1;
if (game.clicking || game.clicking !== game.release) {
color = 'hsl('+h+',100%,75%)';
game.ctx.lineWidth = 3;
}
if (game.clicking !== game.release) {
game.circle(p2,color);
}
game.line(p1,p2,color);
}
}
game.last = game.point;
game.release = game.clicking;
},
rotate: function (a,p) {
var d = Math.sqrt(Math.pow(p.x,2)+Math.pow(p.y,2));
return {
x: d * Math.cos(a),
y: d * Math.sin(a)
}
},
line: function (a,b,c) {
game.ctx.beginPath();
game.ctx.strokeStyle = c;
game.ctx.moveTo(a.x + game.hw, a.y + game.hh);
game.ctx.lineTo(b.x + game.hw, b.y + game.hh);
game.ctx.stroke();
},
circle: function (p,c) {
game.ctx.beginPath();
game.ctx.strokeStyle = c;
game.ctx.arc(p.x + game.hw, p.y + game.hh, 3, 0, game.pi2);
game.ctx.stroke();
},
resize: function () {
game.canvas.width = innerWidth;
game.canvas.height = innerHeight;
game.hw = innerWidth/2;
game.hh = innerHeight/2;
},
change: function () {
game.sides = game.input.value;
game.slice = game.pi2 / game.sides;
},
clear: function () {
game.ctx.fillStyle = 'rgba('+game.background+',1)';
game.ctx.fillRect(0,0,innerWidth, innerHeight);
}
};
addEventListener('load', game.load);
addEventListener('mousedown', game.mousedown);
addEventListener('mouseup', game.mouseup);
addEventListener('resize', game.resize);
addEventListener('mousemove', game.draw);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
overflow: hidden;
cursor: crosshair;
}
div {
position: absolute;
margin: 0.2em;
margin-left: calc(50% - 3em);
background: rgba(255,255,255,0.8);
padding: 0 0.3em;
border-radius: 0.3em;
}
input {
width: 3em;
padding: 0.2em;
margin: 0.3em;
}
button {
padding: 0.2em 0.5em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<label>Sides:</label>
<input type="number" value="7" min="1">
<button>X</button>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T13:56:55.720",
"Id": "440363",
"Score": "1",
"body": "I think this is the wrong site for this kind of question, try stackoverflow instead. But you would probably want to use a Functional Reactive Programming library (see [here](https://github.com/stoeffel/awesome-frp-js) for a list)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T17:14:57.567",
"Id": "440417",
"Score": "1",
"body": "I really don't get it, the help link says: \"What questions can I ask about here?\nIf you have a working piece of code from your project and are looking for open-ended feedback in the following areas: Application of best practices and design pattern usage\" - I posted working code according to the links definition, no bugs, not slow nor failing any tests and I'm asking for best practices in functional design pattern. Can someone explain me what I'm getting wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T17:19:00.950",
"Id": "440418",
"Score": "0",
"body": "We review code, we don't handle specific requests for refactoring code (working code or not) as we do not provide code writing services. If a reviewer decides to include an alternative approach which happens to fit your needs, you are lucky, but it should not be the goal of a review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T17:41:54.940",
"Id": "440424",
"Score": "2",
"body": "I will definitely accept any kind of review, but I'm way more interested in a functional approach. My original post was only please review this code, but the SO system did not allow me and asked me to write more. I see no reason for closing the question but whatever, I edited the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T19:40:16.213",
"Id": "440440",
"Score": "1",
"body": "Thanks for the edits and for the reopen. It's the first time I see such an educated and positive feedback from a stack community. And sorry for my attitude, it's just that I've been through some bad stuff around here."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T13:02:57.857",
"Id": "226561",
"Score": "2",
"Tags": [
"javascript",
"functional-programming"
],
"Title": "Kaleidoscope Effect App"
}
|
226561
|
<p>I'd like to write a script that receives text input from the clipboard that will be from a song lyric sheet with chords. The goal is for the function to return the text to the clipboard after transposing the chord names up or down a half-step. If the solution is with shell commands, I might still wrap it in an AppleScript.
I'm having a hard time conceptualizing a good, reliable approach to the transpose function itself.</p>
<p>Transposing down, any "C" chord would become a "B" chord. An "F#" would become and "F". An "Ab" would become a "G", etc.
It really is fine if the function only transposes down or up, cause one can cycle through, but it'd be nice if it could go either way.
Here's a sample of a text, with about as many variations I can think to include:</p>
<pre><code>C F G
La la is a line of lyrics with simple chords
C B7 Ab F#
La la some chords have flats and sharps
C Abm Fm
La la other lines have minor chords
F#sus Fmj7 B5 Gsus2 Gm7
La la but chords can can't kinda funky
Cdim Daug F+ G2
Doo wop with many short suffixed annotations
C/F Am/G B7/G
and any can have a slash followed by a bass note.
</code></pre>
<p>Notes about a chord sheet formatting:</p>
<p>Chord names are given on lines above the line of lyric.
* Verses etc. are separated by an extra line break.</p>
<ul>
<li><p>All chord names are in capitals, and no other letters on a chord line are.</p></li>
<li><p>Only the chord letter and the flat b or # need to change when transposed. All other "sus", "m7", "+", "dim", etc. remain unchanged.</p></li>
<li><p>Chord half-step progression is: A A#/Bb B C C#/Db D D#/Eb E F F#/Gb G G#/Ab</p></li>
<li><p>Technically, a song should only use flats b or sharps uniformly.</p></li>
<li><p>Any bass notes after a slash / also need to be transposed.</p></li>
</ul>
<p>One of the problems of course has to do with sequential changes and not changing a chord name that has already been changed.</p>
<p>One could isolate the lines with chords by looking only at lines with three spaces in a row. And only the capital letters (and b & #) need to be looked at on those rows.</p>
<p>I found this where someone was working on chord transposing, (<a href="https://stackoverflow.com/questions/11084376/php-chord-transposer">PHP chord transposer</a>), but it was using inline chord notation, and also I don't speak PHP.</p>
<p>Here is code that I now have working. It has a lot of repeats, so is not very efficient. There a better way than this?</p>
<pre><code>property chordList : {"A#", "Bb", "C#", "Db", "D#", "Eb", "F#", "Gb", "G#", "Ab", "A", "B", "C", "D", "E", "F", "G"}
property codeList : {"©12", "©13", "©16", "©17", "©19", "©20", "©23", "©24", "©26", "©27", "©11", "©14", "©15", "©18", "©21", "©22", "©25"}
property loweredList : {"A", "A", "C", "C", "D", "D", "F", "F", "G", "G", "Ab", "Bb", "B", "Db", "Eb", "E", "Gb"}
property raisedList : {"B", "B", "D", "D", "E", "E", "G", "G", "A", "A", "A#", "C", "C#", "D#", "F", "F#", "G#"}
set theString to the clipboard
set transposeUp to false -- true transposes up, false shifts down
set newString to transposeChords(theString, transposeUp)
set the clipboard to newString
on transposeChords(musicString, shiftUp)
if shiftUp then
set changeList to raisedList
else
set changeList to loweredList
end if
set otid to AppleScript's text item delimiters
considering case
set transposedString to ""
repeat with p from 1 to (count paragraphs in musicString)
set thisLine to paragraph p of musicString
if (thisLine contains " ") and (thisLine does not contain "t") then
-- change all chord names to a ©11, ©12, etc. code
repeat with c from 1 to (count chordList)
set thisLine to replaceString((item c of chordList), (item c of codeList), thisLine)
end repeat
-- change all codes to the shifted counterpart
repeat with c from 1 to (count codeList)
set thisLine to replaceString((item c of codeList), (item c of changeList), thisLine)
end repeat
set newLine to thisLine
else
set newLine to thisLine
end if
set transposedString to transposedString & newLine & return
end repeat
return transposedString
end considering
set AppleScript's text item delimiters to otid
end transposeChords
on replaceString(toFind, replaceWith, aString)
set AppleScript's text item delimiters to toFind
set aString to text items of aString
set AppleScript's text item delimiters to replaceWith
set aString to aString as string
end replaceString
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T02:47:10.433",
"Id": "440351",
"Score": "2",
"body": "If you just had the chords, this *could* be doable with a specialized lookup table (dealing with the sus and aug and slash is only a little harder). The formatting is another matter. Ideally, though, you want a real program which understands the notation, not something hacked together that does a blind translation of your requirements. My gut says this might be too large of a scope of a program for SO (ie answers would be far too long), but Im willing to be proven wrong. At the very least it’s an interesting problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T07:14:39.330",
"Id": "440352",
"Score": "2",
"body": "Hey @jweaks, I disagree somewhat with D Ben Knoble. I think this is very doable to a good degree of accuracy and speed. However, just to be extra sure what we're dealing with, can you paste a link to a formatted copy of the lyric/chord sheet on a site that preserves tabs and spaces as they are (SO has converted any tabs that might have been there into spaces, and I doubt the horizontal alignment of the chords is that pronounced at the source). Once you've done that, I'll see whether I'm still as confident. If you want to include more sample song sheets, that's fine and good too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T07:23:26.197",
"Id": "440353",
"Score": "0",
"body": "PS. I notice that, while you use a the letter `b` and the sign `#` in place of genuine flat/sharp symbols. Is that intentional, or something that some piece fo software limits you to, or a product of not previously knowing how to access those symbols for use in text: **`sharp: ♯` `flat: ♭`** There's a bunch of others too: **`♩ ♪ ♫ ♬ ♮ 〽︎ ⏔ ⏕ ⏖ ℟ ℣`** and a few more (they may not print well in SO's choice of font, but generally look good in most monospace situations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T15:07:30.480",
"Id": "440354",
"Score": "0",
"body": "Notation does not use tabs. It uses spaces to align the chord names, so no problem there. And yes, they use a lower case b and a number sign hash # for sharp. Plain text designed for monospace font."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T17:22:31.493",
"Id": "440355",
"Score": "0",
"body": "@jweaks - is there any particular way of identifying chord lines? All I can think are (1) to count through every line (skipping empty lines) and work on odd-numbered lines, or (b) look for lines with strings of multiple spaces. But neither approach feels particularly robust. There's no label or tag or common feature we can pick out that says (effectively) \"this is a chord line\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T19:19:50.233",
"Id": "440356",
"Score": "0",
"body": "Choosing lines with 3 spaces in a row is plenty robust. Technically, should be able to do 2 spaces in a row. Could also check that the line contains no \"t\" since I don't think a \"t\" occurs in any chord name notation. But not necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T06:09:59.420",
"Id": "440357",
"Score": "0",
"body": "If this gets closed, you might want to try posting this request over at MacScripter.net. They are a little more open to projects of this sort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T14:55:43.963",
"Id": "440374",
"Score": "0",
"body": "I would have loved to review this in Java, javascript or C#. But applescript is not my cup of tea :("
}
] |
[
{
"body": "<p>After working for a couple days, I came up with code that works. \nIt loops through paragraphs that match three spaces, and then finds/replaces each chord name, one a time, first changing them to a code, and then to the shifted chord.\nIt's not super robust, in that it uses arrays and repeat loops through them to alter the chords. It works fine thought since song sheets are not huge.\nStill, a regex change if possible would be more robust.</p>\n\n<pre><code>property chordList : {\"A#\", \"Bb\", \"C#\", \"Db\", \"D#\", \"Eb\", \"F#\", \"Gb\", \"G#\", \"Ab\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\"}\nproperty codeList : {\"©12\", \"©13\", \"©16\", \"©17\", \"©19\", \"©20\", \"©23\", \"©24\", \"©26\", \"©27\", \"©11\", \"©14\", \"©15\", \"©18\", \"©21\", \"©22\", \"©25\"}\nproperty loweredList : {\"A\", \"A\", \"C\", \"C\", \"D\", \"D\", \"F\", \"F\", \"G\", \"G\", \"Ab\", \"Bb\", \"B\", \"Db\", \"Eb\", \"E\", \"Gb\"}\nproperty raisedList : {\"B\", \"B\", \"D\", \"D\", \"E\", \"E\", \"G\", \"G\", \"A\", \"A\", \"A#\", \"C\", \"C#\", \"D#\", \"F\", \"F#\", \"G#\"}\n\nset theString to the clipboard\nset transposeUp to false -- true transposes up, false shifts down\n\nset newString to transposeChords(theString, transposeUp)\n\nset the clipboard to newString\n\non transposeChords(musicString, shiftUp)\n if shiftUp then\n set changeList to raisedList\n else\n set changeList to loweredList\n end if\n set otid to AppleScript's text item delimiters\n considering case\n set transposedString to \"\"\n repeat with p from 1 to (count paragraphs in musicString)\n set thisLine to paragraph p of musicString\n if (thisLine contains \" \") and (thisLine does not contain \"t\") then\n -- change all chord names to a ©11, ©12, etc. code\n repeat with c from 1 to (count chordList)\n set thisLine to replaceString((item c of chordList), (item c of codeList), thisLine)\n end repeat\n -- change all codes to the shifted counterpart\n repeat with c from 1 to (count codeList)\n set thisLine to replaceString((item c of codeList), (item c of changeList), thisLine)\n end repeat\n set newLine to thisLine\n else\n set newLine to thisLine\n end if\n set transposedString to transposedString & newLine & return\n end repeat\n return transposedString\n end considering\n set AppleScript's text item delimiters to otid\nend transposeChords\n\non replaceString(toFind, replaceWith, aString)\n set AppleScript's text item delimiters to toFind\n set aString to text items of aString\n set AppleScript's text item delimiters to replaceWith\n set aString to aString as string\nend replaceString\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-20T15:19:47.583",
"Id": "226563",
"ParentId": "226562",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T02:42:47.617",
"Id": "226562",
"Score": "1",
"Tags": [
"regex",
"music",
"applescript"
],
"Title": "Script to transpose chords in a song sheet"
}
|
226562
|
<p>In CentOS I have a Web Application Root on which I have a website directory.<br>
I would like to make an immediate backup of that website's directory by using the <code>zip</code> utility. The code works and tested.</p>
<p>Although I already use <code>set -x</code> and zipping is verbose (I'm not sure if due to <code>set -x</code> or <code>zip</code> default behavior), the trace is super long and hard to follow - I cant vertically-scroll all of the way top of it through Putty Window in Windows10 Home.<br>
I fear I don't have enough testing to ensure that the file was created, in what size (to assume the size is plausible) and such (maybe just adding <code>ls -la ${war}/mediawiki_general_backups</code>, is enough):</p>
<pre><code>date="$(date +%F-%T)"
war="$HOME/public_html" # Web Application Root
domain="example.com"
zip -r "${war}/mediawiki_general_backups/${domain}-directory-backup-${date}.zip" "${war}/${domain}"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T15:03:00.777",
"Id": "440377",
"Score": "0",
"body": "Theorizing on reasons/s for dislike would be extremely helpful"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T15:14:50.237",
"Id": "440378",
"Score": "1",
"body": "I didn't DV the question, but I suspect it's because the second-to-last paragraph reads like you're not _entirely_ sure if it works. That said, I see no functional discrepancies that would prevent it from working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T15:16:19.980",
"Id": "440379",
"Score": "0",
"body": "And I only make that assumption because there's also a close-vote on the question for \"Broken\", though I don't see the legitimacy of that either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:17:05.177",
"Id": "440391",
"Score": "0",
"body": "The code works in tested before. Please consider edit the question because I am not sure I understand what's wrong..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:32:12.063",
"Id": "440398",
"Score": "0",
"body": "I would recommend that you edit your question to make it clearer it works. When your write *\"Hence, I fear I might need a tiny bit more \"testing\" to see...\"* that kind of makes it unclear if your code works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:34:24.923",
"Id": "440401",
"Score": "0",
"body": "Okay, thank you --- just edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T06:02:40.127",
"Id": "440473",
"Score": "0",
"body": "Why are you using `set -x`? (that will expand each simple command in your script and display the output of each) That will make for very long output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T09:46:36.717",
"Id": "440483",
"Score": "0",
"body": "@DavidC.Rankin I use it in default because it is convenient for me; usually it does more good than harm in my work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:55:23.393",
"Id": "440576",
"Score": "0",
"body": "Sure, `set -x` is a great debugging tool. I comment was prompted by the vertical scrolling problem mentioned in your question."
}
] |
[
{
"body": "<p>Well, to be honest I am not exactly sure what do you want to review :) This isn't a script. It is just standard zip command.</p>\n\n<p>Maybe you should think about this: <code>${war}/mediawiki_general_backups/${domain}-directory-backup-${date}.zip</code>. It is too long and ugly. Try to add more these things into your script and a readability will be lost.</p>\n\n<blockquote>\n <p>I fear I don't have enough testing to ensure that the file was created,</p>\n</blockquote>\n\n<p>If you want to be sure, that the zip command finished sucessfully, just test it.</p>\n\n<pre><code>#!/usr/bin/env bash\n\n# Any subsequent(*) commands which fail will cause the shell script to exit immediately.\n# https://stackoverflow.com/a/2871034/10814755\n# Now i should trust the output of zip command. \nset -e\n\n#domain=$1 <- It could be useful, isn't?\ndomain=\"example.com\"\n\n#I omit application root. I thing is safer to keep backups away.\nbackup_path=\"/mediawiki_backups/${domain}/\"\nbackup_file=\"$(date +%F-%T).zip\"\n\n# You should trust the zip command, but sure is sure.\n# So if backup file exist...\n# ...and isn't empty...\nif [[ -f ${backup_path}${backup_file} ]] && [[ ! -s ${backup_path}${backup_file} ]]; then\n #... then do something brave :)\nelse\n echo \"Backup failed!\"\n exit 1\nfi\n\n</code></pre>\n\n<p>Regards :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T15:30:27.433",
"Id": "227099",
"ParentId": "226566",
"Score": "1"
}
},
{
"body": "<p>I recommend starting the script with a shebang so it can be executed as a program:</p>\n\n<pre><code>#!/bin/bash\n</code></pre>\n\n<p>As there's nothing in here that isn't standard shell, then we can make it leaner by using plain POSIX shell instead:</p>\n\n<pre><code>#!/bin/sh\n</code></pre>\n\n<p>I recommend <code>set -eu</code>, to cause the shell to abort in more error cases.</p>\n\n<p>We can save one fork by using <code>exec</code> for the final command. In either case, the exit status should indicate whether the command completed successfully (if running from <code>cron</code>, consider using <code>chronic</code> when running the script, to only be mailed about the failures).</p>\n\n<p>I question the use of <code>zip</code> as archive format - <code>tar</code> is generally installed on all Linux systems, and is the nearest we have to a standard. <code>zip</code> usually needs to be specifically added. Also, <code>tar</code> supports the <code>-C</code> option so that we can store relative paths in the archive, which may be useful if this backup is restored onto a new system with different file layout.</p>\n\n<p>And whilst your quoting is good, it's slightly over the top - variable assignment is implicitly double-quoted.</p>\n\n<pre><code>#!/bin/sh\n\ndate=$(date +%F-%T)\nwar=$HOME/public_html # Web Application Root\ndomain=example.com\narchive=mediawiki_general_backups/$domain-directory-backup-$date.tar.gz\n\nexec tar -C \"$war\" cfz \"$archive\" \"$domain\"\n</code></pre>\n\n<p>Finally, are you sure that's a good place to keep your backups? If the disk fails and you lose the site contents, you've probably lost the backups as well. I hope that this is only the first stage in making your backups and that you have a mechanism to transfer the archive files to offline media (preferably off-site) that you haven't shown us.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:25:09.667",
"Id": "441975",
"Score": "0",
"body": "Hi; thanks. I do have an external automatic backup system; AFAIK this entire shared server is backedup externally with daily backups for each user going 30 days backwards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:26:18.990",
"Id": "441976",
"Score": "0",
"body": "I misunderstand this passage: `And whilst your quoting is good, it's slightly over the top - variable assignment is implicitly double-quoted.`; everything is double quoted both in my example and yours... What did you mean than?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T07:54:07.763",
"Id": "442328",
"Score": "1",
"body": "What I mean is that `a=\"$b\"` can be written as just `a=$b` because word splitting and globbing don't occur in the context of variable assignment. It's not *wrong* to write the former, so if you like the consistency, just keep doing what you're doing!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T07:46:01.430",
"Id": "227158",
"ParentId": "226566",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227158",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T14:35:44.777",
"Id": "226566",
"Score": "1",
"Tags": [
"security",
"bash",
"linux"
],
"Title": "Creating a backup of a website directory inside the Web Application Root directory in *nix"
}
|
226566
|
<p>I implemented Linked List data structure in C++ for practice purpose. The <code>LinkedList.h</code> uses <code>Node.h</code> as nodes. Creates and insert nodes dynamically to the list. I included function descriptions as comments just above the functions.</p>
<p>I would like to receive comments and suggestions regarding the code, algorithms (although there aren't much), comment style (i suppose my comment style is a bit poor) and anything I missed.</p>
<p>I include a basic <code>main</code> function, if you would like to run the codes.</p>
<p><strong><code>Node.h</code></strong></p>
<pre><code>template <class T>
class Node {
public:
Node(const T& item);
Node(const T& item, Node<T>* nextNode);
Node<T>* next(void) const;
void insertNext(Node<T>* nextNode);
Node<T>* removeNext(void);
T getData(void) const;
void changeData(T& item);
private:
T data;
Node<T>* nextPtr;
};
/**
* @brief Default constructor.
* @param item Data to be stored in the node.
* @return void.
*
* The constructor initializes variables.
*/
template <class T>
Node<T>::Node(const T& item) {
data = item;
nextPtr = nullptr;
}
/**
* @brief Default constructor.
* @param item Data to be stored in the node.
* @param nextNode The next node of the node.
* @return void.
*
* The constructor initializes variables.
*/
template <class T>
Node<T>::Node(const T& item, Node<T>* nextNode) {
data = item;
nextPtr = nextNode;
}
/**
* @brief Returns the next node of the node.
* @param void.
* @return Node pointer of type T.
*/
template <class T>
Node<T>* Node<T>::next(void) const {
return nextPtr;
}
/**
* @brief Inserts a node after the node.
* @param nextNode Pointer to the node to be inserted.
* @return void.
*
* Inserts the nextNode after the node and chains nextNode to the
* old next of the node.
*
*/
template <class T>
void Node<T>::insertNext(Node<T>* nextNode) {
nextNode->nextPtr = nextPtr;
nextPtr = nextNode;
}
/**
* @brief Removes the nextPtr field of the node.
* @param void.
* @return Node of type T.
*
* Removes the nextPtr field and equates it to nullptr.
* Returns the removed pointer.
*
*/
template <class T>
Node<T>* Node<T>::removeNext(void) {
Node<T>* removedPtr = nextPtr;
nextPtr = nullptr;
return removedPtr;
}
/**
* @brief Retrieves the node data.
* @param void.
* @return Data of type T.
*/
template <class T>
T Node<T>::getData(void) const {
return data;
}
/**
* @brief Changes the node data.
* @param item The new data of the node.
* @return void.
*/
template <class T>
void Node<T>::changeData(T& item) {
data = item;
}
</code></pre>
<p><strong><code>LinkedList.h</code></strong></p>
<pre><code>#include "Node.h"
template<class T>
class LinkedList {
public:
LinkedList(void); //c'tor
LinkedList(const LinkedList<T>& copyList); //copy c'tor
~LinkedList(void); //d'tor
void insertAt(const T& item); //insert node at currPtr position
void insertAfter(const T& item); //insert node after currPtr position
void insertHead(const T& item); //insert node at headPtr position
void insertTail(const T& item); //insert node at tailPtr position
void removeAt(void); //remove the node at currPtr position
void removeHead(void); // remove the head node
void clear(void); //returns list to initial case
void freeNode(Node<T>* node); //free dynamic memory of a node
std::size_t size(void) const; //size of the list
bool empty(void) const; //the list is empty or not
T nodeData(Node<T>* node) const; //retrieve the input node data
void moveToHead(void);//move currPtr to headPtr position
void moveToTail(void); //move currPtr to tailPtr position
void moveToPos(int n); //move currPtr to nth position
int getPos(void) const; //the position of the currPtr
void print(std::ostream& os); //prints the LinkedList and private variables
private:
void init(void); //initializes private variables
Node<T>* headPtr; //ptr to head node
Node<T>* tailPtr; //ptr to tail node
Node<T>* currPtr; //ptr to current node
Node<T>* prevPtr; //ptr to previous node
std::size_t sizeL; //size of the linked list
Node<T>* newNode(const T& item); //allocate dynamic node
Node<T>* newNode(const T& item, Node<T>* nextNode); //allocate dynamic node
};
/**
* @brief Initializes class variables.
* @param void.
* @return void.
*
* The init function sets all pointer to nullptr and sizeL to 0.
*/
template <class T>
void LinkedList<T>::init(void) {
//ptr init
headPtr = nullptr;
tailPtr = nullptr;
currPtr = nullptr;
prevPtr = nullptr;
//sizeL init
sizeL = 0;
}
/**
* @brief Default constructor.
* @param void.
* @return void.
*
* The constructor uses init function to initialize variables.
*/
template <class T>
LinkedList<T>::LinkedList(void) {
init();
}
/**
* @brief Copy constructor.
* @param copyList The list to be copied.
* @return void.
*
* The copy constructor deepcopies the copyList to the object.
*/
template <class T>
LinkedList<T>::LinkedList(const LinkedList<T>& copyList) {
init();
Node<T>* tempPtr = copyList.headPtr;
for(std::size_t cnt=0; cnt<copyList.sizeL; cnt++) {
insertAfter(copyList.nodeData(tempPtr));
tempPtr = tempPtr->next();
}
moveToPos(copyList.getPos());
}
/**
* @brief Default destructor.
* @param void.
* @return void.
*
* The destructor uses clear function to release allocated memory.
*/
template <class T>
LinkedList<T>::~LinkedList(void) {
clear();
}
/**
* @brief Insert node to the LinkedList.
* @param item Data to be stored in the node.
* @return void.
*
* The insertAt function inserts a node to the location pointed by
* currPtr. The nodes following the currPtr are shifted whereas
* the nodes before the currPtr remain same.
*
* If currPtr is pointing head or the LinkedList is empty,
* the function uses insertHead function.The LinkedList grows
* dynamically.
*
* As a result of this function the currPtr points to the newly
* inserted node.
*/
template <class T>
void LinkedList<T>::insertAt(const T& item) {
if((currPtr == headPtr) || empty()) {
insertHead(item);
} else {
Node<T>* tempPtr = newNode(item); //get a new node
prevPtr->insertNext(tempPtr); //insert it after prevPtr
currPtr = tempPtr; //arrange currPtr
sizeL += 1; //sizeL increments
}
}
/**
* @brief Insert node to the LinkedList.
* @param item Data to be stored in the node.
* @return void.
*
* The insertAfter function inserts a node to the next of location
* pointed by currPtr. The nodes following the currPtr are shifted
* whereas the node currPtr and preceding nodes remain same.
*
* If currPtr is pointing tail, the function uses insertTail
* function. The LinkedList grows dynamically.
*
* If the LinkedList is empty, the function uses insertHead
* function.
*
* As a result of this function the currPtr points to the newly
* inserted node.
*/
template <class T>
void LinkedList<T>::insertAfter(const T& item) {
if(empty()) {
insertHead(item);
} else if(currPtr == tailPtr) {
insertTail(item);
} else {
Node<T>* tempPtr = newNode(item); //get a new node
currPtr->insertNext(tempPtr); //insert it after prevPtr
prevPtr = currPtr; //arrange prevPtr
currPtr = tempPtr; //arrange currPtr
sizeL += 1; //sizeL increments
}
}
/**
* @brief Insert node to the head of the LinkedList.
* @param item Data to be stored in the node.
* @return void.
*
* The insertHead function inserts a node to the head location
* of the LinkedList. The nodes following the headPtr are shifted.
*
* As a result of this function the currPtr points to the newly
* inserted head node.
*/
template <class T>
void LinkedList<T>::insertHead(const T& item) {
if(empty()) {
Node<T>* tempPtr = newNode(item); //get a new node
headPtr = currPtr = tailPtr = tempPtr; /* arrange headPtr, currPtr,
tailPtr */
sizeL = 1; //sizeL is 1
} else {
Node<T>* tempPtr = newNode(item, headPtr); //get a new node
headPtr = currPtr = tempPtr; // arrange headPtr, currPtr
prevPtr = nullptr; //arrange prevPtr
sizeL += 1; //sizeL increments
}
}
/**
* @brief Insert node to the tail of the LinkedList.
* @param item Data to be stored in the node.
* @return void.
*
* The insertTail function inserts a node to the tail location
* of the LinkedList.
*
* If the LinkedList empty, insertTail function uses insertHead function.
*
* As a result of this function the currPtr points to the newly
* inserted tail node.
*/
template <class T>
void LinkedList<T>::insertTail(const T& item) {
if(empty()) {
insertHead(item);
} else {
Node<T>* tempPtr = newNode(item); //get a new node
prevPtr = tailPtr;
tailPtr->insertNext(tempPtr); //insert it after tailPtr
currPtr = tailPtr = tempPtr; //arrange currPtr, tailPtr
sizeL += 1; //sizeL increments
}
}
/**
* @brief Remove the node pointed by currPtr.
* @param void.
* @return void.
*
* The removeAt function removes the node pointed by currPtr. The node
* following is the new currPtr and is chained to prevPtr.
*
* If the currPtr points to head, removeAt function uses
* removeHead function.
*
* If currPtr points to tail, the preceding node is the new currPtr.
*
* If the LinkedList becomes empty after removal,
* the variables are reset to initial states.
*
*
*/
template <class T>
void LinkedList<T>::removeAt(void) {
if(empty()) {
std::cerr << "The LinkedList empty. Can't remove current node." << '\n';
} else if(size() == 1) {
clear();
} else if(currPtr == headPtr) {
removeHead();
} else if(currPtr == tailPtr) {
freeNode(currPtr); //delete currPtr
tailPtr = prevPtr; //arrange tailPtr
sizeL -= 1; // decrement sizeL
moveToTail(); // move currPtr to tailPtr
} else {
Node<T>* tempPtr = currPtr->next(); //hold next of currPtr
currPtr->insertNext(prevPtr); /* insert prevPtr to the next of currPtr.
currPtr is out of list */
freeNode(currPtr); //delete currPtr
currPtr = tempPtr; //arrange currPtr
sizeL -= 1;
}
}
/**
* @brief Remove the node pointed by headPtr.
* @param void.
* @return void.
*
* The removeHead function removes the node pointed by headPtr. The node
* following is the new headPtr.
*
* If the currPtr points to head, currPtr is updated to new headPtr.
*
* If the prevPtr points to head, prevPtr is updated as nullptr.
*/
template <class T>
void LinkedList<T>::removeHead(void) {
if(empty()) {
std::cerr << "The LinkedList empty. Can't remove head node." << '\n';
} else if(size() == 1) {
clear();
} else if(currPtr == headPtr) {
Node<T>* tempPtr = headPtr->next(); //hold next of headPtr
freeNode(headPtr); //delete headPtr
headPtr = tempPtr; //arrange headPtr
sizeL -= 1; //decrements sizeL
currPtr = headPtr; //arrange currPtr
} else if (prevPtr == headPtr) {
Node<T>* tempPtr = headPtr->next(); //hold next of headPtr
freeNode(headPtr); //delete headPtr
headPtr = tempPtr; //arrange headPtr
sizeL -= 1; //decrements sizeL
prevPtr = nullptr; //arrange currPtr
} else {
Node<T>* tempPtr = headPtr->next(); //hold next of headPtr
freeNode(headPtr); //delete headPtr
headPtr = tempPtr; //arrange headPtr
sizeL -= 1; //decrements sizeL
}
}
/**
* @brief Returns the LinkedList to its initial state.
* @param void.
* @return void.
*
* The clear function deletes all nodes in the LinkedList and returns
* all variables to their initial state.
*/
template <class T>
void LinkedList<T>::clear(void) {
moveToHead();
Node<T>* tempPtr;
for(std::size_t cnt=0; cnt<sizeL; cnt++) {
tempPtr = currPtr->next(); //hold next of currPtr
freeNode(currPtr); //delete currPtr
currPtr = tempPtr; //arrange currPtr
}
init();
}
/**
* @brief Releases allocated dynamic memory of a node.
* @param node The pointer to the target node.
* @return void.
*/
template <class T>
void LinkedList<T>::freeNode(Node<T>* node) {
delete node;
}
/**
* @brief Returns the LinkedList size.
* @param void.
* @return size
*/
template <class T>
std::size_t LinkedList<T>::size(void) const {
return sizeL;
}
/**
* @brief Returns true if the LinkedList empty,
* @brief false otherwise.
* @param void.
* @return Boolean value true or false.
*/
template <class T>
bool LinkedList<T>::empty(void) const {
return (sizeL == 0);
}
/**
* @brief Returns the data stored in the specified node.
* @param node The target node.
* @return The data stored in the node of type T.
*/
template <class T>
T LinkedList<T>::nodeData(Node<T>* node) const {
return node->getData();
}
/**
* @brief Move currPtr to headPtr.
* @param void.
* @return void.
*
* The moveToHead function moves currPtr to headPtr.
*/
template <class T>
void LinkedList<T>::moveToHead(void) {
currPtr = headPtr;
prevPtr = nullptr;
}
/**
* @brief Move currPtr to tailPtr.
* @param void.
* @return void.
*
* The moveToTail function uses moveToHead function with
* parameter (sizeL - 1) to move currPtr to tailPtr.
*/
template<class T>
void LinkedList<T>::moveToTail(void) {
moveToPos(sizeL - 1);
}
/**
* @brief Move currPtr to nth node of the LinkedList.
* @param n Position of the target node where n € [0 , sizeL - 1].
* @return void.
*
* The moveToPos function iterates over the LinkedList nodes to move
* currPtr to the nth node of the LinkedList. n is in
* the range of [0 , sizeL - 1].
*
* The moveToPos function uses moveToHead function to move currPtr
* to headPtr.
*/
template <class T>
void LinkedList<T>::moveToPos(int n) {
moveToHead();
for(int cnt=0; cnt<n; cnt++) {
prevPtr = currPtr;
currPtr = currPtr->next();
}
}
/**
* @brief Returns the position of the currPtr
* @param void.
* @return Integer representing position of the currPtr.
*
* The getPost function iterates over the list until reaches the currPtr.
* Then returns the position of the currPtr as int.
*/
template <class T>
int LinkedList<T>::getPos(void) const {
Node<T>* tempPtr = headPtr;
int cnt;
for(cnt=0; tempPtr!=currPtr; cnt++) {
tempPtr = tempPtr->next();
}
return cnt;
}
/**
* @brief Creates a dynamic Node of type T.
* @param item Data to be stored in the new node.
* @return void.
*
* Returns a pointer to node created dynamically. The new node's data is
* item of type T. The new node's next pointer is nullptr.
*/
template <class T>
Node<T>* LinkedList<T>::newNode(const T& item) {
Node<T>* tempPtr = nullptr;
tempPtr = new Node<T>(item);
if(tempPtr == nullptr) {
std::cerr << "Memory allocation for new node is failed" << '\n';
return nullptr;
} else {
return tempPtr;
}
}
/**
* @brief Creates a dynamic Node of type T.
* @param item Data to be stored in the new node.
* @param nextNode The next node of the new node.
* @return void.
*
* Returns a pointer to node created dynamically. The new node's data is
* item of type T. The new node's next pointer is nextNode of type T.
*/
template <class T>
Node<T>* LinkedList<T>::newNode(const T& item, Node<T>* nextNode) {
Node<T>* tempPtr = nullptr;
tempPtr = new Node<T>(item, nextNode);
if(tempPtr == nullptr) {
std::cerr << "Memory allocation for new node is failed" << '\n';
return nullptr;
} else {
return tempPtr;
}
}
/**
* @brief Prints the LinkedList nodes together with private variables.
* @param os The printing medium.
* @return void.
*/
template <class T>
void LinkedList<T>::print(std::ostream& os) {
os << "Class Variables:\n";
//headPtr
if(headPtr == nullptr)
os << "headPtr: " << "nullptr" << " | ";
else
os << "headPtr: " << headPtr << ' ' << nodeData(headPtr) << " | ";
//prevPtr
if(prevPtr == nullptr)
os << "prevPtr: " << "nullptr" << '\n';
else
os << "prevPtr: " << prevPtr << ' ' << nodeData(prevPtr) << '\n';
//tailPtr
if(tailPtr == nullptr)
os << "tailPtr: " << "nullptr" << " | ";
else
os << "tailPtr: " << tailPtr << ' ' << nodeData(tailPtr) << " | ";
//currPtr
if(currPtr == nullptr)
os << "currPtr: " << "nullptr" << '\n';
else
os << "currPtr: " << currPtr << ' '<< nodeData(currPtr) << '\n';
//sizeL
os << "sizeL: " << sizeL << '\n';
Node<T>* tempPtr = headPtr;
for(std::size_t cnt=0; cnt<sizeL; cnt++) {
os << nodeData(tempPtr) << " -> ";
tempPtr = tempPtr->next();
}
os << '\n';
}
</code></pre>
<p><strong><code>Test Code</code></strong></p>
<pre><code>#include "LinkedList.h"
int main() {
LinkedList<int> MyList;
for(int i=1; i<7; i++)
MyList.insertAfter(i);
MyList.print(std::cout);
MyList.moveToPos(3);
MyList.print(std::cout);
MyList.removeAt();
MyList.print(std::cout);
MyList.insertAt(9);
MyList.print(std::cout);
MyList.insertAfter(10);
MyList.print(std::cout);
MyList.removeAt();
MyList.print(std::cout);
MyList.removeAt();
MyList.moveToPos(3);
MyList.print(std::cout);
std::cout << "********************" << '\n';
LinkedList<int> CopiedList(MyList);
CopiedList.print(std::cout);
std::cout << "********************" << '\n';
MyList.moveToHead();
MyList.print(std::cout);
MyList.removeHead();
MyList.removeHead();
MyList.removeAt();
MyList.removeAt();
MyList.removeAt();
MyList.removeAt();
MyList.print(std::cout);
std::cout << "********************" << '\n';
CopiedList.print(std::cout);
std::cout << "********************" << '\n';
for(int i=1; i<6; i++)
MyList.insertHead(i);
MyList.print(std::cout);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:53:12.820",
"Id": "440413",
"Score": "2",
"body": "I'd like for the downvoter (who's probably the close voter) to explain the reasoning behind this. It seems like a well written question with clear description and + from a new contributor, I think it's bad faith to act like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T10:01:05.903",
"Id": "440484",
"Score": "1",
"body": "Currently, CR is a bit buggy when it comes to code fences. Your code may end up having an unwanted three backticks at the end. You can work around this issue by using indentation instead of code fences. (You can select the code and press Ctrl-K.) Also, don’t be discouraged by occasional illogical downvotes."
}
] |
[
{
"body": "<h2>Comments</h2>\n\n<p>Comments should be meaningful. Yours are not. Writing comments that just repeat the code are actual harmful rather than helpful. Over time the comments and code will diverge (as bugs are found and fixed). Then a maintainer that is reading code and comments will find a discrepancy, does he fix a comment or the code? They can probably find out using the source control but its a huge waste of time.</p>\n\n<p>Comments should be reserved to explain <strong>WHY</strong> something is done. Use self documenting code (good variable/function/type names) to document <strong>HOW</strong>.</p>\n\n<p>Comments could also be used to explain algorithms where the code is complex or to put a link to where the algorithm is explained (if you know the link will last).</p>\n\nExample\n\n<pre><code>/**\n * @brief Inserts a node after the node.\n * @param nextNode Pointer to the node to be inserted.\n * @return void.\n *\n * Inserts the nextNode after the node and chains nextNode to the\n * old next of the node.\n *\n */\ntemplate <class T>\nvoid Node<T>::insertNext(Node<T>* nextNode) {\n nextNode->nextPtr = nextPtr;\n nextPtr = nextNode;\n}\n</code></pre>\n\n<p>Did that comment tell me anything I could not understand by simply reading the name of the function <code>insertNext()</code> and the two lines of code!</p>\n\n<h2>Design</h2>\n\n<p>You have implemented a singly linked list. Sure but this is actually harder to do than implement a doubly linked list. As a result I am sure I will find a bug. The tiny amount of extra design will simplify your code tremendously.</p>\n\n<p>You have implemented the list using <code>null</code> to mark the terminator. If you look up a technique called <code>Sentinel List</code> you will find a technique that removes the need for <code>null</code>. By removing the need for <code>null</code> your code will be highly simplified as you don't need to special case inserting into an empty list or and the head/tail of a list it is all simply an insertion into the list.</p>\n\n<p>You maintain state about the internal \"current\" position. Could not see any errors but it seemed all a bit doggey and makes the code complex. I would dump this functionality and just ask the user to pass a position for insertion/deleting/getting.</p>\n\n<h2>High Level Code</h2>\n\n<p>Making it as a top level type you have exposed an implementation detail of the class. This is bad design as it locks you into using that implementation.</p>\n\n<p>Also because you have made it a top level type you have overcomplicated it (presumably to prevent abuse). But a class that should have been 6 lines top takes a 100 lines of vertical space. That's an unnecessary cognitive load to put on the maintainer.</p>\n\n<h2>Idioms</h2>\n\n<p>Your linked list holds pointers. But I don't see you obeying the rule of 3/5. You should look it up and read it.</p>\n\n<p>But without reading the code I bet the following does strange things.</p>\n\n<pre><code>MyList<int> listA;\nlistA.insertHead(1);\n\nMyList<int> listB;\nlistB = listA; // Uses the compiler generated copy assignment\n // If you don't define one the compiler does.\n // When you'r class has pointers make sure\n // you define the methods the compiler may\n // generate automatic implantations off.\nlistB.insertHead(2);\n</code></pre>\n\n<p>How many items are in <code>listA</code>?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">What is The Rule of Three?</a><br>\n<a href=\"https://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11\">Rule-of-Three becomes Rule-of-Five with C++11?\n</a></p>\n\n<h2>More Reading</h2>\n\n<p>Have a look at this review.<br>\n<a href=\"https://codereview.stackexchange.com/a/126007/507\">https://codereview.stackexchange.com/a/126007/507</a></p>\n\n<h2>Code Review</h2>\n\n<pre><code>template <class T>\nclass Node {\n public:\n Node(const T& item);\n Node(const T& item, Node<T>* nextNode);\n Node<T>* next(void) const;\n void insertNext(Node<T>* nextNode);\n Node<T>* removeNext(void);\n T getData(void) const;\n void changeData(T& item);\n private:\n T data;\n Node<T>* nextPtr;\n};\n</code></pre>\n\n<p>MY class would simply have been:</p>\n\n<pre><code>template<typename T>\ntemplate List\n{\n struct Node // Here Node is a private member of the class.\n { // As long as you don't expose a Node through\n T data; // the list interface its implementation is private.\n Node* next; // Thus adding member access functions is superfluous.\n Node* prev; // as only you can use the node.\n }\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>In constructors prefer to use initializer lists rather code blocks to initialize the data. This is because if you don't specifically specify initializer list items then the compiler is going to generate them for you.</p>\n\n<pre><code>Node<T>::Node(const T& item) {\n data = item;\n nextPtr = nullptr;\n}\n</code></pre>\n\n<p>The above code is equivalent to:</p>\n\n<pre><code>Node<T>::Node(const T& item)\n : data() // default initialization of the type T\n{ // So you will call the constructor of T here.\n // Not a big deal for integers but what if T\n // has an expensive type?\n\n data = item; // Here you are calling the assignment operator.\n // So now you have called the constructor\n // followed by a copy assignment.\n nextPtr = nullptr;\n}\n</code></pre>\n\n<p>You should have written like this:</p>\n\n<pre><code>Node<T>::Node(const T& item)\n : data(item)\n , nextPtr(nullptr)\n{}\n</code></pre>\n\n<hr>\n\n<p>I don't see a move constructor?</p>\n\n<pre><code>Node<T>::Node(T&& item) // Notice the double &&\n : data(std::move(item))\n , nextPtr(nullptr)\n{}\n</code></pre>\n\n<p>Here if T is expensive to construct we can move the object into the node. Move semantics has been a standard part of the language since C++11 (8 years).</p>\n\n<p>Sometimes it is also nice to have a construct in place constructor. It may be cheap to pass the parameters to construct a T rather than passing around a T. To do this you need to use var arg templates so a bit more complicated syntactically.</p>\n\n<pre><code>template<typename... Args> // Variable number of arguments.\nNode<T>::Node(Args&& args...)\n : data(std::forward<Args>(args)...) // Arguments forwarded to constructor\n , nextPtr(nullptr)\n{}\n</code></pre>\n\n<hr>\n\n<p>Return value (of containers) by reference.</p>\n\n<pre><code>T Node<T>::getData(void) const {\n return data;\n}\n</code></pre>\n\n<p>Here you are returning y value this means you are creating a copy of the body to return. If T is expensive to copy this is probably not what you want to do.</p>\n\n<pre><code>T const& Node<T>::getData(void) const {\n ^^^^^^\n return data;\n}\n</code></pre>\n\n<hr>\n\n<p>Pass parameters by const reference (rather than reference).</p>\n\n<pre><code>void Node<T>::changeData(T& item) {\n data = item;\n}\n</code></pre>\n\n<p>Unless you explicitly want to modify item then you should pass it be const reference. Also without the const you can not pass temporary object to this function.</p>\n\n<pre><code>struct X {\n X(int x) /* constructor */ {}\n};\n\nNode<T> node(5); // This is allowed as the constructor takes by const ref.\nnode.changeData(6); // Not allowed as we need to construct a temporary X here.\n // You can not pass a reference to a temporary object.\n // A const reference is OK.\n</code></pre>\n\n<p>Again you may want to add a move version of this interface.</p>\n\n<hr>\n\n<p>Don't print error messages from inside structures.<br>\nThrow an exception and allow the business logic externally decide if it wants to print an error message.</p>\n\n<pre><code>void LinkedList<T>::removeAt(void) {\n if(empty()) {\n std::cerr << \"The LinkedList empty. Can't remove current node.\" << '\\n';\n // Throw an exception if you want the message.\n // or simply ignore if it is not an error to remove from an empty list.\n } \n</code></pre>\n\n<hr>\n\n<p>This seems a bit redundant.</p>\n\n<pre><code>void LinkedList<T>::freeNode(Node<T>* node) {\n delete node;\n}\n</code></pre>\n\n<p>Why call <code>freeNode(node)l</code> when you could just call <code>delete node;</code>?</p>\n\n<hr>\n\n<p>Two line initialization should be avoided:</p>\n\n<pre><code> Node<T>* tempPtr = nullptr;\n tempPtr = new Node<T>(item);\n</code></pre>\n\n<p>Prefer to simply create and initialize:</p>\n\n<pre><code> Node<T>* tempPtr = new Node<T>(item);\n</code></pre>\n\n<hr>\n\n<p>The action <code>new</code> never returns <code>nullptr</code>. If it fails to allocate then it will throw an exception.</p>\n\n<pre><code> if(tempPtr == nullptr) {\n std::cerr << \"Memory allocation for new node is failed\" << '\\n';\n return nullptr;\n } else {\n return tempPtr;\n }\n</code></pre>\n\n<p>Which is lucky for you. You return a null pointer but all your code assumes that this function never returns a <code>nullptr</code> and uses it as if the value was always good.</p>\n\n<p>This is really shitty design and you lucked out in that the new would never give you a bad value.</p>\n\n<hr>\n\n<p>Sure:\nNote: printing should not change the class so mark it const.</p>\n\n<pre><code>void LinkedList<T>::print(std::ostream& os) const {\n // ^^^^^\n ...\n}\n</code></pre>\n\n<p>But why not also make it work like a normal C++ streaming object.</p>\n\n<pre><code>friend std::ostream& operator<<(std::ostream& str, LinkedList const& data) {\n data.print(str);\n return str;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T21:44:30.890",
"Id": "440560",
"Score": "0",
"body": "thank you (even though such comments are discouraged by CR) for such a detailed evaluation. I have a lot to learn from this answer. I will go over this line by line definitely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T23:43:47.547",
"Id": "440580",
"Score": "1",
"body": "I think it's important to separate ***internal*** comments (in-line commentary) from ***external*** comments (documentation). Internal comments are useful for **code maintainers**. As you said, those comments should be kept short and crisp, explaining the \"**why**\" instead of the \"**what**\". External comments (documentation) are used by **code consumers** who don't care about the \"**why**\". Instead, they ***need*** the \"**what**\". Consumers ***need*** explicit documentation since they need to figure out which function to call, not how those functions work."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T11:00:21.747",
"Id": "226620",
"ParentId": "226572",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p>Strip out all your comments.</p>\n\n<p>The best of them are just unbelievably redundant, as they just restate the code, using as many words as feasible.</p>\n\n<p>A different Q&A going more into the comments is \"<em><a href=\"https://codereview.stackexchange.com/questions/90111/guessing-a-number-but-comments-concerning\">Guessing a number, but comments concerning</a></em>\".</p></li>\n<li><p>Reduce <code>Node</code> to the bare necessities, and make it a private member of <code>List</code>.</p>\n\n<p>It's an implementation-detail of it, and giving it an elaborate interface and its own invariants to maintain needlessly complicates things.</p>\n\n<pre><code>struct Node {\n struct Node* link;\n T data;\n};\n</code></pre></li>\n<li><p>Only application-code can have a good reason to interact directly with the user without explicit request. All other code should refrain from doing so, instead using exceptions, error-codes and error-values to delegate the choice to the caller.<br>\nComposability, reusability and testability suffer if this basic point is violated.</p></li>\n<li><p>Use the ctor-init-list to initialize the members, that's what it's for. Put the tear-down directly into the dtor, and you can implement <code>.clear()</code> by swapping with a temporary.</p></li>\n<li><p>If you use pointers-to-pointers, you can dispense with all the special-casing.</p></li>\n<li><p>Implement a proper iterator-interface:</p>\n\n<ol>\n<li>You can dispense with the band-aid of the internal iterator.</li>\n<li>You can use standard algorithms. Use them to implement your convenience-functions, unless you drop them completely as redundant.</li>\n<li>You can stop keeping track of any but the first node, only allowing insertion at the head or given an iterator.</li>\n</ol>\n\n<p>All those aspects simplify the implementation and make the abstraction more useful.</p></li>\n<li><p>Keep to the standard interface where possible. While doing your own thing may be fun, the jarring inconvenience is unsupportable. This is not a fashion show.</p></li>\n<li><p><code>pointer == nullptr</code> can be simplified to <code>!pointer</code>. Just like <code>pointer != nullptr</code> is nearly always equivalent to <code>pointer</code>, though where the exact type is important <code>!!pointer</code> works.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T21:53:17.520",
"Id": "440561",
"Score": "0",
"body": "I was always unsure about my commenting, suggestion `1` will work a lot for me. May I request a bit more information on suggestions `4` and `5`? Regarding `4`, releasing memory in directly destructor is okay, but I didn't understand implementing `.clear()` by swapping with a temporary. Regarding `5`, do you mean the special cases like in `insert` and `remove` functions? How does pointer-to-pointer use avoid those cases (I just need some more keywords to search)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:10:36.313",
"Id": "440564",
"Score": "1",
"body": "The copy-and-swap idiom is a common way to implement efficient and exception-safe (copy-/move-) assignment. (There are reasons it might not be right for move-assignment.) Instead of copying an argument, for `.clear()` just use a default-initialized temporary. Regarding double-pointers, the insert-pointer should point to the place where the address of the new node should be stored, not either to the node containing it or be null."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:05:47.083",
"Id": "226637",
"ParentId": "226572",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226620",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:06:04.990",
"Id": "226572",
"Score": "3",
"Tags": [
"c++",
"linked-list"
],
"Title": "LinkedList using Node Class in C++"
}
|
226572
|
<p>This is a "Help me make a choice" script where the user can input two options and then, based on the (3) reasons why they are good options, and the reasons weight the script will tell you which option you should choose.</p>
<p>This is my first Python script based on an idea I had and I'd like to know how I could make it better. For example, should I store the reasons (ie. option1a) in a list, dictionary or keep them in variables? Should I do the same to the weight (ie. option1aw) of each option?</p>
<p>The code works and does what I wanted it to do, but I don't know if I did in the best way possible.</p>
<pre><code>import random
print("First, tell me what your options are.")
option1 = input("Option 1: ")
option2 = input("Ok. Now tell me the other option: ")
option1a = input("\nGood. Now tell me a reason why \'{}\' is a good choice: ".format(option1))
option1b = input("Ok. Now tell me another reason why \'{}\' is a good choice: ".format(option1))
option1c = input("Ok. Now tell me another reason why \'{}\' is a good choice: ".format(option1))
option2a = input("\nThats all for \'{}\'. Now tell me why \'{}\' is a good choice: ".format(option1, option2))
option2b = input("Now tell me another reason why \'{}\' is a good choice: ".format(option2))
option2c = input("Now tell me another reason why \'{}\' is a good choice: ".format(option2))
option1aw = int(input("\nNow let's evaluate the options. Regarding \'{}\', "
"from 1 to 5, tell me how important is \'{}\'? ".format(option1, option1a)))
option1bw = int(input("Still regarding \'{}\', from 1 to 5, tell me how important is \'{}\'? ".format(option1, option1b)))
option1cw = int(input("How about \'{}\', from 1 to 5, tell me how important it is: ".format(option1c)))
option2aw = int(input("\nNow let's evaluate the rest of the options. Regarding \'{}\',"
" from 1 to 5, tell me how important is \'{}\'? ".format(option2, option2a)))
option2bw = int(input("Still regarding \'{}\', from 1 to 5, tell me how important is \'{}\'? ".format(option2, option2b)))
option2cw = int(input("How about \'{}\', from 1 to 5, tell me how important it is: ".format(option2c)))
prompt = input("\nWe'll calculate now. Click enter when you are ready to see the results. > ")
option1result = option1aw + option1bw + option1cw
option2result = option2aw + option2bw + option2cw
options = [option1, option2]
def coinflip():
print("Your best choice is:")
print(options[random.randint(0, len(options)-1)])
if option1result > option2result:
print("\n\'{}\' is your best choice based on the reasons you gave me. ".format(option1))
elif option1result == option2result:
print("\nHonestly, both are good options. Do you want to flip a coin? Press enter. ")
input()
coinflip()
else:
print("\n\'{}\' is your best choice based on the reasons you gave me. ".format(option2))
quit()
</code></pre>
|
[] |
[
{
"body": "<h2>Data instead of code</h2>\n\n<p>You have a lot of repeated calls to input. This should really just be a tuple of strings that all refer to a choices dict; something like:</p>\n\n<pre><code>choices = {}\n\nprompts = (\n ('option1': 'Option 1:'), \n # ...\n ('option1a': 'Good. Now tell me a reason why {option1} is a good choice: '),\n # ...\n)\n\nfor name, prompt in prompts:\n choices[name] = input(prompt.format(**choices))\n</code></pre>\n\n<h2>Global code</h2>\n\n<p>Move most of your global statements into functions, with a top-level <code>main</code> function.</p>\n\n<h2>Quit</h2>\n\n<p>...at the end is redundant.</p>\n\n<h2>The illusion of choice</h2>\n\n<p>Don't ask the user whether they want to flip a coin, only to do it anyway. Either given them an actual choice, or just say that it's going to happen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T18:38:44.067",
"Id": "440430",
"Score": "0",
"body": "Thank you for your reply @Reinderien. I love the Illusion of choice in the end!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T17:40:27.443",
"Id": "226581",
"ParentId": "226574",
"Score": "6"
}
},
{
"body": "<ol>\n<li>I think your program would be easier to use and create if you rearrange when you ask your questions. (This is mostly to show that I have consciously changed how your program works)</li>\n<li><p>You are correct it would be easier to use your data if you enter it as a <em>dictionary</em> and some <em>lists</em>. I personally would use the following layout:</p>\n\n<pre><code>option_1 = {\n 'option': option1,\n 'reasons': [option1a, option1b, option1c],\n 'weights': [option1aw, option1bw, option1cw],\n}\n</code></pre>\n\n<p>This allows getting the relevant by indexing the objects.<br>\nFor example to get the entered option you can do:</p>\n\n<pre><code>option_1['option']\n</code></pre>\n\n<p>To get the first reason you can do:</p>\n\n<pre><code>option_1['option'][0]\n</code></pre>\n\n<p>It should be noted that lists in Python, and most programming languages, are indexed starting at 0, which is why to get the first value we see the 0 above.</p></li>\n<li><p>Reduce your workload by using <em>functions</em>, these allow you to define a set of instructions to run which you can then reuse by calling the function.</p>\n\n<p>Take the following function to get an option:<br>\n<sub><strong>Note</strong>: I have changed the questions in this code snippet.</sub></p>\n\n<pre><code>def get_option():\n return {\n 'option': input('Enter an option: '),\n 'reasons': [\n input(f'Option 1: Why is this a good option? '),\n input(f'Option 2: Why is this a good option? '),\n input(f'Option 3: Why is this a good option? '),\n ],\n 'weights': [\n int(input(f'How important is Option 1? (from 1-5) ')),\n int(input(f'How important is Option 2? (from 1-5) ')),\n int(input(f'How important is Option 3? (from 1-5) ')),\n ]\n }\n</code></pre></li>\n<li><p>Allowing a user to enter two options is now simple. You make a list with both of them.</p>\n\n<pre><code>options = [\n get_option(),\n get_option(),\n]\n</code></pre></li>\n<li><p>Before we go any further I'd like to show you my favorite feature of Python - list comprehensions. These allow you to perform a task on a list in a single line. Take the above code snippet to generate two options, we can rewrite that using standard list generation methods exposed in Python and other languages, which would look like:</p>\n\n<pre><code>options = [] # Build an empty list\nfor _ in range(2): # Loop twice\n options.append(get_option()) # Add an option to options on each loop\n</code></pre>\n\n<p>However this pattern is rather messy and it would be more Pythonic to use a comprehension here.</p>\n\n<pre><code>options = [\n get_option()\n for _ in range(2)\n]\n</code></pre>\n\n<p>You should be able to notice we can also use this to simplify our <code>get_option</code> code.</p>\n\n<pre><code>def get_option():\n return {\n 'option': input('Enter an option: '),\n 'reasons': [\n input(f'Reason {i+1}: Why is this a good option? ')\n for i in range(3)\n ],\n 'weights': [\n int(input(f'How important is Reason {i+1}? (from 1-5) '))\n for i in range(3)\n ]\n }\n</code></pre></li>\n<li><p>From here we can change your <code>option1result</code> and <code>option2result</code> to:</p>\n\n<pre><code>results = [sum(option['weights']) for option in options]\n</code></pre></li>\n<li><p>You can use <code>random.choice</code> to chose from a list.</p></li>\n<li>It is best practice to use an <code>if __name__ == '__main__':</code> guard to prevent your code from running unless it's the main program.</li>\n<li>Don't use <code>quit</code>, if you remove it the program will exit successfully.</li>\n</ol>\n\n\n\n<pre><code>import random\n\n\ndef get_option():\n return {\n 'option': input('Enter an option: '),\n 'reasons': [\n input(f'Reason {i+1}: Why is this a good option? ')\n for i in range(3)\n ],\n 'weights': [\n int(input(f'How important is Reason {i+1}? (from 1-5) '))\n for i in range(3)\n ]\n }\n\n\nif __name__ == '__main__':\n print('First, tell me what your options are.')\n options = [\n get_option()\n for _ in range(2)\n ]\n prompt = input('\\nWe will calculate now.\\n')\n\n results = [sum(option['weights']) for option in options]\n if results[0] == results[1]:\n input('There are multiple best options.\\nThe best will be determined by coinflip.\\n')\n best_option = random.choice(options)\n else:\n best_option = options[0] if results[0] > results[1] else results[1]\n\n print('Your best choice is:')\n print(options[0]['option'])\n</code></pre>\n\n<p>Additional improvements:</p>\n\n<ol>\n<li><p>Your code only currently works for two options. To get the top options for any amount of options is fairly simple.</p>\n\n<p>You want a dictionary that holds all the options with a certain total weight. After this you just want to take the max weight, which will give you all the options with that weight.</p>\n\n<p>Once you have have the best options the code is pretty much the same, if there are multiple options then you just use <code>random.choice</code> on them to narrow them down to one.</p></li>\n<li><p>You should allow your user to enter how many options and reasons they want. This now is just a simple question you can ask before entering either loop.</p></li>\n<li>The way you get user input is error prone, if I enter <code>a</code> as my weight then your code blows up.<br>\nYou should also take into account that you've told your user that only 1-5 are valid entries, but happily allow -1, and 6.</li>\n<li>Not displaying all the best options seems like a poor oversight. Since we know all the best options we can just display them by looping.</li>\n</ol>\n\n<p>Ignoring 3 this can get:</p>\n\n<pre><code>import random\n\n\ndef get_option():\n option = input('Enter an option: ')\n reasons = int(input('How many reasons do you have for this option? '))\n return {\n 'option': option,\n 'reasons': [\n input(f'Reason {i+1}: Why is this a good option? ')\n for i in range(reasons)\n ],\n 'weights': [\n int(input(f'How important is Reason {i+1}? (from 1-5) '))\n for i in range(reasons)\n ]\n }\n\n\ndef get_top_options(options):\n rankings = {}\n for option in options:\n rankings.setdefault(sum(option['weights']), []).append(option)\n return rankings[max(rankings)]\n\n\nif __name__ == '__main__':\n amount_options = int(input('How many options are there? '))\n options = [\n get_option()\n for _ in range(amount_options)\n ]\n prompt = input('\\nWe will calculate now.\\n')\n\n best_options = get_top_options(options)\n if len(best_options) == 1:\n print('Your best choice is:')\n else:\n print('Your best choices are:')\n for option in best_options:\n print(option['option'])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T18:40:10.387",
"Id": "440431",
"Score": "0",
"body": "Thank you for taking the time to reply so extensively. It was basically a Python lesson!! I'll study this later today."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T20:16:43.163",
"Id": "440444",
"Score": "1",
"body": "@LeoRapini No problem, thank you for the reputation. I have also included a couple more improvements. Happy learning :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T18:11:23.653",
"Id": "226582",
"ParentId": "226574",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "226582",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:35:49.013",
"Id": "226574",
"Score": "12",
"Tags": [
"python",
"python-3.x"
],
"Title": "Script that helps people make better choices"
}
|
226574
|
<p>As a follow-up on <a href="https://codereview.stackexchange.com/questions/116319/associating-degrees-with-notes-of-scales">isosceles' question</a>, I have created a small API to generate the notes of a scale given the pitch class set and key note. I've added the <em>reinventhing-the-wheel</em> tag because I know there exist far superior frameworks that deal with notes, chords, scales, musical notations.</p>
<h1>Description</h1>
<blockquote>
<p>A pitch class set describes a collection of pitch classes in steps
relative to the reference note, which has pitch set class 0 and
corresponds to the specified key note. For instance, the major scale
is identified by pitch class set <code>[0, 2, 4, 5, 7, 9, 11]</code>.</p>
</blockquote>
<h1>Usage</h1>
<p>The main purpose of the API is to generate scale notes as follows:</p>
<pre><code> console.log(getScale('C', [0, 2, 4, 5, 7, 9, 11]).map(i => i.NameClass));
</code></pre>
<p>printing the following to the console:</p>
<pre><code>["C" ,"D" ,"E" ,"F" ,"G" ,"A" ,"B"]
</code></pre>
<p>Notes can be manipulated:</p>
<pre><code> let scale = {};
scale = getScale('D##', [0, 2, 4, 5, 7, 9, 11]).map(i => i.NameClass);
scale = getScale('D##', [0, 2, 4, 5, 7, 9, 11]).map(i => i.enharmonic().NameClass);
scale = getScale('D##', [0, 2, 4, 5, 7, 9, 11]).map(i => i.ascendingEnharmonic().NameClass);
scale = getScale('D##', [0, 2, 4, 5, 7, 9, 11]).map(i => i.descendingEnharmonic().NameClass);
scale = getScale('D##', [0, 2, 4, 5, 7, 9, 11]).map(i => i.transpose(-2).NameClass);
scale = getScale('D##', [0, 2, 4, 5, 7, 9, 11]).map(i => i.transpose(new Interval(1, 0)).NameClass);
scale = getScale('D##', [0, 2, 4, 5, 7, 9, 11]).map(i => i.invert().NameClass);
</code></pre>
<h1>Questions</h1>
<ul>
<li>Have I written idiomatic javascript or what can I improve?</li>
<li>Is my API useful and reusable for more complex operations involving notes and scales?</li>
<li>Are my methods self-describing or are comments required?</li>
</ul>
<h1>Code</h1>
<pre><code>(function() {
'use strict';
function getScale(key, pitchClassSet) {
const keyNote = Note.FromName(key);
return pitchClassSet.reduce(function (scale, scaleStep, i) {
const note = keyNote.clone().transpose(new Interval(i, scaleStep));
scale.push(note);
return scale;
}, []);
}
class Interval {
constructor(di, pi) {
this.di = di;
this.pi = pi;
}
get DegreeInterval() {
return this.di;
}
get PitchInterval() {
return this.pi;
}
}
class Note {
static FromName(name) {
const note = new Note(0, 0);
note.Name = name;
return note;
}
static FromDiatonicPitchClass(degree) {
const note = new Note(degree, 0);
note.PitchClass = Note.DiatonicPitchClassSet[note.DegreeClass];
return note;
}
static get DiatonicPitchClassSet() {
return (new function() {
const pcs = [0,2,4,5,7,9,11];
return function () {
return pcs;
}
})();
}
static get ScientificPitchClassSet() {
return (new function() {
const pcs = ['C','D','E','F','G','A','B'];
return function () {
return pcs;
}
})();
}
constructor(degree, pitch) {
this.d = Coil.FromDegree(degree);
this.p = Coil.FromPitch(pitch);
}
get DegreeClass() {
return this.d.Class;
}
set DegreeClass(n) {
this.d.Class = n;
}
get PitchClass() {
return this.p.Class;
}
set PitchClass(n) {
this.p.Class = n;
}
get Pitch() {
return this.p.Value;
}
set Pitch(n) {
this.p.Value = n;
this.d.Group = this.p.Group;
}
get Octave() {
return this.p.Group;
}
set Octave(n) {
this.p.Group = n;
this.d.Group = n;
}
get Accidentals() {
const diatonic = Note.FromDiatonicPitchClass(this.DegreeClass);
const coil = Coil.FromPitch(this.PitchClass - diatonic.PitchClass);
return coil.Delta;
}
set Accidentals(n) {
const diatonic = Note.FromDiatonicPitchClass(this.DegreeClass);
const coil = Coil.FromPitch(diatonic.PitchClass + n);
this.PitchClass = coil.Class;
}
get Name() {
const octaveName = 5 + this.Octave;
return this.NameClass + octaveName;
}
get NameClass() {
const degreeName = Note.ScientificPitchClassSet[this.DegreeClass];
const accidentals = this.Accidentals;
const accidentalsToken = accidentals === 0 ? ''
: (accidentals < 0 ? 'b' : '#' ).repeat(Math.abs(this.Accidentals));
return degreeName + accidentalsToken;
}
set Name(name) {
const regexp = /(?<degree>[a-gA-G])(?<accidentals>[b#]*)(?<octave>[-]?\d*)/
const result = regexp.exec(name);
const degreeToken = result.groups.degree.toUpperCase();
const accidentalsToken = result.groups.accidentals;
const octaveToken = result.groups.octave;
const degree = Note.ScientificPitchClassSet.indexOf(degreeToken);
const octave = octaveToken.length > 0 ? parseInt(octaveToken) : 5;
const accidentals = accidentalsToken.split('')
.map(c => c == 'b' ? -1 : c == '#' ? 1 : 0)
.reduce((a, b) => a + b, 0);
this.DegreeClass = degree;
this.Octave = octave - 5;
this.Accidentals = accidentals;
}
copy(other) {
this.d = other.d.clone();
this.p = other.p.clone();
return this;
}
clone() {
return new Note(0, 0).copy(this);
}
equals(other) {
if (typeof other === "undefined") { return false; }
return other.d.Equals(this.d)
&& other.p.Equals(this.p);
}
isEnharmonicEquivalent(other) {
return other.Pitch === this.Pitch;
}
isInversionalEquivalent(other) {
return other.p.clone().invert().Class === this.p.Class;
}
isOctaveEquivalent(other) {
return other.DegreeClass === this.DegreeClass
&& other.PitchClass === this.PitchClass;
}
normalize() {
this.Octave = 0;
return this;
}
enharmonic(preference, force) {
if (typeof force === "undefined") {
force = false;
}
if (typeof preference === "undefined") {
preference = 0;
}
let degree = Note.DiatonicPitchClassSet.indexOf(this.PitchClass);
if (degree === -1) {
degree = Note.DiatonicPitchClassSet.indexOf(this.PitchClass - 1);
const degreeAlt = Coil.FromDegree(degree + 1).Class;
if (force || (this.DegreeClass !== degree && this.DegreeClass !== degreeAlt)) {
this.DegreeClass = (preference < 0) ? degreeAlt : degree;
}
}
else {
this.DegreeClass = degree;
}
return this;
}
ascendingEnharmonic() {
return this.enharmonic(1, true);
}
descendingEnharmonic() {
return this.enharmonic(-1, true);
}
transpose(interval) {
let di = 0;
let pi = 0;
if (interval instanceof Note) {
di = interval.d.Value;
pi = interval.p.Value;
}
else if (interval instanceof Interval) {
di = interval.DegreeInterval;
pi = interval.PitchInterval;
}
else {
pi = interval;
}
this.d.translate(di);
this.p.translate(pi);
return this;
}
invert() {
this.d.invert();
this.p.invert();
return this;
}
reflect(pivot, pivot2) {
if (typeof pivot2 === "undefined") {
pivot2 = pivot;
}
this.d.reflect(pivot.d.Value, pivot2.d.Value);
this.p.reflect(pivot.p.Value, pivot2.p.Value);
return this;
}
negate() {
this.d.negate();
this.p.negate();
return this;
}
setDegreeClass(n) {
this.DegreeClass = n;
return this;
}
setPitchClass(n) {
this.PitchClass = n;
return this;
}
setPitch(n) {
this.Pitch = n;
return this;
}
setOctave(n) {
this.Octave = n;
return this;
}
setAccidentals(n) {
this.Accidentals = n;
return this;
}
setName(n) {
this.Name = n;
return this;
}
}
class Coil {
static FromDegree(n) {
return new Coil(n, 7);
}
static FromPitch(n) {
return new Coil(n, 12);
}
constructor(value, size) {
this.Value = value;
this.Size = size;
}
get Value() {
return this.value;
}
set Value(n) {
this.value = n;
}
get Size() {
return this.size;
}
set Size(n) {
this.size = Math.max(1, Math.abs(n));
}
get Class() {
return this.modulo(this.Value);
}
set Class(n) {
this.Value = this.Group * this.Size + this.modulo(n);
}
get Group() {
return Math.floor((this.Value) / this.Size);
}
set Group(n) {
this.Value = n * this.Size + this.Class;
}
get Delta() {
const d1 = this.Class;
const d2 = this.clone().invert().Class;
if (d1 > d2) {
return d2 === 0 ? d2 : -d2;
}
return d1;
}
get Distance() {
return Math.abs(this.Delta);
}
copy(other) {
this.Value = other.Value;
this.Size = other.Size;
return this;
}
clone() {
return new Coil(0, 0).copy(this);
}
equals(other) {
if (typeof other === "undefined") { return false; }
return other.Value === this.Value
&& other.Size == this.Size;
}
normalize() {
this.Value = this.Class;
return this;
}
normalizeUnordered() {
this.Value = this.Distance;
return this;
}
translate(n) {
let d = 0;
if (n instanceof Coil) {
d = n.Value;
} else {
d = n;
}
this.Value += d;
return this;
}
invert() {
this.Class = this.Size - this.Class;
return this;
}
reflect(pivot, pivot2) {
if (typeof pivot2 === "undefined") {
pivot2 = pivot;
}
this.Value = pivot + pivot2 - this.Value;
return this;
}
negate() {
this.Value *= -1;
return this;
}
add(other) {
return this.translate(other.Value);
}
addScalar(n) {
return this.translate(n);
}
subtract(other) {
return this.translate(-other.Value);
}
subtractScalar(n) {
return this.translate(-n);
}
modulo(n) {
return ((n % this.Size) + this.Size) % this.Size;
}
}
})();
</code></pre>
|
[] |
[
{
"body": "<p>Those are some very thorough class definitions, with many getters and setters. For context: I have some music experience (e.g. 22 years playing clarinet and saxophone, 18 years playing acoustic guitar) but wouldn't consider myself an expert in theory. I've gotten used to transposing from C to Eflat and Bflat in my head. I haven't really learned about coils in the context of pitches.</p>\n\n<p>Good stuff:</p>\n\n<ul>\n<li>Separation of code into classes with many getters and setters</li>\n<li>using <code>const</code> for anything that doesn't get re-assigned</li>\n<li>many methods allow chaining by returning <code>this</code></li>\n</ul>\n\n<p>I read over <a href=\"https://codereview.stackexchange.com/a/116330/120114\">the answer to the linked question by Flambino</a> and it looks like you have improved indentation, added spacing and made many other improvements. However, I don't see a <code>return</code> at the end of the IIFE, so nothing is really exposed and thus any code to utilize your code would need to be added inside the IIFE. Perhaps that is fine for you.</p>\n\n<p>Have you considered using a linter? It would help clean up a lot of things. I tried running your code through the linter on jslint.com - it advised things like using double quotes on string literals and <code>\"use strict\"</code>. Apparently it had an issue with the regex with named groups...</p>\n\n<p>I would expect a linter (maybe I am thinking of eslint) would mention that some variables are only used once - e.g. in <code>Note::Name()</code> (the setter) many variables are only used once after assignment - e.g. <code>degree</code>, <code>octave</code>, etc. Also in <code>Coil::translate()</code> there is little point in declaring <code>d</code>. The whole method could be simplified to add either <code>n.Value</code> or <code>n</code> to <code>this.Value</code> without assigning either value to <code>d</code>. </p>\n\n<p>To answer your question</p>\n\n<blockquote>\n <p>Are my methods self-describing or are comments required?</p>\n</blockquote>\n\n<p>I would say they are mostly self-describing but it would be wise to include documentation - at least for the parameters. For instance, the interval constructor takes two arguments: <code>di, pi</code>. I can tell by the other method names that one is for the Degree interval and the other is for the Pitch interval but if I wasn't looking at that it would be difficult to know. </p>\n\n<hr>\n\n<p>In <code>getScale()</code> there is a call to <code>pitchClasSet.reduce()</code> that always pushes a <code>Note</code> clone into the array and returns the array. Use <code>Array.map()</code> instead of <code>Array.reduce()</code> when simply pushing elements into an array and returning the array.</p>\n\n<blockquote>\n<pre><code> return pitchClassSet.reduce(function (scale, scaleStep, i) {\n const note = keyNote.clone().transpose(new Interval(i, scaleStep));\n scale.push(note);\n return scale;\n }, []);\n</code></pre>\n</blockquote>\n\n<p>can be simplified to:</p>\n\n<pre><code>return pitchClassSet.map((scaleStep, i) => keyNote.clone().transpose(new Interval(i, scaleStep)))\n</code></pre>\n\n<hr>\n\n<p>The ES-6 standard adds <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameter</a> values - so places like: </p>\n\n<blockquote>\n<pre><code>enharmonic(preference, force) {\n if (typeof force === \"undefined\") {\n force = false;\n }\n if (typeof preference === \"undefined\") {\n preference = 0;\n }\n</code></pre>\n</blockquote>\n\n<p>Can be simplified to:</p>\n\n<pre><code>enharmonic(preference = 0, force = false) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T05:58:33.440",
"Id": "442050",
"Score": "0",
"body": "These are some good code cleanup suggestions. My ultimate goal is to make software that could recognize chords. I need a solid base with coils and notes to start making chords, scales and what not :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T05:59:51.980",
"Id": "442051",
"Score": "0",
"body": "About exposing the API, I'm still contemplating what would be the best pattern... using a master object or just exposing each of the classes ;."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T23:24:30.817",
"Id": "227198",
"ParentId": "226577",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "227198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T16:59:52.750",
"Id": "226577",
"Score": "6",
"Tags": [
"javascript",
"object-oriented",
"reinventing-the-wheel",
"api",
"music"
],
"Title": "Generate music notes by specified key and scale"
}
|
226577
|
<p>Is this the correct way to block requests in Express?</p>
<p><strong>app.js</strong></p>
<pre><code>app.use("/", indexRouter);
app.use(function(req, res, next) {
next(createError(404));
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
console.log(err);
res.status(err.status || 500);
res.json({ error: err.message });
});
</code></pre>
<p><strong>controller</strong></p>
<pre><code>exports.fetch_seat = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ error: true, message: errors.array() });
}
Seat.getSeatByNumber(req.params.seatNumber, (err, seat) => {
if (err) res.json(err);
else res.json(seat);
});
};
</code></pre>
<p><strong>model</strong></p>
<pre><code>Seat.findSeat = function(key, value) {
return new Promise((resolve, reject) => {
const seat = file.find(r => r[key] === value);
if (!seat) {
reject({
error: true,
message: "Seat not found",
status: 404
});
}
resolve(seat);
});
};
Seat.getSeatByNumber = function(seatNumber, result, next) {
try {
this.findSeat("seatNumber", seatNumber)
.then(seat => {
console.log(seat);
if (seat !== undefined && Object.keys(seat).length > 0) {
return result(null, seat);
} else {
return result({
error: true,
message: "Seat not found",
status: 404
});
}
})
.catch(error => {
console.log(error);
console.log("1st catch");
return result(error, null);
});
} catch (error) {
console.log("outer catch");
console.log(error);
return result(error);
}
};
</code></pre>
<p>I have changed the functions within my model to promises. do i need it to be promises from the controller?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:31:40.280",
"Id": "440640",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>If possible, always whitelist acceptable sources instead of trying to blacklist harmful ones. Also, don't use try-catch for control flow, use it for what it's designed for: error handling. </p>\n\n<p>All that being said, you aren't passing the promise out of the model, because you wait for the response with .then, so no you wouldn't have to make the controller methods promises as well, but why wouldn't you? JS is single-threaded, so always default to asynchronous operations to be non-blocking.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:28:48.053",
"Id": "440633",
"Score": "0",
"body": "I have added an update. not sure what i should do about the try catch. do i not need it? I have not been able to log anything in the `\"outer catch\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:33:49.313",
"Id": "440685",
"Score": "0",
"body": "As the only place where an error can come is the promise, the outer catch it will never reach. You just need the Promise.catch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T04:48:13.320",
"Id": "226663",
"ParentId": "226579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T17:30:35.897",
"Id": "226579",
"Score": "2",
"Tags": [
"javascript",
"error-handling",
"asynchronous",
"express.js"
],
"Title": "Blocking requests within Express"
}
|
226579
|
<p>I am just starting to learn programming. I had already coded some functions and stuff in other languages, and whilst trying to complete this Python challenge
Kevin and Stuart want to play the 'The Minion Game'.</p>
<blockquote>
<p>Game Rules</p>
<p>Both players are given the same string. Both players have to make
substrings using the letters of the string.</p>
<ul>
<li>Stuart has to make words starting with consonants. </li>
<li>Kevin has to make words starting with vowels. </li>
<li>The game ends when both players have made all possible substrings.</li>
</ul>
<p>Scoring A player gets +1 point for each occurrence of the substring in
the string.</p>
<p>For Example: </p>
<ul>
<li>String = BANANA </li>
<li>Kevin's vowel beginning word = ANA here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.</li>
</ul>
</blockquote>
<p>For better understanding, see <a href="https://i.imgur.com/v2uckYQ.png" rel="nofollow noreferrer">this image</a>.</p>
<p>I have not yet implemented the feature that multiple occurrences of substrings yield more points.</p>
<p>I switched over to Java.</p>
<p>I initially wanted to start learning Python, but the company I just started an apprenticeship in almost exclusively uses Java, so I figured I might as well learn that language.</p>
<p>I tried completing it by mostly using trial and error and some google, I did not watch a lot of guides so far, so figuring out what I need to code in what way took me quite a few hours. Now my code basically does what it is supposed to do, but I feel like it is written unnecessarily complicated and could be much shorter.</p>
<p>Since I have not really understood scope and accessibility of methods yet, I was not able to reuse code as I would have liked to and needed to rewrite a lot.</p>
<pre><code>public static void main(String[] args)
{
System.out.println("Please enter a word");
Scanner consoleInput = new Scanner(System.in);
String userInput = consoleInput.nextLine();
System.out.println(GetVowels(userInput).size() + " words starting with wovels: " + GetVowels(userInput));
System.out.println(GetConsonants(userInput).size() + " words starting with consonants: " + GetConsonants(userInput));
}
static ArrayList<String> GetVowels(String userInput){
char[] vowels = "aeiou".toCharArray();
ArrayList<String> possibleWords = new ArrayList<String>();
for(int i = 0; i < vowels.length; i++){
int offset = 0;
while(userInput.indexOf(vowels[i], offset) >= 0){
int wordStartingIndex = userInput.indexOf(vowels[i], offset);
for (int u = wordStartingIndex; u <= userInput.length(); u++)
{
String maybeAWord = userInput.substring(wordStartingIndex, u);
if(maybeAWord.length() > 0 && possibleWords.indexOf(maybeAWord) < 0)
{
possibleWords.add(maybeAWord);
}
}
offset = userInput.indexOf(vowels[i], offset) +1;
}
}
return possibleWords;
}
static ArrayList<String> GetConsonants(String userInput){
char[] vowels = "aeiou".toCharArray();
ArrayList<String> possibleWords = new ArrayList<String>();
ArrayList<Integer> vowelIndexes = new ArrayList<Integer>();
ArrayList<Integer> consonantIndexes = new ArrayList<Integer>();
for(int i = 0; i < vowels.length; i++) {
int offset = 0;
while (userInput.indexOf(vowels[i], offset) >= 0)
{
vowelIndexes.add(userInput.indexOf(vowels[i], offset));
offset = userInput.indexOf(vowels[i], offset) + 1;
}
}
for(int i = 0; i < userInput.length(); i++)
{
if(vowelIndexes.indexOf(i) < 0)
{
int wordStartingIndex = i;
int offset = wordStartingIndex;
while(offset <= userInput.length())
{
String maybeAWord = userInput.substring(wordStartingIndex, offset);
if(maybeAWord.length() > 0 && possibleWords.indexOf(maybeAWord) < 0)
{
possibleWords.add(maybeAWord);
}
offset = offset + 1;
}
}
}
return possibleWords;
}
</code></pre>
<p>I absolutely do not expect anyone to rewrite part of my code in a more compact or efficient way, but I would be very grateful for some tips or hints on what I could write differently, how I might be able to reuse some of the code that I had to write multiple times, or just things that I should avoid in the future.</p>
|
[] |
[
{
"body": "<p><em>Just a couple of words before the code review starts: I only found small issues that are not super crucial but make your code more readable or even a bit faster. My review is kinda long not because your code is bad but because I tried to elaborately explain why I would make some changes.</em></p>\n\n<h2>General Code Style</h2>\n\n<ul>\n<li>Methods, in general, should always use <code>lowerCamelCase</code> for consistency and readability. So in your case, the two methods should be named <code>getVowels</code> and <code>getConsonants</code>.</li>\n<li>You should stay consistent with the placement of the braces. Most coding conventions recommend to have whitespace between keywords and braces and to keep the curly braces in the same line instead of having them in a new line, e.g.: <code>for (int i = 0; i < 10; i++) {</code></li>\n<li>Using access modifiers is considered good practice and using the default access is not neccessary in your code which means you can use the modifier <code>private</code>.</li>\n</ul>\n\n<h3>Programming to Interface</h3>\n\n<ul>\n<li>It's generally a good practice to program to an interface if possible, which in your case means that you should use the interface <code>List</code> wherever you can. The main reason for this design principle is that your code doesn't become dependent on a specific implementation. Here is a <a href=\"https://stackoverflow.com/a/9853116/11959029\">link</a> to a post that explains this better than I ever could.\n\n<ul>\n<li>Concretely this means that both your methods should return <code>List<String></code> instead of <code>ArrayList<String></code> and when initializing a list you should use the following pattern:</li>\n</ul></li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>List<T> identifier = new ArrayList<>();\n</code></pre>\n\n<h2>main</h2>\n\n<ul>\n<li>You should probably modify the input to be in all uppercase letters just in case the user doesn't use all caps. This makes the game more fool-proof.</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>String userInput = consoleInput.nextLine().toUpperCase();\n</code></pre>\n\n<ul>\n<li>Safe the <code>List</code>s <code>getVowels(userInput)</code> and <code>getConsonants(userInput)</code> as they are used multiple times and a call to one of these methods is pretty cost-intensive since they have three nested for-loops (we want those to be called as few times as possible).</li>\n</ul>\n\n<p>The full method would look like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n System.out.println(\"Please enter a word\");\n Scanner consoleInput = new Scanner(System.in);\n String userInput = consoleInput.nextLine().toUpperCase();\n\n List<String> vowels = getVowels(userInput);\n List<String> consonants = getConsonants(userInput);\n System.out.println(vowels.size() + \" words starting with vowels: \" + vowels);\n System.out.println(consonants.size() + \" words starting with consonants: \" + consonants);\n}\n</code></pre>\n\n<h2>getVowels</h2>\n\n<ul>\n<li>You can use a for-each loop instead of the currently existing for-loop with minimal effort. Usually, you should always use for-each over a classic for-loop because it is shorter and a clarifies the intention of the loop.</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>for (char vowel : vowels) {\n</code></pre>\n\n<ul>\n<li>Declare the variable <code>wordStartingIndex</code> outside of the loops and initialize it inside of the condition. This reduces the amount of memory usage a bit:</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>int wordStartingIndex;\n// ...\nwhile ((wordStartingIndex = userInput.indexOf(vowels[i], offset)) >= 0) {\n</code></pre>\n\n<ul>\n<li>The variable <code>wordStartingIndex</code> can also be reused when assigning a new value to the variable <code>offset</code>:</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>offset = wordStartingIndex + 1;\n</code></pre>\n\n<ul>\n<li>Use the method <code>contains</code> instead of <code>indexOf</code> when checking if a word is already in the list of possible words. This effectively does the same but makes it clearer to someone who is reading the code what your goal is with that line (or even you if you take a look at it a few months later):</li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>!possibleWords.contains(maybeAWord)\n</code></pre>\n\n<p>Applying the above recommendations the method would look like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static List<String> getVowels(String userInput) {\n char[] vowels = \"aeiou\".toCharArray();\n List<String> possibleWords = new ArrayList<>();\n\n int wordStartingIndex;\n for (char vowel : vowels) {\n int offset = 0;\n while ((wordStartingIndex = userInput.indexOf(vowel, offset)) >= 0) {\n for (int u = wordStartingIndex; u <= userInput.length(); u++) {\n String maybeAWord = userInput.substring(wordStartingIndex, u);\n if (maybeAWord.length() > 0 && !possibleWords.contains(maybeAWord)) {\n possibleWords.add(maybeAWord);\n }\n }\n offset = wordStartingIndex + 1;\n }\n }\n return possibleWords;\n}\n</code></pre>\n\n<h2>getConsonants</h2>\n\n<ul>\n<li>The list <code>consonantIndexes</code> is never used so it can safely be deleted at the current state of the project. If you plan on using it later leave it in the code but I removed it in the final version.</li>\n<li>Again you should make use of the for-each loop and use a variable to store the value of <code>userInput.indexOf(vowel, offset)</code> since it is used three times in a row without it changing.</li>\n<li>The variable <code>wordStartingIndex</code> is completely redundant and thus can safely be deleted. Instead you should use the iterator-variable <code>i</code>.</li>\n<li>Also again, you should use the <code>contains</code> method instead of checking if the index is less than 0.</li>\n</ul>\n\n<p>Applying the above recommendation the method would look like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static List<String> getConsonants(String userInput) {\n char[] vowels = \"aeiou\".toCharArray();\n List<String> possibleWords = new ArrayList<>();\n List<Integer> vowelIndexes = new ArrayList<>();\n\n int vowelIndex;\n for (char vowel : vowels) {\n int offset = 0;\n while ((vowelIndex = userInput.indexOf(vowel, offset)) >= 0) {\n vowelIndexes.add(vowelIndex);\n offset = vowelIndex + 1;\n }\n }\n\n for (int i = 0; i < userInput.length(); i++) {\n if (vowelIndexes.indexOf(i) < 0) {\n int offset = i;\n while (offset <= userInput.length()) {\n String maybeAWord = userInput.substring(i, offset);\n if (maybeAWord.length() > 0 && !possibleWords.contains(maybeAWord)) {\n possibleWords.add(maybeAWord);\n }\n offset = offset + 1;\n }\n }\n }\n return possibleWords;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T21:08:41.053",
"Id": "226595",
"ParentId": "226584",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T18:28:38.037",
"Id": "226584",
"Score": "3",
"Tags": [
"java",
"beginner",
"programming-challenge",
"console"
],
"Title": "Forming words that start with consonants and vowels"
}
|
226584
|
<p>I wrote a script to calculate document distance. It seems working but I couldn't be sure. (I tried for the small strings and it seems working) Also I am not sure that its fast enough for large texts.</p>
<p><a href="https://www.andrew.cmu.edu/course/15-121/labs/HW-4%20Document%20Distance/lab.html" rel="nofollow noreferrer">Here is the Document Distance formula</a>:</p>
<p><a href="https://i.stack.imgur.com/i7blm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i7blm.png" alt="document distance forumla"></a></p>
<p>The frequency is the number of occurrences for each object. Such as for
"D1: be or not to be" the frequency will be freq<span class="math-container">$$(D_1) = {be=2, not=1, or=1, to=2}$$</span> and <span class="math-container">$$||D_1|| = \sqrt{2^2 + 1^2 + 1^2 + 2^2}$$</span></p>
<pre><code>from math import sqrt
from string import ascii_lowercase
alphanumerics = ascii_lowercase + "0123456789"
file1 = open("document1.txt", "r")
file2 = open("document2.txt", "r")
print(file1)
document1 = ""
for line in file1:
document1 += line + ""
document2 = ""
for line in file2:
document2 += line + ""
if document1 == "":
print("--- The document1.txt file is empty! ---")
raise ValueError
elif document2 == "":
print("--- The document2.txt file is empty!! ---")
raise ValueError
print(document1, document2)
def word_processor(document):
'''returns an array that only contains the words in the text'''
doc_word = []
word = ""
count_space = 0
for char in document.lower():
if char in alphanumerics:
word += char
count_space = 0
elif char == " " and count_space == 0:
doc_word.append(word)
word = ""
count_space += 1
doc_word.append(word)
return doc_word
doc1_words = word_processor(document1)
doc2_words = word_processor(document2)
dot_product = 0
doc1_word_freq = {i: doc1_words.count(i)
for i in doc1_words} # the doc1 vector
doc2_word_freq = {i: doc2_words.count(i)
for i in doc2_words} # the doc2 vector
for key, value in doc1_word_freq.items():
if key in doc2_word_freq.keys():
dot_product += doc2_word_freq[key] * value # the dot product of the two doc vectors
doc1_mag = sqrt(sum([value**2 for value in doc1_word_freq.values()])) # the magnitude of the each document
doc2_mag = sqrt(sum([value**2 for value in doc2_word_freq.values()]))
similarity = dot_product / (doc1_mag * doc2_mag) * 100
print("The similarity between 2 document is", similarity, "percent")
</code></pre>
<p>Any ideas ? </p>
<p>I did not use the <code>acos</code> function since I don't think I need it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T23:05:38.247",
"Id": "440455",
"Score": "1",
"body": "Take a look at https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-notes/ -> Unit 1 - Introduction - 2 - Lecture code (ZIP). He has a variety of 8 different py files solving your same task but the first version takes 228 seconds and the most efficient one 0.2 seconds to process two 1 MB-ish files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:59:26.310",
"Id": "440539",
"Score": "2",
"body": "You should explain in more detail what \"document distance\" means in your post. It's an important part of the review so we can know what the code is supposed to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:04:30.640",
"Id": "440563",
"Score": "1",
"body": "@IEatBagels I edited my post"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:41:39.330",
"Id": "440594",
"Score": "0",
"body": "You've tried it with smaller strings, but what's keeping you from testing with larger strings as well?"
}
] |
[
{
"body": "<p>Most of your code can be greatly reduced.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/10043636/any-reason-not-to-use-to-concatenate-two-strings\">Doing string addition is often a bad idea in Python</a>, especially if you are doing it in a loop. Also note that <code>a + \"\" == a</code> for any string <code>a</code>. I would replace your mix of global code and the <code>word_processor</code> function with this short function:</p>\n\n<pre><code>import string\n\nWHITELIST = set(string.ascii_letters + string.digits + string.whitespace)\n\ndef get_words(file_name):\n with open(file_name) as f:\n for line in f:\n line = \"\".join(c for c in line.casefold() if c in WHITELIST)\n yield from line.split()\n</code></pre>\n\n<p>This filters each line of the file to only contain ASCII letters and whitespace and splits it by whitespace afterwards (the default behavior of <a href=\"https://docs.python.org/3.7/library/stdtypes.html#str.split\" rel=\"nofollow noreferrer\"><code>str.split</code></a>). The <a href=\"https://docs.python.org/3/whatsnew/3.3.html#pep-380-syntax-for-delegating-to-a-subgenerator\" rel=\"nofollow noreferrer\"><code>yield from</code></a> effectively flattens the output into a stream of words (the whole function is a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator</a>, so you can consume the output one at a time without keeping the whole list in memory). It also uses the <a href=\"https://effbot.org/zone/python-with-statement.htm\" rel=\"nofollow noreferrer\"><code>with</code></a> keyword to ensure your files are closed, even in the event of an exception interrupting the program. I used <code>str.casefold</code> instead of <code>str.lower</code>, as recommended by <a href=\"https://codereview.stackexchange.com/users/100620/ajneufeld\">@AJNeufeld</a> in the comments.</p>\n\n<p>You should put the actual code into a function as well. I would call it <code>similarity</code>, since it does not actually measure distance, but similarity (from 0 to 100). For this you can use <a href=\"https://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> instead of using <code>list.count</code> repeatedly (each of which is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>).</p>\n\n<pre><code>from collections import Counter\nfrom math import sqrt\n\ndef similarity(words1, words2):\n words1, words2 = Counter(words1), Counter(words2)\n dot = sum(words1[k] * words2[k] for k in words1.keys() & words2.keys())\n norm1 = sqrt(sum(v**2 for v in words1.values()))\n norm2 = sqrt(sum(v**2 for v in words2.values()))\n return dot / (norm1 * norm2)\n</code></pre>\n\n<p>Here I used the fact that <code>Counter</code> can take any iterable (like the output of <code>get_words</code>) and counts how often each item occurs (it returns a kind of dictionary). Also, dictionary keys behave like sets, so we can do a set intersection so we don't have to check for every key if it is also in the second words counter. I would also leave scaling the similarity to the caller.</p>\n\n<p>Use it within a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from the module. You might want to add a simple CLI interface with <code>sys.argv</code> (or do it properly and use <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> if you want more functionality). Throw in a <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> to make formatting the output to the user easier (and make it a percent with not too many digits shown).</p>\n\n<pre><code>import sys\n\nif __name__ == \"__main__\":\n file1, file2 = sys.argv[1:3]\n sim = similarity(get_words(file1), get_words(file2))\n print(f\"Similarity of {file1} and {file2}: {sim:.2%}\")\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>python3 similarity.py file.txt file_old.txt\n# Similarity of file.txt and file_old.txt: 92.19%\n</code></pre>\n\n<p>For these two small files (21KiB), your code takes 0.3s, whereas my code only takes 0.05s on my machine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:13:35.620",
"Id": "440565",
"Score": "0",
"body": "Your first code Its kind of hard for me to understand (the syntax), is it works even when theres two (or more) spaces or commas between the spaces such as some grammer errors etc ? For instance `I need to, buy a headphone`. I think that split will ot work in this case ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:19:34.377",
"Id": "440566",
"Score": "1",
"body": "I liked the Counter and casefold method thanks a lot for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:21:32.603",
"Id": "440567",
"Score": "0",
"body": "If we assume that each word is seperated by space its more logical to use split. But if its not how can we use split ? Thats why I have `count_space = 0`. But I am sure that there can be found some more clever way to do that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:21:50.757",
"Id": "440568",
"Score": "2",
"body": "@Reign Well, if in doubt, try it ;) With `line = \"I need to, buy a headphone\\n\"`, `\"\".join(filter(WHITELIST.__contains__, line.casefold())).split()` returns `['i', 'need', 'to', 'buy', 'a', 'headphone']`, which is the correct interpretation, as far as I can tell. One error that will mess it up a bit is missing spaces, i.e. `foo,bar` will be interpreted as the word `foobar`, because there is no whitespace left after the filtering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:22:33.137",
"Id": "440569",
"Score": "1",
"body": "@Reign It splits on any amount of whitespace, not only spaces. So extra spaces are fine, missing spaces not so much. But I guess your code also cannot deal with missing spaces. I would say no code can, because there are ambiguous words, which are made up of multiple other words."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:42:37.570",
"Id": "440572",
"Score": "0",
"body": "I see I just used the str.split(\" \") for a string and did not work, but indeed your might does which is great Thanks then"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T16:25:23.140",
"Id": "226636",
"ParentId": "226586",
"Score": "6"
}
},
{
"body": "<p>This bit of your code that is trying to vectorize text into count vector</p>\n\n<pre><code>doc2_words = word_processor(document2)\n\ndoc1_word_freq = {i: doc1_words.count(i)\n for i in doc1_words} # the doc1 vector\ndoc2_word_freq = {i: doc2_words.count(i)\n for i in doc2_words} # the doc2 vector\n</code></pre>\n\n<p>can be replaced by <a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer\" rel=\"nofollow noreferrer\">scikit-learn's CountVectorizer</a></p>\n\n<pre><code>vectorizer=sklearn.feature_extraction.text.CountVectorizer()\nvectorizer.fit([document1, document2])\ndoc1_word_freq = vectorizer.transform([document1])\ndoc2_word_freq = vectorizer.transform([document2])\n</code></pre>\n\n<p>This can be loaded directly from files with <code>vectorizer=sklearn.feature_extraction.text.CountVectorizer(content='file')</code></p>\n\n<p>For even large text I would use Keras <a href=\"https://keras.io/preprocessing/text/\" rel=\"nofollow noreferrer\">keras.preprocessing.text.Tokenizer</a></p>\n\n<p>and then this bit of the code </p>\n\n<pre><code>for key, value in doc1_word_freq.items():\n if key in doc2_word_freq.keys():\n dot_product += doc2_word_freq[key] * value # the dot product of the two doc vectors\n\ndoc1_mag = sqrt(sum([value**2 for value in doc1_word_freq.values()])) # the magnitude of the each document\ndoc2_mag = sqrt(sum([value**2 for value in doc2_word_freq.values()]))\n\nsimilarity = dot_product / (doc1_mag * doc2_mag) * 100 \nprint(\"The similarity between 2 document is\", similarity, \"percent\")\n</code></pre>\n\n<p>is recommended to use <a href=\"https://stackoverflow.com/questions/18424228/cosine-similarity-between-2-number-lists\">Numpy</a> or even <a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.cosine_similarity.html\" rel=\"nofollow noreferrer\">Scikit-learn</a> for matrix operation</p>\n\n<pre><code>similarity = sklearn.metrics.pairwise.cosine_similarity(doc1_word_freq, doc2_word_freq)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:10:47.300",
"Id": "226907",
"ParentId": "226586",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226636",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T18:49:42.797",
"Id": "226586",
"Score": "7",
"Tags": [
"python",
"algorithm",
"edit-distance"
],
"Title": "Document distance in Python"
}
|
226586
|
<p>I have written the following php class method to traverse an array and build a query from the array.</p>
<p>The data of this array looks like:</p>
<pre><code>0 => [
'key1' => 'value',
'key1' => 'value',
'key3 => 'value'
],
1 => [
'key1' => 'value',
'key1' => 'value',
'key3 => 'value'
]
</code></pre>
<p>The project is not my own, but the module im working on is so I am making use of the existing database class which is based on pdo within the project.</p>
<p>As you can see I am looping through the array building a query and inserting the contents of each into one row. Is there a more efficient way to build the queries?</p>
<pre><code>/**
*
* @param string $table
* @param string $keyColumn
* @param int $keyID
* @param array $data
* @return int
*/
private function insertKeyed($table, $keyColumn, $keyID, $data) {
// each array element
foreach ($data as $topkey => $topval) {
// start of query string
$buildQuery[] = "INSERT INTO `{$table}` SET `{$keyColumn}` = '{$this->db->escape($keyID)}'";
foreach ($topval as $key => $value) {
if (!is_array($value)) {
// add each column as array element
$buildQuery[] = "`{$key}` = '{$this->db->escape($value)}'";
}
}
// merge into string
$queryString = implode(',', $buildQuery);
$result = $this->db->query($queryString);
// ensure that $buildQuery is reset for multiple rows.
unset($buildQuery);
if (!$result->num_rows) {
$this->log->message('INSERT FAILED.');
break;
} else {
$this->log->message('INSERT SUCCEEDED.');
}
}
return $this->db->getLastId();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T09:44:11.510",
"Id": "440482",
"Score": "1",
"body": "Is this class *really* based on PDO? To implement an escape() function based on PDO, one has to savagely torture and molest this honest driver."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T10:27:48.160",
"Id": "440485",
"Score": "0",
"body": "what's the purpose of having distinct $keyColumn, $keyID in the function prameters?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:46:55.817",
"Id": "440575",
"Score": "0",
"body": "To your first comment: Not this class no, but the property $db yes, its a class of its own that instantiates a PDO instance. The escape function is nothing more than a string replace. I'm not sure if its a stop-gap that never got looked at again or if its just because I am bout 2 years behind the main project with my website version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T23:17:34.337",
"Id": "440579",
"Score": "0",
"body": "For your second comment. This runs on two tables out of a four table structure, meaning the id is no available until right before execution of this function. The data being inserted has an external source and before this function handles the array two tables receive data. Table 2 references Table 1. Both tables 3 and 4 reference table 2. So basically, at this point is does not seem logical to update the array to insert the column name and the last insert id. Of course that would mean less parameters and might be something I should consider. Sorry for the comment deletions, edits too long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:03:42.403",
"Id": "440589",
"Score": "0",
"body": "Sorry i don't really get it, so I cannot review. I only want to ask: do you have any problem with efficiency at the moment? What made you to ask for a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:30:39.630",
"Id": "440771",
"Score": "0",
"body": "Because it was nested loops initially which was taking a long time to run and the dataset is very large. I want to make it as efficient as possible that is all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:36:09.103",
"Id": "440772",
"Score": "0",
"body": "if it helps here is a sample of the initial data and the database structure (basicaly) the columns have changed but the overall structure is pretty much the same (but the two countries tables no longer reference the services table): https://dba.stackexchange.com/questions/245375/assistance-with-appropriate-schema-for-this-dataset-involving-the-services-of-pa"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:42:38.667",
"Id": "440777",
"Score": "0",
"body": "wrap your inserts into a transaction"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:45:19.363",
"Id": "440779",
"Score": "0",
"body": "So you are suggesting to build up a transaction list and perform just one insert? Well four, one for each table?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:52:06.250",
"Id": "440781",
"Score": "0",
"body": "One question I can switch between database classes without any alteration to queries, would you suggest I use mysqli instead? (there are pdo, mysql_, mysqli, mssql and postgre) last two I wouldnt not be able to use, mysql Im not sure if its still available in php7 I would have to check but to be fair I know better than to use it.\n\nIs there much of a difference between mysqli and pdo in efficiency terms?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T04:36:45.727",
"Id": "440827",
"Score": "0",
"body": "No there isn't. The way you are using PDO, however, is no different from obsoleted mysql_ either. You must be using prepared statements"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T04:37:54.437",
"Id": "440828",
"Score": "0",
"body": "I am suggesting to wrap all your inserts in all tables in a single transaction"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T05:06:58.493",
"Id": "440829",
"Score": "0",
"body": "From what I can tell they are using pdo's prepare function though I don't know why they have chosen to still use escape. In any case, thank you for help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T05:16:20.747",
"Id": "440830",
"Score": "0",
"body": "because it's a [cargo cult prepare](https://phpdelusions.net/pdo/cargo_cult_prepared_statement)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T05:21:02.940",
"Id": "440831",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/97804/discussion-between-chris-and-your-common-sense)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T19:12:40.140",
"Id": "226588",
"Score": "0",
"Tags": [
"performance",
"php"
],
"Title": "Class method to build SQL query"
}
|
226588
|
<p>Code Review has a <a href="https://codereview.meta.stackexchange.com/questions/9251/possible-solution-for-zombies-unanswered-questions">Zombie Problem</a> and, in comparison to The Walking Dead TV Show, our survival doesn't depend on killing them all day every day.</p>
<p>As a potential solution, I though it would be interesting to setup a friendly zombie killing competition (this wasn't talked about in meta yet), but in order for this to work we need a way to rank our killers.</p>
<p>I've written the following <a href="https://data.stackexchange.com/" rel="nofollow noreferrer">Stack Exchange Data Explorer</a> query, which has the following requirements.</p>
<p>Questions must : </p>
<ul>
<li>Not be closed/deleted/community owned</li>
<li>Be at least one month older than the competition's start date</li>
<li>Not have answers with a score greater than one preceding the competition's start date</li>
</ul>
<p>And in order for the zombie to be killed, the questions targeted by the above requirements must have an answer with a score of 1 or more that follows the beginning of the competition's date.</p>
<p>I then group the answers per user, show their "kill count" and order by this value, in descending order.</p>
<p><strong>The query in question</strong></p>
<pre><code>declare @startDate date;
set @startDate = CONVERT(datetime, '2019-07-21');
select top(25) u.DisplayName, count(*)
from Posts q
inner join Posts a on q.Id = a.ParentId
inner join Users u on a.OwnerUserId = u.Id
where q.PostTypeId = 1
-- Target old questions with new answers
and datediff(month, q.CreationDate, @startDate) > 1
and a.Score > 0
and a.CreationDate > @startDate
and not exists (select Id from Posts where ParentId = q.Id and CreationDate < @startDate and Score > 0)
-- Remove low quality/closed/deleted/community owned questions
and q.Score >= 0
and q.ClosedDate is null and q.CommunityOwnedDate is null and q.DeletionDate is null
group by u.Id, u.DisplayName
order by count(*) desc
</code></pre>
<p>I don't have a database schema in hand, but there are two table concerned : </p>
<p>Posts : Where we have questions and answers. The answers have a <code>ParentId</code> that is a question. A post has an owner (OwnerUserId) with an associated <code>User</code>. I think the rest of the columns names are pretty self explanatory, but I can add details if necessary.</p>
<p>I've tested the query and, to the best of my knowledge, it works. I'm not very used to SEDE so there might be things I missed, which I'd like to learn.</p>
<p>I'd also like to know if there are performance pitfalls in my query I should be aware of or best practices that I'm missing.</p>
<p>The <a href="https://data.stackexchange.com/codereview/query/1094604/zombie-killers-ranking" rel="nofollow noreferrer">query</a> itself.</p>
|
[] |
[
{
"body": "<p>As a heads up - we have very different formatting styles for our code. Feel free to ignore that difference and don't consider it a comment on your style (unless you prefer mine, in which case please do).</p>\n<hr />\n<h3>Aliases</h3>\n<p>I really dislike the practice of using short aliases for tables. I've never seen a point, and it always makes it harder for me to understand. You can get easy aliases (e.g. <code>q</code> -> <code>questions</code> or <code>a</code> -> <code>answers</code>) for very few characters.</p>\n<p>I also really like when each column of my output has an actual name, so its easier to understand. In this case, I would alias <code>COUNT(*)</code> as <code>[Zombie Kill Count]</code> or something.</p>\n<p>Also, you can use the alias in your <code>ORDER BY</code>, which I find conceptually easier to understand.</p>\n<hr />\n<h3>Performance</h3>\n<p>One thing that jumps out at me is that you're using a function in your <code>WHERE</code> clause. This can cause the cardinality estimator to get <em>really</em> confused (I don't know if SEDE still uses the legacy cardinality estimator; if they do, then this problem is magnified) and you can end up with some less-than-ideal query plans. One way to avoid this is to not include your column in the function. For example, instead of this:</p>\n<pre><code>SELECT *\n FROM Posts\n WHERE DATEDIFF( MONTH, CreationDate, @startDate ) > 1;\n</code></pre>\n<p>You could do this</p>\n<pre><code>SELECT *\n FROM Posts\n WHERE CreationDate < DATEADD( MONTH, -1, @startDate );\n</code></pre>\n<p>This lets the cardinality estimator use the available statistics on the <code>CreationDate</code> column without confusing it with the function.</p>\n<p>If you're grouping by a value that doesn't actually add a new level of granularity (<code>Users.DisplayName</code> doesn't actually change the grouping) it can be more efficient to use an aggregate there; you get the same result, but a cheaper sort.</p>\n<pre><code>SELECT MAX( u.DisplayName ) -- I'm cheaper than grouping on me\n</code></pre>\n<p>Playing around with the <code>APPLY</code> operator can be fun as well; I've often seen it perform better than a <code>NOT EXISTS</code>, like so (with a <code>GoodAnswers.Id IS NULL</code> in the <code>WHERE</code> clause to get an exclusive outer apply). Note - this one wasn't tested, so YMMV. <code>APPLY</code> can be pretty situational, but I always have fun writing them.</p>\n<pre><code>OUTER APPLY ( SELECT TOP( 1 ) Id\n FROM Posts OldAnswers\n WHERE OldAnswers.ParentId = Questions.Id\n AND OldAnswers.CreationDate < @startDate\n AND OldAnswers.Score > 0 \n ORDER BY ( SELECT NULL ) ) GoodAnswers\n</code></pre>\n<hr />\n<p>Overall, I came up with something like this.</p>\n<pre><code>DECLARE @startDate date;\nSET @startDate = CONVERT( datetime, '2019-07-21' );\n\nSELECT TOP ( 25 )\n MAX( Answerers.DisplayName ) [Answerer Name],\n COUNT( * ) [Zombie Kill Count]\n FROM Posts Questions\n INNER JOIN Posts Answers\n ON Questions.Id = Answers.ParentId\n INNER JOIN Users Answerers\n ON Answers.OwnerUserId = Answerers.Id\n OUTER APPLY ( SELECT TOP ( 1 )\n Id\n FROM Posts OldAnswers\n WHERE OldAnswers.ParentId = Questions.Id\n AND OldAnswers.CreationDate < @startDate\n AND OldAnswers.Score > 0\n ORDER BY ( SELECT NULL )) GoodAnswers\n WHERE Questions.PostTypeId = 1\n -- Target old questions with new answers\n AND Questions.CreationDate < DATEADD( MONTH, -1, @startDate )\n AND Answers.Score > 0\n AND Answers.CreationDate > @startDate\n -- That didn't already have a good answer\n AND GoodAnswers.Id IS NULL\n -- Remove low quality/closed/deleted/community owned questions\n AND Questions.Score >= 0\n AND Questions.ClosedDate IS NULL\n AND Questions.CommunityOwnedDate IS NULL\n AND Questions.DeletionDate IS NULL\n GROUP BY Answerers.Id\n ORDER BY [Zombie Kill Count] DESC;\n</code></pre>\n<hr />\n<p>Some extra notes:</p>\n<ul>\n<li>Unfortunately, I had a hard time finding information on the available\nindices on SEDE. The best resource I found was <a href=\"https://meta.stackexchange.com/a/268343/247602\">this</a> post. It\ndoesn't list any indices on the <code>Posts</code> table, although we do have\none on <code>Users.Id</code>. As such there aren't any great suggestions I have\nfor joins here; you're probably doing about as well as you can.</li>\n<li>You have a pretty lengthy <code>WHERE</code> clause going on; that'll likely dilute the cardinality even further, but I don't see a reasonable\nalternative.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T02:51:16.333",
"Id": "440467",
"Score": "1",
"body": "I know this is \"against rules\" but I just want to say this is a terrific answer. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T08:38:46.993",
"Id": "459846",
"Score": "0",
"body": "The `Posts` table isn't an actual table but a view over `PostsWithDeleted`. Its indexes will be used when you select from `Posts`. The view gets created [here](https://gist.github.com/NickCraver/f009ab6e0d6b85ae54f6#file-sp_refresh_database-sql-L120)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T21:38:41.303",
"Id": "226598",
"ParentId": "226593",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "226598",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T20:43:12.253",
"Id": "226593",
"Score": "6",
"Tags": [
"sql",
"sql-server",
"stackexchange"
],
"Title": "Zombie killers ranking"
}
|
226593
|
<p>I'm new at Rust and I'm trying to implement a cards' deck on Rust, I'm trying to use most idiomatic code I can, but since I'm new at this language, I'd like to hear advice from more experienced programmers. There's my code.
(P.D: Thanks in advance! :>)</p>
<pre class="lang-rust prettyprint-override"><code>use std::fmt;
use rand::seq::SliceRandom;
use rand::thread_rng;
#[derive(PartialEq)]
pub struct Card<'a> {
name: &'a str,
value: i8,
suit: char,
}
impl<'a> fmt::Debug for Card<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} of {}", self.name, self.suit)
}
}
pub struct Deck<'a> {
pub cards: Vec<Card<'a>>,
}
impl<'a> Deck<'a> {
const SUITS: [char; 4] = ['♥', '♦', '♣', '♠'];
const CARDS: [(&'a str, i8); 13] = [
("ACE", 11),
("TWO", 2),
("THREE", 3),
("FOUR", 4),
("FIVE", 5),
("SIX", 6),
("SEVEN", 7),
("EIGHT", 8),
("NINE", 9),
("TEN", 10),
("JACK", 10),
("QUEEN", 10),
("KING", 10),
];
pub fn new() -> Deck<'a> {
let mut deck: Vec<Card> = Vec::new();
for suit in Deck::SUITS.iter() {
for (card_name, card_value) in Deck::CARDS.iter() {
deck.push(Card {
name: card_name,
value: *card_value,
suit: *suit,
});
}
}
let mut rng = thread_rng();
deck.shuffle(&mut rng);
Deck { cards: deck }
}
pub fn deal_card(&mut self) -> Card<'a> {
if self.cards.is_empty() {
self.initialize_deck()
}
self.cards.pop().unwrap()
}
pub fn get_initial_cards(&mut self) -> Vec<Card> {
vec![self.deal_card(), self.deal_card()]
}
/// When the cards vector is empty, shuffle a new deck
fn initialize_deck(&mut self) {
*self = Deck::new();
}
}
</code></pre>
<p><em>EDIT:</em> This module is meaned to be used with a BlackJack game, that is the reason because the cards have those particular values</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T23:20:45.577",
"Id": "440456",
"Score": "0",
"body": "If you're only going to use a constant once, why not just inline it? That makes it clearer that it's only for a single purpose. Declaring it separately implies you're going to reuse it.\n\nAnd rather than storing the name on the card, it would be more memory efficient to implement a function to look up the name based on the value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T07:44:22.287",
"Id": "440477",
"Score": "0",
"body": "The constants are there because I want the user to be able to see the cards and suits that I'm using on the deck. I want them to be what in other languages you'd call static variables. \nAbout storing both name and value, you're totally right, but I think that for readibility, I'm going to delete the value, and create the function that gives the value according to the name. Thx a lot!"
}
] |
[
{
"body": "<p>You’ve made a fairly classic mistake when it comes to modeling cards in software. Cards have different values depending on the game. In some games, an Ace == 1, others 11, sometimes it could be either <em>in the same game</em> (Blackjack for example). Non-face cards aren’t always their value either. In some games, they’re all “5 points”, regardless of the number on the card. </p>\n\n<p>In short, the value of a particular card depends on the game, not the card. How might you redesign to account for that?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T07:09:40.057",
"Id": "440474",
"Score": "0",
"body": "Another example: in the \"Belote\" (a French game), both the strength and the points of a card depend on if the suit is trump or not. Before the players chose the trumps suit, the cards do not have those characteristics fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T07:40:09.880",
"Id": "440476",
"Score": "0",
"body": "I forgot to mention that I'm going to use this module with a BlackJack game I'm developing, that is the reason because the cards have those particular values"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T01:05:07.720",
"Id": "226606",
"ParentId": "226602",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T22:30:01.953",
"Id": "226602",
"Score": "4",
"Tags": [
"beginner",
"rust",
"playing-cards"
],
"Title": "Most idiomatic way of declaring a deck in Rust"
}
|
226602
|
<p>I have a series of Events (roughly 10-20 events that will be dynamically created per month): </p>
<p><strong>Event Model</strong>:</p>
<pre><code>import { Schema, model } from "mongoose";
const eventSchema = new Schema({
callTimes: { type: Array, of: Date, required: true },
eventDate: { type: Date, required: true },
employeeResponses: [
{
_id: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
},
response: { type: String, required: true },
notes: String,
},
],
scheduledEmployees: [
{
_id: {
type: Schema.Types.ObjectId,
ref: "User",
required: true
},
callTime: { type: Date, required: true },
},
],
});
export default model("Event", eventSchema);
</code></pre>
<p><strong>Some sample data</strong>:</p>
<pre><code>[
{
"_id": "5d5daaafcf11d95c0a75a023",
"callTimes": [
"2019-08-21T10:30:41-07:00",
"2019-08-21T11:00:41-07:00",
"2019-08-21T11:30:41-07:00"
],
"eventDate": "2019-08-20T02:30:36.000Z",
"employeeResponses": [],
"scheduledEmployees": []
},
{
"_id": "5d5b5ee857a6d20abf49db19",
"callTimes": [
"2019-08-19T17:15:43-07:00",
"2019-08-19T17:45:43-07:00",
"2019-08-19T18:15:43-07:00",
"2019-08-19T19:00:43-07:00"
],
"eventDate": "2019-08-21T02:30:36.000Z",
"employeeResponses": [
{
"_id": "5d5b5e952871780ef474807b",
"response": "Available to work.",
"notes": "I can work all day."
},
{
"_id": "5d5b5e952871780ef474807c",
"response": "Not available to work.",
"notes": "I have school during that time."
}
],
"scheduledEmployees": []
}
...etc
]
</code></pre>
<p>Employees can view a form that includes the current month's events and add their responses. However, I'm running into a predicament with creating/updating sub documents dynamically. I'm trying to create a <code>bulkWrite</code> function that will either create an <code>employeeResponse</code> sub document if none exists or update the sub document if it's already been created.</p>
<p>I came up with this function, where:</p>
<ul>
<li><code>_id</code> contains the form id </li>
<li><code>response</code> is an object that contains the event's ObjectId, the employee event response (value), and an updateEvent boolean flag</li>
<li><code>notes</code> are employee event notes </li>
<li><code>userId</code> (req.session.user.id) is the current logged in employee stored in an express-session</li>
</ul>
<p><strong>Update Event function</strong>:</p>
<pre><code>const updateFormAp = async (req, res) => {
try {
const { _id, responses, notes } = req.body;
if (!_id || !responses) throw "Missing required update event parameters. You must include an event id and response.";
const formExists = await Form.findOne({ _id });
if (!formExists) throw "Unable to locate that event form.";
// iterate over responses and update the Events accordingly...
await Event.bulkWrite(
responses.map(response => {
try {
const { id: eventId, value, updateEvent } = response;
const { id: userId } = req.session.user;
// if the employee response exists...
const filter = updateEvent
? {
// set the filter to event id + employee id
_id: eventId,
"employeeResponses._id": userId,
}
: {
// else set the filter to event id only
_id: eventId,
};
// if the employee response exists...
const update = updateEvent
? {
// update the sub document in place
$set: {
"employeeResponses.$.response": value,
"employeeResponses.$.notes": notes,
},
}
: {
// else add a new sub document
$push: {
employeeResponses: {
_id: userId,
response: value,
notes,
},
},
};
return {
updateOne: {
filter,
update,
},
};
} catch (error) {
throw error;
}
}),
);
res
.status(201)
.json({ message: "Successfully added your responses to the A/P form!" });
} catch (err) {
res
.status(400)
.json({ error: err.toString() });
}
};
</code></pre>
<p>So, if an event was added <strong>after</strong> some responses were recorded, the employee can go back and add their response to this newly created event while optionally updating their other responses as well. </p>
<p>Is there another or better approach to handling all 3 cases?</p>
<ol>
<li>No Event <code>employeeResponses</code> sub documents exists for the logged in employee, create them</li>
<li>One or many Events don't contain <code>employeeResponses</code> sub documents for the logged in employee, create them</li>
<li>One or many Events already contain <code>employeeResponses</code> sub documents for the logged in employee, update them.</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T23:41:04.543",
"Id": "226605",
"Score": "4",
"Tags": [
"javascript",
"node.js",
"mongodb",
"mongoose"
],
"Title": "MongoDB BulkWrite - create or update a sub document within an array"
}
|
226605
|
<p>I am building a simple calculator with jQuery.</p>
<p>I can append the value to the screen and when the user clicked the operator the first values are clear or empty.</p>
<p>My question is, how can I store first and second values from the input field to use those values to perform the calculation?</p>
<pre><code>$(document).ready(function() {
console.log("ready!");
let firstVal = 0;
let secVal = 0;
let latestNumber = 0;
$(".btn").on("click", function(event) {
let currentVal = $("input").val();
console.log("currentVal is " + currentVal);
let val = $(this).data("val");
console.log("val is " + val);
firstVal = $("input").val(currentVal + val);
switch (val) {
case "+":
latestCalculationMethod = val;
$("input").val("");
return;
case "-":
latestCalculationMethod = val;
$("input").val("");
return;
case "x":
latestCalculationMethod = val;
$("input").val("");
return;
case "/":
latestCalculationMethod = val;
$("input").val("");
return;
default:
latestNumber = 0;
}
if (firstVal === "") {
firstVal = latestNumber;
} else {
secVal = latestNumber;
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T20:45:49.430",
"Id": "440555",
"Score": "2",
"body": "Welcome to Code Review! The question \"_My question is, how can I store first and second values from the input field to use those values to perform the calculation?_\" is off-topic for this site because it asks about a feature not currently implemented. See the [help/on-topic] for more information."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T02:07:12.590",
"Id": "226609",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Simple jQuery calculator"
}
|
226609
|
<p>For implementing <code>Singleton</code> we can use <em>Traditional way</em> like this <a href="https://www.codeproject.com/Tips/219559/Simple-Singleton-Pattern-in-Csharp" rel="noreferrer">Article</a>,
but i think that to write it in another way:</p>
<pre><code> public class Person
{
private static Person personInstance;
static Person()
{
personInstance = new Person();
}
private Person() { }
public static Person GetPersonInstance()
{
return personInstance;
}
}
</code></pre>
<p>As we know a <code>Static Constructor</code> will call automatically before the first instance is created or any static members are referenced and just once only. so if i write singleton like above, is it true (i mean this class is singleton)? or not?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:26:27.870",
"Id": "440617",
"Score": "4",
"body": "https://csharpindepth.com/articles/singleton. Jon Skeet article on singleton. It's some kind of cannonical read before starting any conversation about singleton."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:32:21.240",
"Id": "440704",
"Score": "1",
"body": "I can't deal with the capitalization of `SingleTonSample` in the article OP posted."
}
] |
[
{
"body": "<p>Your implementation does the trick. For what it's worth, I would consider your implementation the current \"traditional way\". It is thread-safe. The static constructor is guaranteed to run only once, so you won't accidentally end up with two instances if two threads try to grab the instance for the first time simultaneously.</p>\n\n<h1>Laziness</h1>\n\n<p>There is one more thing you might want to consider though. Because of the way the static constructor works, it is executed the first time the class is referenced in the code. This means that the instance in your singleton is created, even when you don't try to grab the instance, but another static variable perhaps.</p>\n\n<p>To fix this, you might want to make the creation of the instance lazy, so that it really only fires when you need it. To do this, you can use the <code>Lazy<T></code> class.</p>\n\n<h1>Sealed</h1>\n\n<p>This is mostly a formality, but it's nice when trying to do it formally. The <code>sealed</code> keyword means that that class cannot be inherited from. The private constructor already ensured that, but this makes it more explicit.</p>\n\n<h1>Readonly</h1>\n\n<p>As Jesse mentioned in the comments, it's a good idea to make the instance field (lazy or not) <code>readonly</code>. This prevents you from accidentally mucking up your singleton instance from within the class.</p>\n\n<pre><code>public sealed class Person\n{\n private Person() { }\n private static readonly Lazy<Person> lazyPersonInstance = new Lazy<Person>(() => new Person());\n public static Person GetPersonInstance() \n {\n return lazyPersonInstance.Value;\n }\n}\n</code></pre>\n\n<p>Your method <code>GetPersonInstance</code> can also be a getter-property:</p>\n\n<pre><code> public static Person Instance => lazyPersonInstance.Value;\n</code></pre>\n\n<h1>Exceptions</h1>\n\n<p>IEatBagels already posted an answer about throwing exceptions. I'll elaborate a bit on how it would work in this example. We're looking at the scenario where instantiating the singleton instance throws an exception.</p>\n\n<p>In your code, this exception would be thrown when the static constructor is ran. As IEatBagels points out, when this happens, the type is broken for the rest of the \"program\". This means that you have one shot at creating your instance.</p>\n\n<p>In my example, the initiation of the instance does not happen during the execution of the static constructor. All we do during static initialization - static constructor and static fields act similarly IIRC - is creating the <code>Lazy<T></code> object with the factory method. This method is only executed when <code>lazyPersonInstance.Value</code> is called.</p>\n\n<p>However, <code>Lazy<T></code> caches exceptions. This means that if the factory method throws an exception, that exception will be rethrown on every subsequent call to <code>lazyPersonInstance.Value</code>. Without re-executing the factory method. So in the end, this is the same problem as the static constructor problem. The <code>Lazy<T></code> docs have the following to say:</p>\n\n<blockquote>\n <p>The Lazy stands in for an actual T that otherwise would have been initialized at some earlier point, usually during startup. A failure at that earlier point is usually fatal. If there is a potential for a recoverable failure, we recommend that you build the retry logic into the initialization routine (in this case, the factory method), just as you would if you weren't using lazy initialization.<br>\n <sub><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1?view=netframework-4.8\" rel=\"noreferrer\">MSDN docs</a></sub></p>\n</blockquote>\n\n<p>So if you really must throw exceptions in your constructor, be sure to handle them in the factory method.</p>\n\n<h2>Exceptions and thread-safety</h2>\n\n<p>There's one more workaround for the problem of exceptions in constructors. <code>Lazy</code> has three thread-safety modes, defined in the enum <code>System.Threading.LazyThreadSafetyMode</code> which can be passed to the constructor of <code>Lazy<T></code>.</p>\n\n<ol>\n<li><code>None</code>. No thread safety.</li>\n<li><code>ExecutionAndPublication</code>. This is the default. This ensures that the factory method is executed only once, and that the object on <code>lazy.Value</code> is always the same across threads.</li>\n<li><code>PublicationOnly</code>. This only ensures thread-safety on <code>lazy.Value</code>. It can happen that the factory method is executed simultaneously by multiple threads, but the resulting instance is still the same. The others are discarded. According to the <code>Lazy<T></code> docs, <strong>Exceptions are not cached here</strong>. </li>\n</ol>\n\n<p>This leaves you, the implementer of the singleton with a decision: if there are exceptions that might be thrown, that can't be handled within the factory method, and that might not throw in subsequent attempts (weird, but might happen), you could consider loosening up some of the locking on <code>Lazy</code> to allow for this behaviour.</p>\n\n<hr>\n\n<p>For further reading, see <a href=\"https://csharpindepth.com/articles/singleton\" rel=\"noreferrer\">this blog post by Jon Skeet.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:29:29.507",
"Id": "440509",
"Score": "4",
"body": "One small note - to *truly* be a singleton, the class should also be `sealed` so no inheritors can be created and change behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T18:25:33.243",
"Id": "440543",
"Score": "4",
"body": "@jessecslicer hmm, I was going to mention that, but the private constructor already prevents inheritance. It's never a bad idea though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T19:46:30.580",
"Id": "440552",
"Score": "5",
"body": "I'd probably also mark `lazyPersonInstance` as `readonly` to keep other methods from being able to muck around with it, even by accident."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T06:17:37.337",
"Id": "440602",
"Score": "1",
"body": "@JesseC.Slicer thanks, added :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T07:00:06.663",
"Id": "226613",
"ParentId": "226611",
"Score": "19"
}
},
{
"body": "<p>There's a potential bug with this scenario.</p>\n\n<p>According to <a href=\"https://stackoverflow.com/questions/4737875/exception-in-static-constructor\">this Jon Skeet post</a>, if an exception is thrown inside the <code>static</code> constructor, it is never retried. Which means that if your Singleton initialization has a problem, your Singleton is doomed for the lifetime of your application, which normally isn't a problem with the \"traditional\" way of doing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:57:51.250",
"Id": "440680",
"Score": "0",
"body": "good catch. real world (constructors) vs academic examples."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:57:39.867",
"Id": "226634",
"ParentId": "226611",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "226613",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T05:21:54.530",
"Id": "226611",
"Score": "17",
"Tags": [
"c#",
"design-patterns",
"singleton"
],
"Title": "Singleton Design Pattern implementation in a not traditional way"
}
|
226611
|
<p>I am creating introduction app to java ee and APIs of java ee and i want know if my code is ok (like its working but if it could be done better) and what should i avoid in future</p>
<pre class="lang-java prettyprint-override"><code>package sk.studenthosting.simec.API;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/rest")
public class Rest extends Application {
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package sk.studenthosting.simec.API;
import sk.studenthosting.simec.dao.TaskDao;
import sk.studenthosting.simec.dao.TaskDaoJpa;
import sk.studenthosting.simec.service.TaskService;
import javax.ejb.EJB;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
@Path("/rest")
public class Rest_api {
@EJB
private TaskService service;
@EJB
private TaskDao notes;
@GET
@Produces(MediaType.TEXT_HTML)
public String Index(){
List allNotes = notes.getAllNotes();
return (service.createTable(allNotes));
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public String createNote(@FormParam("Note") String Note,
@QueryParam("Note") String Note2) {
List allNotes = notes.getAllNotes();
if (Note == null){Note = Note2;}
if (Note.equals("") || Note == null) {
return (service.createTable(allNotes)) + "<h1>Note field cannot be empty</h1>";
} else {
TaskDaoJpa addNote = new TaskDaoJpa();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
addNote.setTime(timestamp);
addNote.setNote(Note);
notes.addNote(addNote);
return (service.createTable(allNotes)) + "<p>Note was successfully created</p>";
}
}
@DELETE
@Produces(MediaType.TEXT_HTML)
public String deleteNote(@QueryParam("Id") int Id) {
List allNotes = notes.getAllNotes();
try {
notes.deleteNote(Id);
} catch (Exception e) {
return (service.createTable(allNotes))+"<h1>Note with this Id was not found</h1>";
}
return (service.createTable(allNotes))+"<h1>Note was successfully deleted</h1>";
}
@PUT
@Produces(MediaType.TEXT_HTML)
public String editNote(@QueryParam("Id") int Id,
@QueryParam("Note") String Note) {
List allNotes = notes.getAllNotes();
try {
TaskDaoJpa note = notes.getNote(Id);
note.setNote(Note);
notes.editNote(note);
} catch (Exception e) {
return (service.createTable(allNotes))+"<h1>Note with this Id was not found</h1>";
}
return (service.createTable(allNotes))+"<h1>Note was successfully edited</h1>";
}
@GET
@Path("/{Id}")
@Produces(MediaType.TEXT_HTML)
public String gettingId(@PathParam("Id") String Ids,
@QueryParam("Id") String Ids2){
List allNotes = notes.getAllNotes();
if (Ids == null){Ids = Ids2;}
try {
int Id = Integer.parseInt(Ids);
TaskDaoJpa note = notes.getNote(Id);
ArrayList<TaskDaoJpa> myList = new ArrayList<>();
myList.add(note);
return (service.createTable(myList));
} catch (NumberFormatException e) {
return (service.createTable(allNotes)) + "<h1>In order to get note you have to insert Id(number)</h1>";
} catch (Exception ex){
return (service.createTable(allNotes)) + "<h1>Note with this number doesnt exist</h1>";
}
}
}
</code></pre>
<p>i know its not best to create only html</p>
<pre class="lang-java prettyprint-override"><code>package sk.studenthosting.simec.dao;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Stateless
public class TaskDao {
@PersistenceContext
private EntityManager em;
public void addNote(TaskDaoJpa note) {
em.persist(note);
}
public void editNote(TaskDaoJpa note) {
em.merge(note);
}
public void deleteNote(int noteId) {
em.remove(getNote(noteId));
}
public TaskDaoJpa getNote(int noteId) {
return em.find(TaskDaoJpa.class, noteId);
}
public List getAllNotes() {
return em.createNamedQuery("Notes.getAll").getResultList();
}
}
</code></pre>
<p>i will eventually add text filter and filter for more than one Id</p>
<pre class="lang-java prettyprint-override"><code>package sk.studenthosting.simec.dao;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
@Entity
@Table(name = "notes")
@NamedQuery(name = "Notes.getAll", query = "SELECT t From TaskDaoJpa t")
public class TaskDaoJpa implements Serializable {
private int noteId;
private String note;
private Timestamp time;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "noteId", nullable = false, updatable = false)
public int getNoteId() {
return noteId;
}
protected void setNoteId(int noteId) {
this.noteId = noteId;
}
@Basic
@Column(name = "note", nullable = false, length = -1)
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Basic
@Column(name = "time", nullable = true)
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public TaskDaoJpa(int noteId, String note, Timestamp time) {
this.noteId = noteId;
this.note = note;
this.time = time;
}
public TaskDaoJpa(){}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package sk.studenthosting.simec.service;
import sk.studenthosting.simec.dao.TaskDaoJpa;
import javax.ejb.Local;
import java.util.List;
@Local
public interface TaskService {
String createTable(List<TaskDaoJpa> notes);
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package sk.studenthosting.simec.service;
import sk.studenthosting.simec.dao.TaskDaoJpa;
import javax.ejb.Stateless;
import java.util.List;
@Stateless
public class TaskServiceEjb implements TaskService {
public TaskServiceEjb() {
}
@Override
public String createTable(List<TaskDaoJpa> notes) {
StringBuilder tableTemp = new StringBuilder();
for (Object noteInfo : notes) {
TaskDaoJpa temporary = (TaskDaoJpa) noteInfo;
String betterTime = temporary.getTime().toString().replaceAll("\\.\\d+", "");
tableTemp.append("<tr><td>");
tableTemp.append(temporary.getNoteId());
tableTemp.append("</td><td>");
tableTemp.append(betterTime);
tableTemp.append("</td><td>");
tableTemp.append(temporary.getNote());
tableTemp.append("</td></tr>");
}
String table = " <table border='1'><th>id</th><th>time</th><th>note</th>" + tableTemp + "</table><form action='' method='GET'><input type='text' style='width: 3em;' placeholder='Id' name='Id'/>" +
"<input type='text' placeholder='Note' name='Note'/><br/>" +
"<input type='submit' formmethod='POST' value='Pridat'/>" +
"<input type='submit' value='Vyhladat'/>" +
"<input type='submit' value='Delete'/></form>";
return table;
}
}
</code></pre>
<p>i was also thinking about button i created(Delete button) could be in post method and in jax rs i would create, thanks to java, http Delete request and and sent it again to page, does it work or is there a lot easier method ?
Thanks everyone who will try to help me.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T07:15:30.503",
"Id": "226614",
"Score": "3",
"Tags": [
"java",
"dependency-injection",
"rest",
"jpa"
],
"Title": "HTTP Delete,Put,Get,Post REQUEST java-ee RESTful services JPA CDI EJB"
}
|
226614
|
<p>I have base Controller for Attachments, here is code of it</p>
<p>In this controller, I pass data from the request and return URL of the posted object.</p>
<pre><code>public class ApiAttachmentControllerBase<T> : PM101MobileApiController where T : Entity<int>
{
private readonly IObjectStorageManager _storageManager;
protected readonly IRepository<T> Repository;
public ApiAttachmentControllerBase(IObjectStorageManager storageManager, IRepository<T> repository)
{
_storageManager = storageManager;
Repository = repository;
}
private void CheckFileSize(IFormFile file)
{
if (file.Length > PM101Consts.MaxAttachmentSize)
{
throw new UserFriendlyException(L("Attachment_Warn_SizeLimit",
PM101Consts.MaxAttachmentSizeMb.ToString()));
}
}
private void CheckFileType(IFormFile file, params string[] supportedTypes)
{
if (supportedTypes.Any())
{
var extention = Path.GetExtension(file.FileName);
if (!supportedTypes.ToList().Contains(extention))
{
throw new UserFriendlyException(L("Attachment_Warn_Type", extention));
}
}
}
private async Task<T> GetEntityAsync(int entityId)
{
var entity = await Repository.FirstOrDefaultAsync(entityId);
if (entity == null)
{
throw new UserFriendlyException(L("EntityNotFound"));
}
return entity;
}
protected async Task<List<string>> UploadMultipleAttachmentAsync(
int entityId,
ICollection<IFormFile> uploadFiles,
Func<T, string> getAttachments,
Action<T, string> setAttachments,
params string[] supportedTypes
)
{
var entity = await GetEntityAsync(entityId);
if (uploadFiles != null)
{
var files = uploadFiles.ToList();
files.ForEach(f =>
{
CheckFileType(f, supportedTypes);
CheckFileSize(f);
});
var attachmentUrls = new List<string>();
foreach (var file in files)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileName =
AttachmentHelper.GenerateFilePath(file.FileName, entityId, entity.GetType().Name);
var url = await _storageManager.UploadFileAsync(fileName, ms.ToArray(), file.ContentType);
attachmentUrls.Add(url);
}
}
}
return attachmentUrls;
}
return null;
}
}
</code></pre>
<p>I inherited it in another controller like this</p>
<pre><code>public class InspectionsController : ApiAttachmentControllerBase<Inspection>
{
public InspectionsController(IObjectStorageManager storageManager, IRepository<Inspection> repository) : base(
storageManager, repository)
{
}
</code></pre>
<p>And then I use it in a method like this</p>
<pre><code>[HttpPost]
public async Task<IActionResult> AddPreInspection([FromForm] CreatePreInspectionDto input)
{
var preInspectionCount = await Repository.GetAll().Where(x => x.InspectionTypeId == 1).ToListAsync();
if (preInspectionCount.Count > 0)
{
return Conflict("Pre inspection already exists");
}
var preInspection = new Inspection();
ObjectMapper.Map(input, preInspection);
var id = await Repository.InsertAndGetIdAsync(preInspection);
var inspectionGet = await Repository.GetAll().FirstOrDefaultAsync(x => x.Id == id);
if (input.EvidenceAttachments != null)
{
var evidenceAttachments = string.Join(";", await UploadMultipleAttachmentAsync(
id,
input.EvidenceAttachments,
a => a.EvidenceAttachments,
(a, value) => a.EvidenceAttachments = value,
".jpeg", ".png", ".jpg"
));
inspectionGet.FrontPropertyAttachments = evidenceAttachments;
}
if (input.FrontPropertyAttachments != null)
{
var frontPropertyAttachments = string.Join(";", await UploadMultipleAttachmentAsync(
id,
input.EvidenceAttachments,
a => a.EvidenceAttachments,
(a, value) => a.EvidenceAttachments = value,
".jpeg", ".png", ".jpg"));
inspectionGet.FrontPropertyAttachments = frontPropertyAttachments;
}
await Repository.UpdateAsync(inspectionGet);
return Ok();
}
</code></pre>
<p>Maybe I can have a more elegant way to post an image, get URL and update entity than do all these checks in controller action?</p>
|
[] |
[
{
"body": "<p>I have a few ideas...</p>\n\n<ul>\n<li><code>CheckFileSize</code> & <code>CheckFileType</code> should be implemented either via action-filters or <a href=\"https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2\" rel=\"noreferrer\">Model validation attributes</a></li>\n<li>the exceptions they throw are too generic and don't tell me which files where invalid</li>\n<li><code>Repository.GetAll().Where(x => x.InspectionTypeId == 1)</code> getting everything and then filtering it is very inefficient. You should remove <code>GetAll</code></li>\n<li><code>Conflict(\"Pre inspection already exists\")</code> is not helpful. I'd like to know which pre-inspection caused the error.</li>\n<li><code>var files = uploadFiles.ToList();</code> is unnecessary becuase <code>files.ForEach(f =></code> is an ugly way to work with a collection. Use a normal <code>foreach</code> instead. As a matter of fact you can do this with the other loop you have there. Is it by design that you don't want to uplodad valid attachements but stop processing them if anyone is invalid?</li>\n<li><code>.Where(x => x.InspectionTypeId == 1)</code> doesn't make any sense with the hardcoded <code>1</code>. Did you mean to write <code>.Where(x => x.InspectionTypeId == input.InspectionTypeId)</code>?</li>\n<li><code>var preInspectionCount = await Repository.GetAll().Where(x => x.InspectionTypeId == 1).ToListAsync();</code> you could use <code>CountAsync</code> here like <code>var preInspectionCount = await Repository.CountAsync(x => x.InspectionTypeId == 1)</code></li>\n<li>what do you need <code>getAttachments</code> and <code>setAttachments</code> for? They are not used anywhere</li>\n<li>what if <code>if (input.EvidenceAttachments != null)</code> and <code>if (input.FrontPropertyAttachments != null)</code> are true? Both <code>if</code>s assign the value to <code>inspectionGet.FrontPropertyAttachments =</code> so the second one will overwirte the result of the first one. Is this a bug or by design? They are also both using <code>input.EvidenceAttachments,</code> with the <code>UploadMultipleAttachmentAsync</code> so there is another bug. </li>\n</ul>\n\n<p>It looks like you have (at least) three bugs there. Are you sure this actually works?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T10:47:32.900",
"Id": "440487",
"Score": "0",
"body": "Thank's for advice. Yeah, it works"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T10:52:39.823",
"Id": "440489",
"Score": "0",
"body": "I find some little bugs. Thank's"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T10:45:49.033",
"Id": "226619",
"ParentId": "226615",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226619",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T07:51:34.587",
"Id": "226615",
"Score": "2",
"Tags": [
"c#",
".net",
"asp.net-core"
],
"Title": "Posting images from request to Azure blob"
}
|
226615
|
<p>I have SQL scripts that I want to be executable directly in the editor (like DataGrip or SSMS) and also in automated integration tests. However, in each use-case they require different environment and version parameters. I cannot use <code>string_split</code> because we use an ancient <strong>SQL Server 2012</strong>.</p>
<p>In order to differentiate between them, I created the <code>GetCurrentOrDefault</code> function that can either use the first or the second value. </p>
<p>I start by finding the index of the <code>|</code> that I use as a separator. Then I get the string before and after this character. Finally, I check whether the string has the format <code>'{%}|%'</code> and if yes, then I use the default version, otherwise the current one. (All magic-numbers are arbitrary primes.)</p>
<pre><code>if object_id('dbo.GetCurrentOrDefault') is not null drop function GetCurrentOrDefault
go
create function GetCurrentOrDefault(@valueOrDefault nvarchar(59)) returns nvarchar(17)
begin
declare @current_value as nvarchar(17);
declare @default_value as nvarchar(17);
declare @value_separator_index as int
select @value_separator_index = charindex('|', @valueOrDefault)
if @value_separator_index = 0 return null
select @current_value = substring(@valueOrDefault, 0, @value_separator_index)
select @default_value = substring(@valueOrDefault, @value_separator_index + 1, len(@valueOrDefault) - @value_separator_index + 1)
return iif(@valueOrDefault like '{%}|%', @default_value, @current_value)
end
go
</code></pre>
<p>Usage example:</p>
<pre><code>declare @env as nvarchar(51) = N'{Environment}|production'
declare @ver as nvarchar(59) = N'{Version}|3.9.0'
select @env = dbo.GetCurrentOrDefault(@env)
select @ver = dbo.GetCurrentOrDefault(@ver)
if @env is null raiserror ('Invalid environment: ' + @env, 16, 1)
if @ver is null raiserror ('Invalid version: ' + @ver, 16, 1)
-- many many inserts with settings ...
</code></pre>
<p>Tests replace the placeholders with their custom values like:</p>
<blockquote>
<pre><code>.GetSql().Format(new { Environment = "test", Version = "4.0.0" }) // C#
</code></pre>
</blockquote>
<hr>
<p>What do you think? Is there a more clever solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:10:52.430",
"Id": "440506",
"Score": "1",
"body": "Is there a reason the test can't have a parameter with a default value? e.g. if your test is a stored procedure, it can't have `@Environment nvarchar(51) = N'production'` as a parameter? Your last piece suggests that your test runner is in some other language, maybe C#? Can you use parameterized SQL in the test runner to handle this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:25:52.403",
"Id": "440508",
"Score": "1",
"body": "@Dannnno mhmm... theoretically I could use such paremeterized SQL but I guess I then would need to have some kind of a stored procedure for that. Currently it's just a _flat_ file with many inserts. Your guess about C# was correct. I added a comment for this. I like being able execute scripts directly and via code but this is tricky as you need some fallback values when running it in an IDE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:22:35.543",
"Id": "440517",
"Score": "0",
"body": "_.GetSql()_ gets you the entire script? or just the declarations of variables.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:30:47.460",
"Id": "440520",
"Score": "0",
"body": "Is there an option to have some table exist in the database that should have such values, and the script just uses the default if the table is missing/not populated?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:36:56.237",
"Id": "440523",
"Score": "1",
"body": "@dfhwze tl;dr: the entire script. It's defined in the main project and I linked it in a test project under a different name as an embedded resource - can it be more complex? :-P I then import it, _inject_ the two values and execute the script to insert these settings with a different environment and/or version. After that I run tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:39:30.883",
"Id": "440524",
"Score": "0",
"body": "@Dannnno nope, this script only inserts a bunch of settings with environment & version. Nothing more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T17:49:28.767",
"Id": "442653",
"Score": "1",
"body": "You can replace `if object_id('dbo.GetCurrentOrDefault') is not null drop function GetCurrentOrDefault` with just `DROP FUNCTION IF EXISTS [dbo].[GetCurrentOrDefault]`. It also fixes a potential bug with the lack of schema (`dbo` ) on the second part of your statement. And it fixes another obscure potential bug if `GetCurrentOrDefault` happens to be anything other than a function."
}
] |
[
{
"body": "<h3>Potential Issues</h3>\n\n<ul>\n<li>a naive string replacement could change more than just the placeholders; for instance, when another part of the script uses the same string as a literal</li>\n<li>the replacement can introduce a value with the same format <code>{%}</code>; your sql has no way of knowing that this is a replacement value, and since the format matches that of a place holder, it will be ignored and the default value will be taken</li>\n<li>make sure the sql user of your unit test project has limited rights, because you don't know the exact sql that is going to run at runtime</li>\n</ul>\n\n<p>If you insist on using a string replacement, try to manage escape characters and try to avoid false positives/negatives, both from sql and C# injection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:41:21.573",
"Id": "440525",
"Score": "1",
"body": "I might try the ugly python style of special variable names like `____Version____` or should I use more underscores? I gues python fans would be thrilled, the more the better ;-]"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:39:24.580",
"Id": "226633",
"ParentId": "226616",
"Score": "3"
}
},
{
"body": "<h2>Answering your question</h2>\n<p>Overall, I think the solution is sound, but there are a few things you could make cleaner. I agree with everything in <a href=\"https://codereview.stackexchange.com/a/226633/47529\">dfhwze's answer</a>, but assuming this is the route you keep here are a few thoughts:</p>\n<p>This piece is a little risky in case <code>N'|'</code> exists in the new value.</p>\n<pre><code>SELECT @value_separator_index = CHARINDEX( '|', @valueOrDefault );\n</code></pre>\n<p>You probably want the last <code>N'|'</code> in the value (didn't test this; I probably have an off-by-one error or missing zero-handling).</p>\n<pre><code>SELECT @value_separator_index = LEN( @valueOrDefault - CHARINDEX( N'|', REVERSE( @valueOrDefault ) ) )\n</code></pre>\n<p>You can also provide an expected label to the function to avoid an issue that dfhwze calls out.</p>\n<blockquote>\n<p>the replacement can introduce a value with the same format {%}; your sql has no way of knowing that this is a replacement value, and since the format matches that of a place holder, it will be ignored and the default value will be taken</p>\n</blockquote>\n<p>Then you can make sure the Label doesn't have unexpected values by comparing it with... <em>another pattern</em></p>\n<pre><code>IF @Label LIKE N'%[%]%' \n OR @Label LIKE N'%[_]%' \n OR @Label LIKE N'%[\\[]%' ESCAPE '\\' \n OR @Label LIKE N'%[\\]]%' ESCAPE '\\'\nBEGIN\n -- Do stuff, like replace the values and escape them\nEND;\n</code></pre>\n<p>From this point, your final validation becomes (assuming you use <code>\\</code> to escape things), which avoids the issue of them providing a strange non-default value</p>\n<pre><code>RETURN IIF( @valueOrDefault LIKE '{' + @Label + '}|%' ESCAPE '\\', @default_value, @current_value)\n</code></pre>\n<hr />\n<h2>Disputing your premise, and providing an alternative</h2>\n<p>Once you peel back the string parsing, you can realize that this effectively becomes <code>ISNULL</code></p>\n<pre><code>SET @environment = ISNULL( <<maybePopulated>>, N'production' )\n</code></pre>\n<p>You could accomplish this like so:</p>\n<pre><code>DECLARE @configuredEnvironment nvarchar(17);\nDECLARE @defaultEnvironment nvarchar(17) = N'production'\nDECLARE @environment nvarchar(17) = ISNULL( @configuredEnvironment, @defaultEnvironment );\n</code></pre>\n<p>Then if your test runner can just make sure to set <code>@configuredEnvironment</code> in the task (this might be as easy as dropping the first row of the file and replacing it with your configuration) and you don't have to do string parsing.</p>\n<hr />\n<h2>Providing another alternative</h2>\n<p>Ultimately, what you're really trying to do is create parameterized SQL with default values. As it turns out, this is a concept that already exists:</p>\n<pre><code>CREATE PROCEDURE dbo.[test my cool thing]\n( @environment nvarchar(17) = N'production',\n @version nvarchar(17) = N'3.9.0'\n)\nAS\nBEGIN\n -- do something cool\nEND;\nGO\n</code></pre>\n<p>From your test runner, this then becomes</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using (var conn = new SqlConnection(connectionString)) // Can be pulled from a config file\n{\n conn.Open();\n using (var cmd = new SqlCommand("dbo.[test my cool thing]", conn))\n {\n // I forget the exact properties, but this should be close\n cmd.Parameters.AddWithValue("@environment", environment); // config file\n cmd.Parameters.AddWithValue("@version", version); // config file\n cmd.CommandType = CommandType.StoredProcedure;\n \n cmd.ExecuteNonQuery();\n }\n}\n</code></pre>\n<p>Then for end-users running it in the IDE it just becomes</p>\n<pre><code>EXECUTE dbo.[test my cool thing] -- Pass parameters if you want them\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T16:23:58.093",
"Id": "440532",
"Score": "0",
"body": "Mind blowing! `ISNULL` looks really cool."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T16:09:30.057",
"Id": "226635",
"ParentId": "226616",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226635",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T08:30:35.830",
"Id": "226616",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"t-sql",
"configuration"
],
"Title": "Function to get current value or default from a string of two values"
}
|
226616
|
<p>I've created a simple data visualization in python that shows the movement of refugees around the world. The code works but I feel it is a bit slow. it takes about 10 s (on my hardware at least) to generate the plot.
I'm using a python graphing library called plotly to create the graphics. The user can click an origin country from the dropdown and see the movement of refugees from that country. Due to the way that the graphing library is set up, the dropdown and other interactive objects in the plotly menu are more just meant to restyle certain elements, and in the case of a dropdown menu, no 'value' is returned from the dropdown. What I did to make the dropdown work is I've created a visibility list for every trace in the visualization, perhaps this is part of what is making the code run a bit slow. The other thing that might make the code run slower is I am creating an arrow for each line, but I want the arrow to point correctly relative to the direction of travel so I need to manually calculate the direction of the arrow, which I believe is also making the code run slower.</p>
<p>Some of the steps I've taken to try to speed up my code include concatenating text using join(), using dictionaries for values where possible, and try to minimize the amount of code I use within loops.</p>
<pre><code>import plotly.graph_objects as go
import pandas as pd
import numpy as np
import math
#read in a list of all countries
countries = pd.read_csv('https://raw.githubusercontent.com/jerguy1928/refugee_map/master/rounded_country_centroid_locations.csv')
countries.head()
#this is just me testing things with a slightly different file
# travel_paths = pd.read_csv('https://raw.githubusercontent.com/jerguy1928/refugee_map/master/test_file_3.csv')
#read in a list of refugee movements
travel_paths = pd.read_csv('https://raw.githubusercontent.com/jerguy1928/refugee_map/master/test_file_4.csv')
#sorting the data (my functions require the data to be sorted but my data isn't sorted)
travel_paths.head()
travel_paths.sort_values(["origin","year"],inplace=True)
travel_paths = travel_paths.reset_index(drop=True)
#creating two dictionaries for each countries corresponding latitudes/longitudes
country_lat = dict(zip(countries['country'],countries['lat']))
country_long = dict(zip(countries['country'],countries['long']))
#creates a world map as a backdrop
fig = go.Figure(data=go.Choropleth(
locations = countries['country_code_3'],
z = countries['zero'],
text = countries['country'],
hoverinfo= 'text',
marker_line_color='darkgray',
marker_line_width=0.5,
showscale= False,
))
# creates the dropdown menu. Each menu entry works by passing a T/F array to the 'visible' property for the map
def dropdown_menu():
mentioned_countries = []
menu_data = []
menu = []
k = 0
for j in range(len(travel_paths)):
ORIGIN = travel_paths['origin'][j]
desc = ["Movement of refugees from ",ORIGIN]
msg = ''.join(desc)
false_array = list(np.zeros(len(travel_paths),bool))
if ORIGIN not in mentioned_countries:
mentioned_countries.append(ORIGIN)
false_array.insert(j+1,True)
false_array[0] = True
menu_data.insert(k,false_array)
menu.insert(k,dict(args = [{"visible": menu_data[k]},{"title": msg} ], label = ORIGIN, method = "update"))
k += 1
else:
menu_data[k-1].insert(j+1,True)
#these two lines are used for a 'Show All' paths (all true array)
true_array = list(np.ones(len(travel_paths),bool))
menu.insert(0,dict(args = [{"visible": true_array},{"title": "Currently showing all refugees"} ], label = "<i>Show all</i>", method = "update"))
return menu
#this dictionary descibes the size of each path based on the number of refugees
refugee_lvl = {
(0,20):0.5,
(21,50):1,
(51,100):1.5,
(101,500):2,
(501,1000):2.5,
(1001,10000):3,
(10001,50000):3.5,
(50001,100000):4,
(100001,1000000):4.5,
(1000001,5000000):5
}
#this dictionary is used for the size of each arrow for each path
marker_lvl = {
(0,20):3,
(21,50):3.5,
(51,100):4,
(101,500):4.5,
(501,1000):5,
(1001,10000):5.5,
(10001,50000):6,
(50001,100000):6.5,
(100001,1000000):7,
(1000001,5000000):7.5
}
# my code calculates the angle of travel and assigns an appropriate 'arrowhead' (my makeshift draw arrow solution)
angle_calc = {
(0,22.5):'triangle-up',
(22.501,67.5):'triangle-ne',
(67.501,112.5):'triangle-right',
(112.501,157.5):'triangle-se',
(157.501,202.5):'triangle-down',
(202.501,247.5):'triangle-sw',
(247.501,292.5):'triangle-left',
(292.501,337.5):'triangle-nw',
(337.5,360):'triangle-up',
}
#this function returns a value from a dictionary with range values
def get_key(table,num):
for key in table:
if key[0] < num < key[1]:
result = table[key]
return result
# this function calculates the angle of travel for the travel path
def get_shape(start_lon,start_lat,end_lon,end_lat):
s2 = (end_lat - start_lat)/(end_lon-start_lon)
angle = math.atan((900000-s2)/(1+(900000*s2)))
angle_degrees = math.degrees(angle)
if start_lat > end_lat:
angle_degrees +=180
elif angle_degrees < 0 and start_lat < end_lat:
angle_degrees += 360
return get_key(angle_calc,angle_degrees)
#this function draws the traces
def trace_creator():
#These dictionaries define options for if the refugee movement is internal (IDP) or external (REF)
IDP = {
'mode':'markers',
'size':15,
'person_type':'IDPs',
'opacity':1,
'color':'blue',
'symbol':'circle-open'
}
REF = {
'mode':'lines+markers',
'person_type':'Refugees',
'opacity':[0,1],
'color':'green',
}
#loop through all travel paths
for i in range(len(travel_paths)):
ORIGIN = travel_paths['origin'][i]
DESTINATION = travel_paths['destination'][i]
YEAR = travel_paths['year'][i]
REFUGEES = travel_paths['refugees'][i]
ORIGIN_LAT = country_lat.get(ORIGIN)
ORIGIN_LON = country_long.get(ORIGIN)
DEST_LAT = country_lat.get(DESTINATION)
DEST_LON = country_long.get(DESTINATION)
lat_list = [ORIGIN_LAT]
lon_list = [ORIGIN_LON]
#If internal movement
if ORIGIN == DESTINATION:
mode_val = IDP.get('mode')
size_val = IDP.get('size')
person_type = IDP.get('person_type')
marker_opacity = IDP.get('opacity')
marker_color = IDP.get('color')
marker_symbol = IDP.get('symbol')
#if external movement
else:
lat_list.append(DEST_LAT)
lon_list.append(DEST_LON)
mode_val = REF.get('mode')
size_val = get_key(marker_lvl,REFUGEES)
person_type = REF.get('person_type')
marker_opacity = REF.get('opacity')
marker_color = REF.get('color')
marker_symbol = get_shape(ORIGIN_LON,ORIGIN_LAT,DEST_LON,DEST_LAT)
text_list = [ORIGIN,' → ', DESTINATION, "<br>", person_type, ": ", format(REFUGEES,',d')]
s = ''
# passing the values from above to the add_trace method
fig.add_trace(
go.Scattergeo(
lat = lat_list,
lon = lon_list,
mode = mode_val,
marker= dict(
size = size_val,
symbol = marker_symbol,
color = marker_color,
opacity = marker_opacity
),
line = dict(width = get_key(refugee_lvl,REFUGEES),color = 'red'),
showlegend= True,
legendgroup= str(YEAR),
name = str(YEAR),
text= s.join(text_list),
hoverinfo= 'text'
)),
trace_creator()
#adding titles/dropdown menu
fig.update_layout(
updatemenus=[
go.layout.Updatemenu(
buttons = dropdown_menu(),
direction="down",
pad={"r": 10, "t": 10},
showactive=True,
x=0.37,
xanchor="left",
y= 1.08,
yanchor="top"
),
],
title_text = 'Movement of UNHCR Refugees (Choose origin country from the list)',
geo = go.layout.Geo(
projection_type = 'mercator',
showland = True,
showcountries= True,
landcolor = 'rgb(243, 243, 243)',
countrycolor = 'rgb(204, 204, 204)',
),
)
#draw the figures
fig.show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:17:31.847",
"Id": "440507",
"Score": "0",
"body": "Have you tried profiling your code to see which parts take a longer time? It's entirely possible it is slow because you're downloading data from the web"
}
] |
[
{
"body": "<blockquote>\n <p>The other thing that might make the code run slower is I am creating an arrow for each line, but I want the arrow to point correctly relative to the direction of travel so I need to manually calculate the direction of the arrow, which I believe is also making the code run slower.</p>\n</blockquote>\n\n<p>That would be it. <code>trace_creator()</code> alone takes 10s on my machine, which is basically all of the runtime for me.</p>\n\n<p>Half of it is <code>go.Scattergeo</code> calls, the other <code>fig.add_trace</code>.</p>\n\n<p>Unfortunately I don't know the library, but, I imagine there most be some construction where you're only adding a single <code>Scattergeo</code> with all of those paths included. If not, then, perhaps they can be grouped and so the number of them could be reduced from the ~1k of them?</p>\n\n<hr>\n\n<p>How did I find out?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python\">This post</a> for how to time a block of code. I inserted some <code>timeit</code> timers and just narrowed it down.</p>\n\n<p>The other options is, as was already said, to use <a href=\"https://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script\">a profiler</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T20:52:36.197",
"Id": "226649",
"ParentId": "226617",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T10:18:09.047",
"Id": "226617",
"Score": "6",
"Tags": [
"python",
"performance",
"pandas",
"data-visualization",
"geospatial"
],
"Title": "Graphing refugee movements using plotly in Python"
}
|
226617
|
<p>I am working on an RPG in Java and I am using a tile-based map. The characters will not be building, so I will not need to store the maps outside of the game, but I feel as if there is a more efficient way to initialize my maps.</p>
<pre class="lang-java prettyprint-override"><code>public static int[][] spawnWorld = {
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 6, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 11, 4, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 2, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 2, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 2, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 2, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 2, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 6, 5, 7, 8, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 0, 0, 2, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 1, 0, 0, 2, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 10, 4, 4, 12, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14 },
{ 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14 } };
public static int[][] spawnSigns = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};
public static int[][] mainWorld;
public static int[][] grassHouse1;
</code></pre>
<p>It's just a bunch of cluttering numbers that takes up a lot of space.
How can I make this more efficient?</p>
<p><strong>EDIT:</strong></p>
<p>A list of the tile ids so far:</p>
<p>VGrassPathCenter - 0</p>
<p>VGrassPathLeft - 1</p>
<p>VGrassPathRight - 2</p>
<p>VGrassPathTop - 3</p>
<p>VGrassPathBottom - 4</p>
<p>VGrassPathTopLeftCorner - 5</p>
<p>VGrassPathTopLeft - 6</p>
<p>VGrassPathTopRightCorner - 7</p>
<p>VGrassPathTopRight - 8</p>
<p>VGrassPathBottomLeftCorner - 9</p>
<p>VGrassPathBottomLeft - 10</p>
<p>VGrassPathBottomRightCorner - 11</p>
<p>VGrassPathBottomRight - 12</p>
<p>EmptyTile - 13</p>
<p>Grass - 14</p>
<p>Signs are just 1 = Sign, 0 = No Sign.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T13:08:15.977",
"Id": "440493",
"Score": "0",
"body": "Could you maybe list what the numbers are for? Like, what makes a tile = 14 instead of 0 or 1?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:02:32.073",
"Id": "440505",
"Score": "0",
"body": "@IEatBagels, Just added Tile Ids. Its to tell the Tile Writing method which tile to put down."
}
] |
[
{
"body": "<p>Is there a better way? Plainly speaking, not so much.</p>\n\n<p>The thing is, <em>you</em> decide what is the content of the array and the clearest way of doing so is how you did it. We could do something like this : </p>\n\n<pre><code>//I put x,y because I didn't count the row/column sizes\npublic static int[][] spawnWorld = new int[x][y];\n\nArray.fill(spawnWorld, 14);\n\n//Those are random indices\nspawnWorld[14][10] = 1;\nspawnWorld[15][10] = 1;\nspawnWorld[16][10] = 1;\n//etc..\n</code></pre>\n\n<p>Does that look better? Hell no. At least with your current format, you can see the patterns.</p>\n\n<p>So what can we do?</p>\n\n<p>I think your best bet is to not store the maps in the code. Imagine you wanted to change a map at some point, you would need to recompile your code! That seems overkill. The best solution would be to have separate (text?) files that contains the map. For example : </p>\n\n<p><strong>map1.map</strong></p>\n\n<pre><code>14,14,14,14,14,14,14,14,14,14\n14,14,14,1,14,14,14,14,14,14\n14,14,14,1,14,14,14,14,14,14\n14,14,14,1,14,14,14,14,14,14\n14,14,14,1,14,14,14,14,14,14\n14,14,14,1,14,14,14,14,14,14\n</code></pre>\n\n<p>And to load the said map file in your code and put it in an array.</p>\n\n<p>Also, you might want to consider writing a small form application to create the maps and save them to the <code>.map</code> format (I've used <code>.map</code>, but it could be whatever you want). That way you could make your map easily without having to write a bunch of 14s and 1s everywhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:23:28.557",
"Id": "440518",
"Score": "0",
"body": "How would you load the format?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:25:37.887",
"Id": "440519",
"Score": "0",
"body": "@WeaponGod243 Well, that's kind of up to you to figure it out :) But if you read it like a text file, it won't be hard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T08:23:38.877",
"Id": "440628",
"Score": "0",
"body": "Once the data is in a text file, there is no pressing need to use numbers or commas anymore. Choose a suitable character for each tile type and map them to numbers when reading. Then you can edit the maps easily in Emacs (not vi)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:08:00.130",
"Id": "226625",
"ParentId": "226621",
"Score": "2"
}
},
{
"body": "<p>Can't post comments yet so just a thought - If you are going to have external files and will be editing them it might be an idea to map your numbers to emoji characters or other suitable font which might give you a more visually accessible map file format.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:31:18.343",
"Id": "440669",
"Score": "1",
"body": "No why did I not think of that! Pretty clever idea. I guess it shows that I'm from the ASCII generation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:35:39.827",
"Id": "226677",
"ParentId": "226621",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226625",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T11:59:00.217",
"Id": "226621",
"Score": "2",
"Tags": [
"java",
"performance",
"beginner",
"game",
"role-playing-game"
],
"Title": "RPG Map Initialization"
}
|
226621
|
<p>I am building a color sorting machine using a Arduino uno and a TCS3200 color sensor. I have a code that is working perfectly fine however I feel like the code could be a bit more clean seeing that I am using 3 almost identical for loops. Could anyone help me re-write these 3 for loops into one loop. Thank you in advance!</p>
<p>Like I mentioned the code works perfectly fine. I only need some help re-writing these 3 for loops</p>
<pre><code>void loop() {
delay(150);
float frequencyR[3];
for(unsigned int i = 0; i < 3; i++) {
delay(150);
digitalWrite(S2, LOW);
digitalWrite(S3, LOW);
frequencyR[i] = pulseIn(sensorOut, LOW);
delay(150);
}
float frequencyG[3];
for(unsigned int i = 0; i < 3; i++) {
delay(150);
digitalWrite(S2, HIGH);
digitalWrite(S3, HIGH);
frequencyG[i] = pulseIn(sensorOut, LOW);
delay(150);
}
float frequencyB[3];
for(unsigned int i = 0; i < 3; i++) {
digitalWrite(S2, LOW);
digitalWrite(S3, HIGH);
frequencyB[i] = pulseIn(sensorOut, LOW);
delay(150);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T13:09:24.243",
"Id": "440495",
"Score": "0",
"body": "Hi Nils, could you rework your indentation? I'm sure you can see now that it's not as it should be (I'm assuming this isn't the way your code is indented in your real code)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:48:16.170",
"Id": "440600",
"Score": "1",
"body": "You're reading values into local arrays, and not doing anything with them? Please show us your real code, with context, so that we can give you proper advice. See [ask]."
}
] |
[
{
"body": "<p>Pass the pin values as ints and the array as a float pointer.</p>\n\n<pre><code>void sample(int pin1, int pin2, float *result){\n for(unsigned int i = 0; i < 3; i++) {\n digitalWrite(S2, pin1);\n digitalWrite(S3, pin2);\n result[i] = pulseIn(sensorOut, LOW);\n\n delay(150);\n\n }\n}\n</code></pre>\n\n<p>And you call it with:</p>\n\n<pre><code>float frequencyR[3];\nsample(LOW, LOW, frequencyR);\n\nfloat frequencyG[3];\nsample(HIGH, HIGH, frequencyG);\n\nfloat frequencyB[3];\nsample(LOW, HIGH, frequencyB);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T12:48:12.420",
"Id": "226623",
"ParentId": "226622",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226623",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T12:40:35.733",
"Id": "226622",
"Score": "-1",
"Tags": [
"c++",
"performance",
"arduino"
],
"Title": "How do I re-write 3 for loops into one function"
}
|
226622
|
<p>I have an <code>Analytics</code> class that performs some actions to compile analytics data. Here is that class:</p>
<pre><code><?php
namespace App\Analytics\StockMoves;
use Exception;
use App\Order;
use Carbon\Carbon;
use App\StockableItem;
use App\Odoo\Contracts\Client as Odoo;
use Illuminate\Support\Facades\Storage;
use App\Analytics\MissingDatesException;
use App\Analytics\StockMoves\ChannelInterface;
class Analytics
{
/**
* The start date as a string in "YYYY-MM-DD HH:MM:SS"
* format UTC. The retrieved date will be greater than
* or equal to this value.
*/
protected $start;
/**
* The end date as a string in "YYYY-MM-DD HH:MM:SS"
* format UTC. The retrieved data will be less than
* or equal to this value
*/
protected $end;
/**
* The path to the file where data rows will be written
*/
protected $filename;
/**
* The path to the file where error rows will be written
*/
protected $errorFilename;
/**
* The count of data rows written
*/
protected $dataCount = 0;
/**
* The count of error rows written
*/
protected $errorCount = 0;
/**
* The odoo api client
*/
protected $odoo;
public function __construct(Odoo $odoo, ChannelInterface $channel)
{
$this->odoo = $odoo;
$this->channel = $channel;
}
public function setDates($start, $end)
{
$this->start = $start;
$this->end = $end;
}
public function getDomain()
{
return $this->channel->getDomain($this);
}
public function getMoves($page)
{
return $this->odoo->searchRead(
'stock.move',
$this->getDomain(),
$this->channel->getFields(),
$page);
}
public function getTotalPages()
{
$total = $this->odoo->count('stock.move', $this->getDomain());
return ceil($total / 100);
}
public function getFilename()
{
return str_replace(
' ',
'.',
sprintf(
"analytics/%s/%s.%s--%s",
$this->channel->getName(),
Carbon::now()->timestamp,
$this->start,
$this->end
)
);
}
public function getErrorFilename()
{
return $this->getFilename() . '.errors';
}
public function deleteFiles()
{
Storage::disk('local')->delete([
$this->getFilename(),
$this->getErrorFilename()
]);
}
public function writeRow(array $row)
{
Storage::disk('local')
->append($this->getFilename(), json_encode($row));
$this->dataCount++;
}
public function writeError(array $move, Exception $e)
{
Storage::disk('local')
->append($this->getErrorFilename(),
sprintf("Move ID %s: %s:%s - Error message: %s",
$move['id'],
$e->getFile(),
$e->getLine(),
$e->getMessage()
)
);
$this->errorCount++;
}
public function getDataCount()
{
return $this->dataCount;
}
public function getErrorCount()
{
return $this->errorCount;
}
public function getRowData($move)
{
return $this->channel->getRowData($move);
}
public function run()
{
throw_unless($this->start && $this->end, MissingDatesException::class);
$this->deleteFiles();
$pages = $this->getTotalPages();
for ($page = 1; $page <= $pages; $page++) {
$moves = $this->getMoves($page);
foreach ($moves as $move) {
try {
$row = $this->getRowData($move);
}
catch(Exception $e) {
$this->writeError($move, $e);
continue;
}
$this->writeRow($row);
}
}
}
public function getStartDate()
{
return $this->start;
}
public function getEndDate()
{
return $this->end;
}
}
</code></pre>
<p>As you can see, this class has a <code>ChannelInterface</code> injected into the constructor. That channel is used throughout various methods in the class. There are currently three implementations of <code>ChannelInterface</code>:</p>
<pre><code>ChannelA
ChannelB
ChannelC
</code></pre>
<p>Now I am creating a <code>RunChannelBAnalytics</code> command, and within that command I need to instantiate an <code>Analytics</code> instance using the <code>ChannelB</code> implementation. I would like to make use of the Laravel IOC, so one thing I can do is this:</p>
<pre><code>$analytics = app(Analytics::class, ['channel' => new ChannelB]);
</code></pre>
<p>Please note that the first <code>$odoo</code> argument in the constructor is already bound into the IOC, so that argument is populated correctly.</p>
<p>My question is, how can I more properly use the IOC to get the correct <code>ChannelInterface</code>, in this case <code>ChannelB</code>, without hardcoding as I show above.</p>
<p>I will ultimately have another command for <code>RunChannelCAnalytics</code> in which I will need to use the <code>ChannelC</code> implementation.</p>
<p>The only way I can think to accomplish this is to create another analytics class for each channel and bind into the IOC using contextual binding. For example, I would create:</p>
<pre><code>class ChannelBAnalytics extends Analytics {}
</code></pre>
<p>And then in a service provider I would say:</p>
<pre><code>$this->app->when(ChannelBAnalytics::class)
->needs(ChannelInterface::class)
->give(function () {
return new ChannelB;
});
</code></pre>
<p>But this doesn't seem ideal to me since I will then be creating subclasses for each channel, which is what I was trying to avoid by using the composition method.</p>
<p>Is there a proper or better way to accomplish what I need?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:43:20.747",
"Id": "440596",
"Score": "1",
"body": "It seems that your `RunChannelBAnalytics` command is the code to be reviewed, and the `Analytics` class you've shown us is just background information. But you haven't actually shown us a `RunChannelBAnalytics` command, other than sketches of how you might go about writing one."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T14:58:48.373",
"Id": "226628",
"Score": "1",
"Tags": [
"php",
"dependency-injection",
"laravel"
],
"Title": "How should I instantiate a class using composition with Laravel IOC container?"
}
|
226628
|
<p>I'm working on improving my Python skills and have been doing a daily code problem. For the problem:</p>
<p><em>Given a word W and a string S, find all starting indices in S which are anagrams of W</em></p>
<p>For example s = "abxaba" and w = "ab" should return [0, 3, 4],
s = "cbaebabacd", w = "abc" should return [0, 6]</p>
<p>Is there more efficient/pythonic solution than the code I wrote? Storing the queue as a list and casting it to set twice per loop feels like it must be inefficient.</p>
<pre><code>def anagram_indices(w, s):
w = set(list(w))
queue = []
index = []
for x, i in enumerate(list(s)):
queue.append(i)
while(w.issubset(set(queue[1:]))):
queue.pop(0)
if w == set(queue):
index.append(x-len(w)+1)
return(index)
word = "ab"
string = "abxaba"
print(anagram_indices(word, string))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:33:59.160",
"Id": "440522",
"Score": "0",
"body": "Hey Cooper, could you give us some examples of what your code is supposed to output for some inputs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T16:16:41.947",
"Id": "440530",
"Score": "2",
"body": "Question edited!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T16:23:59.497",
"Id": "440533",
"Score": "0",
"body": "`print(anagram_indices(\"abab\", \"abxba\"))`returns `[0, 3]`"
}
] |
[
{
"body": "<p><code>index</code> is a singular noun that doesn't represent of group of things, therefor it isn't a good name for an array.</p>\n\n<p>Your method is named <code>anagram_indices</code> and returns an array, I like to call the returned array <code>results</code>, so it's clear that the array are the anagram indices.</p>\n\n<p>Using <code>i</code> and <code>x</code> is <em>very</em> confusing, so much that it made me question my own knowledge of the <code>enumerate</code> function. I expected <code>i</code> to be the index and <code>x</code> to be the letter, while it's the opposite. You should rename those with better variable names. Actually, using single letter variable names is almost never a good idea, there are some edge cases. I expect a variable named <code>i</code> to represent an index, for example.</p>\n\n<p>Your algorithm itself is fine, but the naming is very confusing, which is kind of a problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:52:09.663",
"Id": "226641",
"ParentId": "226629",
"Score": "3"
}
},
{
"body": "<h1><code>list</code></h1>\n\n<p>A <code>str</code> is an iterable itself, so calling <code>list</code> on it in <code>w = set(list(w))</code> and <code>for x, i in enumerate(list(s)):</code> is unnecessary.</p>\n\n<h1><code>set</code></h1>\n\n<p>a set only has the unique elements. If the word <code>w</code> contains any double letters, they will be only counted once. A <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>Counter</code></a> is a more appropriate data structure </p>\n\n<h1><code>deque</code></h1>\n\n<p>For the queue, a <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>deque</code></a> (double ended queue) would be a better data structure then a list for additions on one end, and pops on the other. If you define the <code>maxlen</code>, you don't even need to explicitly pop. </p>\n\n<h1>generators</h1>\n\n<p>You can forgo the <code>index</code> list, and instead <code>yield</code> the index at which there is an anagram</p>\n\n<pre><code>def anagram_indices2(w, s):\n len_w = len(w)\n if len_w > len(s):\n return # or raise an Exception\n # raise ValueError(\"`w` must not be at longer than `s`\")\n\n word_counter = Counter(w)\n queue = deque(s[:len_w-1], maxlen=len_w)\n\n for i, char in enumerate(s[len_w-1:]):\n queue.append(char)\n if Counter(queue) == word_counter:\n yield i\n</code></pre>\n\n<p>The <code>s[:len_w-1]</code> is so you don't have to make a separate check for the first round of words</p>\n\n<p>Which gives:</p>\n\n<pre><code> list(anagram_indices2(word, string))\n</code></pre>\n\n<blockquote>\n<pre><code>[0, 3, 4]\n</code></pre>\n</blockquote>\n\n<pre><code> list(anagram_indices2(\"abab\", \"abxbabas\"))\n</code></pre>\n\n<blockquote>\n<pre><code>[3]\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:09:01.223",
"Id": "226683",
"ParentId": "226629",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:00:29.377",
"Id": "226629",
"Score": "7",
"Tags": [
"python",
"strings"
],
"Title": "Pythonic Substring Anagram Index"
}
|
226629
|
<p>I use c++ 11 enum class usually instead of the old enums because many enums can contain the same value
but as known they don't have the bitwise operators out of the box so we should define them manually</p>
<p>in windows it's already done for us with this macro in windows.h header :</p>
<pre><code>DEFINE_ENUM_FLAG_OPERATORS
</code></pre>
<p>but I then encountered another problem</p>
<p>if I use these enum as flags I can put many values in the falg using bitwise operator | , but to test if the flag contains a value I can't check with bitwise operator & like this :</p>
<pre><code>if (flags & value) {...}
</code></pre>
<p>I could however write a template function like this to test :</p>
<pre><code>template <class T>
constexpr bool has_value(T flags, T value)
{
return (std::underlying_type_t<T>)flags & (std::underlying_type_t<T>)value;
}
</code></pre>
<p>but I really would like to use the old format to test for values in the flags
I already found a solution on github which wrapped all chosen emums in a class called flags and it was used like the old ones but with the type safety of enum classes</p>
<p>As I don't want to use templates for this purpose and I want only operator & to give me a bool value in if expressions , I used another class that holds the enum value and can be converted to bool and this is what I wrote</p>
<pre><code>#define OVERLOAD_ENUM_OPERATORS(x) \
class EnumBool##x \
{ \
x enum_value; \
public: \
constexpr EnumBool##x(const x e_val) : enum_value(e_val) {} \
constexpr operator x() const { return enum_value; } \
explicit operator bool() const { return (std::underlying_type_t<x>)enum_value != 0; } \
}; \
inline constexpr EnumBool##x operator&(const x lhs, const x rhs) \
{ \
return EnumBool##x((x)((std::underlying_type_t<x>)lhs & (std::underlying_type_t<x>)rhs)); \
} \
inline constexpr x operator|(const x lhs, const x rhs) \
{ \
return (x)((std::underlying_type_t<x>)lhs | (std::underlying_type_t<x>)rhs); \
} \
inline constexpr x operator^(const x lhs, const x rhs) \
{ \
return (x)((std::underlying_type_t<x>)lhs ^ (std::underlying_type_t<x>)rhs);\
} \
inline constexpr x operator~(const x lhs) \
{ \
return (x)(~(std::underlying_type_t<x>)lhs);\
} \
inline constexpr x& operator|=(x& lhs, const x rhs) \
{ \
lhs = (x)((std::underlying_type_t<x>)lhs | (std::underlying_type_t<x>)rhs); \
return lhs; \
} \
inline constexpr x& operator&=(x& lhs, const x rhs) \
{ \
lhs = (x)((std::underlying_type_t<x>)lhs & (std::underlying_type_t<x>)rhs); \
return lhs; \
} \
inline constexpr x& operator^=(x& lhs, const x rhs) \
{ \
lhs = (x)((std::underlying_type_t<x>)lhs ^ (std::underlying_type_t<x>)rhs); \
return lhs; \
} \
inline constexpr bool operator==(const x lhs, const x rhs) \
{ \
return (std::underlying_type_t<x>)lhs == (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator!=(const x lhs, const x rhs) \
{ \
return (std::underlying_type_t<x>)lhs != (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator>(const x lhs, const x rhs) \
{ \
return (std::underlying_type_t<x>)lhs > (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator<(const x lhs, const x rhs) \
{ \
return (std::underlying_type_t<x>)lhs < (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator>=(const x lhs, const x rhs) \
{ \
return (std::underlying_type_t<x>)lhs >= (std::underlying_type_t<x>)rhs; \
} \
inline constexpr bool operator<=(const x lhs, const x rhs) \
{ \
return (std::underlying_type_t<x>)lhs <= (std::underlying_type_t<x>)rhs; \
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:26:06.727",
"Id": "440537",
"Score": "1",
"body": "Is there a reason, why you don't want use templates?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T12:32:15.087",
"Id": "440977",
"Score": "0",
"body": "Do you know that you can overload operators for enum class, just like the standard does for std::byte?"
}
] |
[
{
"body": "<p>A few things that might be improved:</p>\n\n<ul>\n<li>Use <code>static_cast<type>(value)</code> instead of <code>(type)(value)</code>.</li>\n<li>I'm missing an <code>bool operator!(const x lhs)</code>.</li>\n<li>You could also define <code>operator&&</code> and <code>operator||</code>.</li>\n<li>You can make <code>enum_value</code> const.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:15:19.670",
"Id": "226638",
"ParentId": "226631",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T15:04:47.587",
"Id": "226631",
"Score": "4",
"Tags": [
"c++",
"bitwise",
"enum"
],
"Title": "overload c++ enum class operators and enable check value set"
}
|
226631
|
<p>I created the class <strong>ContinuousDimensionInterval</strong>, to model an interval of a continuous dimension interval, presented below.</p>
<pre><code>namespace Minotaur.Math.Dimensions {
using System;
public sealed class ContinuousDimensionInterval: IDimensionInterval {
public int DimensionIndex { get; }
public readonly DimensionBound Start;
public readonly DimensionBound End;
public ContinuousDimensionInterval(
int dimensionIndex,
DimensionBound start,
DimensionBound end
) {
if (dimensionIndex < 0)
throw new ArgumentOutOfRangeException(nameof(dimensionIndex) + " must be >= 0.");
DimensionIndex = dimensionIndex;
Start = start;
End = end;
}
public bool Contains(float value) {
if (float.IsNaN(value))
throw new ArgumentOutOfRangeException(nameof(value));
if (value > Start.Value && value < End.Value)
return true;
if (Start.IsInclusive && value == Start.Value)
return true;
if (End.IsInclusive && value == End.Value)
return true;
return false;
}
}
}
</code></pre>
<p>I felt the need to create a struct, <strong>DimensionBound</strong>, to represent the bounds of an interval, since they may be inclusive or exclusive.</p>
<pre><code>namespace Minotaur.Math.Dimensions {
using System;
public readonly struct DimensionBound {
public readonly float Value;
public readonly bool IsInclusive;
public DimensionBound(float value, bool isInclusive) {
if (float.IsNaN(value))
throw new ArgumentOutOfRangeException(nameof(value) + " can't be NaN.");
Value = value;
IsInclusive = isInclusive;
}
}
}
</code></pre>
<p>I'd like to receive some feedback on the implementation of both classes.</p>
<ol>
<li>Should I disallow the construction of <code>DimensionBound</code> with
value=infinity and inclusive=true?</li>
<li>Is my decision to make <code>DimensionBound</code> a <code>struct</code> reasonable? It feels struct-like to me...</li>
<li>Should <code>DimensionBound</code> implement <code>IEquatable<DimensionBound></code>?</li>
<li>Am I over-engineering the whole thing by creating a class to represent the bounds of an interval?</li>
</ol>
<p>Here an example of how the class is used:</p>
<pre><code>private static bool IntersectsContinuous(ContinuousDimensionInterval lhs, ContinuousDimensionInterval rhs) {
// @Improve performance?
// @Verify correctness
var aStart= lhs.Start;
var aEnd = lhs.End;
var bStart = rhs.Start;
var bEnd = rhs.End;
if (aStart.Value > bEnd.Value)
return false;
if (aStart.Value == bEnd.Value)
return aStart.IsInclusive && bEnd.IsInclusive;
if (bStart.Value > aEnd.Value)
return false;
if (bStart.Value == aEnd.Value)
return bStart.IsInclusive && aEnd.IsInclusive;
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:40:38.490",
"Id": "440741",
"Score": "1",
"body": "What's the use of `DimensionIndex`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:43:11.387",
"Id": "440806",
"Score": "0",
"body": "It is used to identify a dimension. It could be a string \"DimensionIdentifier\", but in my case a int suffices."
}
] |
[
{
"body": "<p>The <code>ContinuousDimensionInterval</code> constructor should validate that it has valid bounds, i.e. <code>Start</code> <= <code>End</code> (and if they are equal, at least one of them should be inclusive). This is more likely to be a programming or logic error than an attempt to create an empty interval (which may be something you want to more explicitly support by providing a <code>SetEmpty</code> member).</p>\n\n<p><code>DimensionBound</code> should have some sort of comparison operations defined for it. The full <code>IComparable</code> interface, not just <code>IEquatable</code>. This would also make validating the <code>Start</code> and <code>End</code> bounds of <code>ContinuousDimensionInterval</code> easier.</p>\n\n<p>As for your specific questions:</p>\n\n<ol>\n<li>Does it make sense that an interval will be unbounded (either positive or negative infinity)? I don't see a reason to restrict them to finite bounds.</li>\n<li>A <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/structs\" rel=\"noreferrer\"><code>struct</code></a> in C# is a value type, not a reference type, so it will always be copied when being passed around. There are other restrictions as well. Only you can decide if they are acceptable for you. (My personal preference would be to lean towards making it a class.)</li>\n<li>As I mentioned above, you should implement the full <code>IComparable</code> interface for <code>DimensionBound</code>.</li>\n<li>Nope. Small classes that do one thing are the building blocks to larger, more complicated objects.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T22:43:22.470",
"Id": "440573",
"Score": "2",
"body": "I'm not sure making `DimensionBound` implemented `IComparable` would make sense: can you elaborate on how you'd propose it be done? I would only want to implement `IComparable` if there was a natural and meaningful ordering (if you need to order them otherwise, use an `IComparer`), and I'm not convinced there is one here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:46:23.913",
"Id": "440597",
"Score": "1",
"body": "Having `SetEmpty` in a readonly struct sounds strange."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T21:58:24.840",
"Id": "226651",
"ParentId": "226650",
"Score": "5"
}
},
{
"body": "<h2>Review</h2>\n\n<ul>\n<li>You are constrained to <code>float</code> which makes your class only usable for a limited number of scenarios. I would like to be able to work with <code>int</code>, <code>double</code>, <code>DateTime</code>, <code>MyCustomEntity</code>, ..</li>\n<li>You should not need to care about special cases as unbounded or NaN. NaN should be filtered out beforehand, since it is unusable for comparison. Unbounded and bounded values should be compared by using the built-in interface <code>IComparable</code>.</li>\n<li>Intersection of continuous data when 2 edges match requires both edges to be <code>IsInclusive</code> in your specification. I would argue that only one of them should require this flag. Adjacent items that meet each other form an intersection ( [source required] ).</li>\n<li>Your struct is immutable, which is proper design. Whether or not to make a class instead, depends on <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct\" rel=\"nofollow noreferrer\">how you would like to use this</a>. I tend to prefer class more than struct. Note that a struct has an inherent default value, while a reference type is <code>null</code> by default. How would you distinguish a default value from a value that happens to have the same value? This is one reason to go with a class, unless you cope with this issue by using a <code>Nullable<T></code> and accepting the overhead it provides.</li>\n<li>It is good practice to override <code>GetHashCode()</code> and <code>Equals()</code>.</li>\n</ul>\n\n<hr>\n\n<h2>Suggestions</h2>\n\n<p><a href=\"https://codereview.stackexchange.com/a/226651/200620\">1201ProgramAlarm's answer</a> suggests to use <code>IComparable</code> on <code>DimensionBound</code>, but I would use it on the generic type parameter.</p>\n\n<pre><code>public class DimensionBound<T> where T : IComparable<T>\n{\n public readonly T Value;\n public readonly bool IsInclusive;\n\n public DimensionBound(T value, bool isInclusive)\n {\n Value = value;\n IsInclusive = isInclusive;\n }\n}\n</code></pre>\n\n<p>The interval could then be refactored to compare the values. Note that I would provide a convenience constructor accepting an inclusive start and exclusive end (which is considered common practice when dealing with continuous data). </p>\n\n<p>I would also favour instance methods over the static comparison. Furthermore, I would argue the purpose of the dimension in this class. I would remove it and call the class <code>Interval</code>. You can always create an additional class or use a tuple <code>(int, Interval)</code> to include the dimension.</p>\n\n<pre><code>public sealed class Interval<T> where T : IComparable<T>\n{\n public readonly DimensionBound<T> Start;\n public readonly DimensionBound<T> End;\n\n public Interval(T start, T end)\n : this(ew DimensionBound<T>(start, true), new DimensionBound<T>(end, false))\n {\n }\n\n public Interval(DimensionBound<T> start, DimensionBound<T> end)\n {\n Start = start;\n End = end;\n }\n\n public bool Contains(T value)\n {\n // method body ..\n }\n\n public bool Intersects(Interval<T> other)\n {\n // method body ..\n }\n}\n</code></pre>\n\n<p>If we don't change your specification and require both edges to be inclusive when 2 intervals meet, we could implement <code>Intersects</code> (<code>Contains</code> is similar) as follows (comments added for code review purposes only):</p>\n\n<pre><code>public bool Intersects(Interval<T> other)\n{\n // compare start to other end\n var compareToStart = Start.Value.CompareTo(other.End.Value);\n\n // no intersection possible; instance starts after other is finished\n if (compareToStart == 1) return false;\n\n // both intervals meet but at least one of the bounds is exclusive, so no intersection\n if (compareToStart == 0 && !(Start.IsInclusive && other.End.IsInclusive)) return false;\n\n // compare end to other start\n var compareToEnd = End.Value.CompareTo(other.Start.Value);\n\n // no intersection possible; instance finishes before other is started\n if (compareToEnd == -1) return false;\n\n // both intervals meet but at least one of the bounds is exclusive, so no intersection\n if (compareToEnd == 0 && !(End.IsInclusive && other.Start.IsInclusive)) return false;\n\n return true;\n}\n</code></pre>\n\n<p>This works with <code>float</code>, or any other <code>IComparable<T></code>.</p>\n\n<pre><code>Assert.IsTrue(new Interval<float>(0, 1).Intersects(new Interval<float>(0.5f, 1.5f));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:40:42.513",
"Id": "440593",
"Score": "1",
"body": "oh, you actually get the question..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:43:02.017",
"Id": "440595",
"Score": "1",
"body": "@t3chb0t Interval logic is fun: https://en.wikipedia.org/wiki/Allen%27s_interval_algebra. Or with 3 intervals: https://www.ics.uci.edu/~alspaugh/cls/shr/allen.html."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:47:16.170",
"Id": "440599",
"Score": "3",
"body": "CR is more demanding than school... I'm not done studying your last question about sudoku yet and here's the next topic already... this is cool ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:21:17.727",
"Id": "440615",
"Score": "0",
"body": "I'm not convinced by bullet 3: maybe I don't know the pure maths underneath, but unless there exists a value that both intervals contain, I don't think that would be considered an intersection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:27:00.533",
"Id": "440618",
"Score": "0",
"body": "I'm also less than sure about comparing `DimensionBound<T>` to `T`: it's not clear what it gives you, and it's not clear how you'd compare `1` to `(1, inclusive/exclusive)`: if both are 0, then 'equality' is intransitive, and otherwise you have to 'kill' one of them. Can you provide a spec for this: maybe you have a good idea I can't come up with. (sorry for all the edits; misread your answer at first)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:34:24.990",
"Id": "440619",
"Score": "0",
"body": "@VisualMelon to answer your first edit: in a continuous set, each T is an instantaneous value. When 2 intervals are adjacent with a difference of epsilon (if at least one is included), they are considered to meet (hence, intersect). When working with discrete values, I would agree there would be no intersection in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:36:59.257",
"Id": "440620",
"Score": "0",
"body": "@VisualMelon to answer your second question: I'm not comparing DimensionBound<T> to T, I'm comparing the former's value (of type T) to T. The IsInclusive flag means that the value itself is either included or not. If not, depending on the context (start or end) the actual value is T+epsilon vs T-epsilon. I hope my explanation makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:41:34.640",
"Id": "440621",
"Score": "0",
"body": "@VisualMelon We could argue whether 2 intervals that meet (diff = epsilon) should be considered an intersection or not. Perhaps a specification should make this clear. It might be for me, but not for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:49:38.287",
"Id": "440622",
"Score": "0",
"body": "Thanks for the swift responses. Re first: could you provide a reference for that? I'm struggling to find a sensible definition of intersection that isn't from set theory, and the only intersection I've ever known is defined in terms of membership. Looking at epsilons, consider the case of two exclusive bounds: we can still make the gap arbitrarily small, but I don't think anyone would argue they meet or intersect. Re second: I think I know what you mean, but I think having `a.Compare(x) == 0 && b.Compare(x) == 0` when `a.Equals(b) == false` is asking for trouble...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:50:42.740",
"Id": "440623",
"Score": "1",
"body": "... I'm also not convinced it would be of any real use: I think it would be better to leave deciding how to compare these things to whoever is using them, because they will (hopefully) have a meaningful interpretation. (argh, chat button went away; I'm happy to move if you are)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:57:04.440",
"Id": "440624",
"Score": "0",
"body": "@VisualMelon (1) In interval logic (https://en.wikipedia.org/wiki/Allen%27s_interval_algebra), there is the concept of meets and that of overlaps. Intersection is not defined (as far I know). This means we either have to resort to set theory or come up with a spec ourselves. I have no issue to resort to set theory. On the other hand, perhaps we should have functions _Overlaps_ rather than _Intersects_ to avoid ambiguity. (2) valid point, but since the whole point of the OP is work with continuous data, I see the combination (IsIncluded, Value) as a value, not just Value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:57:43.757",
"Id": "440625",
"Score": "0",
"body": "_I think it would be better to leave deciding how to compare these things to whoever is using them_ I totally agree this is a context-bound problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T08:01:26.110",
"Id": "440626",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/97760/discussion-between-dfhwze-and-visualmelon)."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:35:39.633",
"Id": "226665",
"ParentId": "226650",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T21:08:55.640",
"Id": "226650",
"Score": "7",
"Tags": [
"c#",
"interval"
],
"Title": "Modeling and computing intersection between continuous intervals"
}
|
226650
|
<p>My code:</p>
<pre><code>import re
mbox = open('mailbox.txt')
ndict = {}
for line in mbox:
domain = re.findall('From [^ ].*@([^ ]*)', line)
if domain:
if domain[0] in ndict:
ndict[domain[0]] += 1
else:
ndict[domain[0]] = 1
print_list = [print(i) for i in sorted([(i, ndict[i]) for i in
list(ndict.keys())], key=lambda x: x[1], reverse=True)]
</code></pre>
<p>I don't like how I create a dictionary and then immediately convert it into a list (which I'm doing in order to sort it), as it seems un-Pythonic to me. Is there a more Pythonic way to do this without using dictionaries? </p>
<p>i.e. Can you do this by making a list and appending tuples of the domains and number of occurrences? </p>
|
[] |
[
{
"body": "<ol>\n<li><p>I suggest you get a linter such as Prospector or flake8, this can tell if your code is un-Pythonic. Some people prefer hinters like black.</p>\n\n<p>Your code doesn't conform to PEP 8 which is <em>the standard</em> when it comes to Python. Your comprehension is hard to read because it doesn't conform to best practices.</p></li>\n<li><p>I'd recommend moving your code into a <code>main</code> function and use an <code>if __name__ == '__main__':</code> guard. This reduces global pollution and prevents your code from running accidentally.</p></li>\n<li><p>When you see something like:</p>\n\n<pre><code>if key in my_dict:\n my_dict[key] += value\nelse:\n my_dict[key] = default + value\n</code></pre>\n\n<p>Then you should probably use <code>dict.get</code> which can get the following code:</p>\n\n<pre><code>my_dict[key] = my_dict.get(key, default) + value\n</code></pre>\n\n<p>In this case you can add more sugar by using <code>collections.defaultdict</code>, as it will default missing keys to 0.</p>\n\n<pre><code>import collections\n\nmy_dict = collections.defaultdict(int)\nmy_dict[key] += 1\n</code></pre></li>\n<li><p>Don't use comprehensions with side effects, they're hard to understand and are better expressed as standard <code>for</code> loops. This is as the list you're making is absolutely pointless.</p></li>\n<li>You can use <code>dict.items()</code> rather than your comprehension with <code>dict.keys()</code>.</li>\n</ol>\n\n<pre><code>import re\nimport collections\n\n\ndef main():\n with open('mailbox.txt') as mbox:\n ndict = collections.defaultdict(int)\n for line in mbox:\n domain = re.findall('From [^ ].*@([^ ]*)', line)\n if domain:\n ndict[domain[0]] += 1\n\n for item in sorted(ndict.items(), key=lambda x: x[1], reverse=True):\n print(item)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>You can replace the majority of your code with <code>collections.Counter</code>.</p>\n\n<pre><code>import re\nimport collections\n\n\ndef main():\n with open('mailbox.txt') as mbox:\n counts = collections.Counter(\n domain[0]\n for domain in re.findall('From [^ ].*@([^ ]*)', line)\n if domain\n )\n for item in counts.most_common():\n print(item)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T00:25:39.930",
"Id": "440582",
"Score": "0",
"body": "Thank you for the answer, and for telling me about PEP 8 (I didn't even know about it before lol; apologies!) and all these new methods and libraries! `dict.get` I feel would be an especially useful one for me. However, I have to ask why you would use `dict.items` over `dict.keys` in that instance. Also I think you might have made a mistake in your last code block, you wrote count instead of counts when iterating. Thank you for your time btw!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T00:29:06.137",
"Id": "440583",
"Score": "1",
"body": "@rivershen No problem, we all have to start somewhere :) I'm unsure what you mean by your `dict.items` question, but I'll give it a stab anyway. Since `[(i, ndict[i]) for i in ndict.keys()]` is pretty much the same as `ndict.items()` then there are no benefits to using the former - it's longer to type and to read. Yes I did make a mistake, I have fixed that now thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T00:14:45.357",
"Id": "226656",
"ParentId": "226654",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226656",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T23:26:18.323",
"Id": "226654",
"Score": "4",
"Tags": [
"python",
"sorting",
"regex",
"email"
],
"Title": "Sorting email address according to occurrences of each domain"
}
|
226654
|
<p>I wrote some code to return how many prime numbers are in a specific range and what they are. It also tells you whether the number of primes is also a prime!</p>
<p>I feel like this seems like a fairly long winded approach for something that's probably very simple, can someone please tell me how I can improve this?</p>
<pre><code>def prime_number():
primes = []
primes_2 = []
low = int(input("What number would you like to start at? "))
high = int(input("What number would you like to go up to? "))
if int(low) == 1 and int(high) == 1:
print("1 isn't a prime number dumb dumb")
elif high < 2:
print("Don't be annoying")
else:
for x in range(int(low), int(high)):
for i in range(2, x):
if (x % i) == 0 and x != i:
break
elif (x % i) == 1 and i <= (x - 2):
continue
elif (x % i) == 1 and i == (x - 1):
primes.append(x)
x = x + 1
print("The number of prime numbers is: ", len(primes))
for y in range(2, int(low)):
for z in range(2, y):
if (y % z) == 0 and y != z:
break
elif (y % z) == 1 and z <= (y - 2):
continue
elif (y % z) == 1 and z == (y - 1):
primes_2.append(y)
y = y + 1
if int(len(primes)) in primes or int(len(primes)) in primes_2:
print("Huh, fancy that!", len(primes), "is also also a prime number!")
print("The prime numbers are: ",primes)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T00:38:58.033",
"Id": "440584",
"Score": "6",
"body": "It's a shame this has been down voted, I don't see anything particularly wrong with it. I have edited it so that it reads better, best of luck :)"
}
] |
[
{
"body": "<p>Welcome to Code Review! Here are some suggestions.</p>\n\n<h2>Naming</h2>\n\n<p>Choose a better name than <code>primes_2</code>. I'm not clear on what this variable does.</p>\n\n<h2>Write some documentation</h2>\n\n<p>...in triple quotes at the top of your function. Describe its inputs and outputs.</p>\n\n<h2>Separate user input from processing</h2>\n\n<p>Put your calculation code in a separate function from your user input and output code.</p>\n\n<h2>Validation</h2>\n\n<p>If the user enters invalid input, consider looping until the input they provide is valid. Or, at least - return out of the function if it's invalid, instead of having a large <code>else</code> covering the rest of your code.</p>\n\n<h2>Increment-and-assign</h2>\n\n<p>Use <code>x += 1</code> instead of <code>x = x + 1</code>.</p>\n\n<h2>Formatted output</h2>\n\n<p>Consider using this form instead:</p>\n\n<pre><code>print(f'Huh, fancy that! {len(primes)} is also a prime number!')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T01:32:52.070",
"Id": "226659",
"ParentId": "226655",
"Score": "3"
}
},
{
"body": "<h1>You have a problem with indentation in this line:</h1>\n\n<pre><code>elif (x % i) == 1 and i == (x - 1):\nprimes.append(x)\n</code></pre>\n\n<h1>f-strings:</h1>\n\n<pre><code>if int(len(primes)) in primes or int(len(primes)) in primes_2:\n print(\"Huh, fancy that!\", len(primes), \"is also also a prime number!\")\n print(\"The prime numbers are: \",primes)\n</code></pre>\n\n<p>you might want to replace this with f'strings that looks like this:</p>\n\n<pre><code>if int(len(primes)) in primes or int(len(primes)) in primes_2:\n print(f'Huh, fancy that! {len(primes)} is also a prime number!')\n print(f'The prime numbers are:\\n{primes}')\n</code></pre>\n\n<h1>Prime sieve</h1>\n\n<p>A much more efficient way of calculating prime numbers within a given range is using the sieve of Eratosthenes: <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes</a></p>\n\n<h1>Bug:</h1>\n\n<p>your code does not include 2 as a prime number, it returns the following for range(0, 100):\n[3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]</p>\n\n<h1>For comparison purposes: (I included a part of your prime implementation in a new function)</h1>\n\n<pre><code>def prime_slow(low, high):\n \"\"\"Return a list of primes.\"\"\"\n primes = []\n for x in range(int(low), int(high)):\n for i in range(2, x):\n if (x % i) == 0 and x != i:\n break\n elif (x % i) == 1 and i <= (x - 2):\n continue\n elif (x % i) == 1 and i == (x - 1):\n primes.append(x)\n x = x + 1\n return primes\n\n\nif __name__ == '__main__':\n test_number = 10 ** 4\n start_time1 = perf_counter()\n prime_slow(0, test_number)\n end_time1 = perf_counter()\n print(f'Time to calculate primes (slow method): {end_time1 - start_time1} seconds.')\n start_time2 = perf_counter()\n list(prime_sieve(test_number))\n end_time2 = perf_counter()\n print(f'Time to calculate primes (using a sieve): {end_time2 - start_time2} seconds.')\n</code></pre>\n\n<ul>\n<li>Time to calculate primes (slow method): 3.067288957 seconds.</li>\n<li>Time to calculate primes (using a sieve): 0.0016803199999997354\nseconds.</li>\n</ul>\n\n<h1>The whole code might look like:</h1>\n\n<pre><code>def prime_sieve(upper_bound):\n \"\"\"Generate primes up to upper_bound.\"\"\"\n primes = [True] * upper_bound\n primes[0] = primes[1] = False\n\n for index, prime in enumerate(primes):\n if prime:\n yield index\n for number in range(index * index, upper_bound, index):\n primes[number] = False\n\n\ndef prime_number():\n \"\"\"Display number of primes within user specified range.\"\"\"\n try:\n lower_bound = int(input('Enter starting number: '))\n upper_bound = int(input('Enter ending number: '))\n primes = prime_sieve(upper_bound)\n valid_primes = [prime for prime in primes if prime >= lower_bound]\n print(f'The number of prime numbers is: {len(valid_primes)}'\n f' prime numbers in range {lower_bound} to {upper_bound}')\n except ValueError:\n print(f'Invalid number!')\n print('Failed to calculate primes.')\n\n\nif __name__ == '__main__':\n prime_number()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T11:00:57.940",
"Id": "443248",
"Score": "1",
"body": "In the function `prime_number`, [`list(itertools.dropwhile(p: p < lower_bound, primes))`](https://docs.python.org/3/library/itertools.html#itertools.dropwhile) might be faster in some cases (e.g. where the lower bound is small), because it stops comparing elements as soon as the condition is true and yields all elements afterwards."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T01:52:18.747",
"Id": "226660",
"ParentId": "226655",
"Score": "3"
}
},
{
"body": "<p>Since you compute the primes between <code>low</code> and <code>high</code> to get the number of primes</p>\n<p><strong>and</strong></p>\n<p>you compute the primes between zero and <code>low</code> to check if your <code>len(primes)</code> is prime, why not compute primes from zero to <code>high</code> in one shot? This also has the big advantage of increasing the speed of your computing speed (yes, you read that right).</p>\n<p>Right now, to see if a number <code>n</code> is prime, you check if you can divide <code>n</code> by all the numbers "behind" it. So, for example :</p>\n<blockquote>\n<p>Is 5 a prime?</p>\n<p>Let's try to divide by 4,3,2,1</p>\n<p>We can't, so 5 is prime.</p>\n</blockquote>\n<p>It's alright when you check for 5, it's a very small number. How about 103? It's still pretty fast, how about 23321? It gets slower.</p>\n<p>Is there a faster way we could check if a number is prime? If, for <code>n</code>, I already have all primes <code>p</code> smaller than <code>n</code>, we can verify primness using <a href=\"https://www.mathsisfun.com/prime-factorization.html\" rel=\"nofollow noreferrer\">Prime Factorization</a> an <a href=\"https://www.geeksforgeeks.org/dynamic-programming/\" rel=\"nofollow noreferrer\">Dynamic Programming</a>.</p>\n<p>Here are non-formal definition of the two concepts above, if you don't want to click the links</p>\n<p><strong>Prime factorization :</strong> Any integer can be rewritten as a multiplication of prime numbers to a power <code>p</code>.</p>\n<p>Examples :</p>\n<p><span class=\"math-container\">$$4 = 2^2$$</span>\n<span class=\"math-container\">$$288 = 2^5 * 3^2$$</span>\n<span class=\"math-container\">$$45 = 3^2 * 5$$</span></p>\n<p>I hope you get it.</p>\n<p><strong>Dynamic Programming :</strong> To fix a big problem, use a composition of smaller problem you already solved.</p>\n<p>Want to see if 15 is prime (we know it's not)? But you already know all the prime numbers below, let's use that!</p>\n<blockquote>\n<p>Primes under 15 : <code>2, 3, 5, 7, 11, 13</code></p>\n</blockquote>\n<p>Using the definition of prime factorization, I can check if 15 is prime by dividing it only by the numbers above. This means instead of trying 14 divisions, we can do 6! Now, that ain't a big win, but is 23321 a prime? Instead of doing 23320 divisions, we can do only 2599 (because 23321 is the 2600th prime number). Now that's faster!</p>\n<hr />\n<p>Doing this <code>x = x + 1</code> in your loop is useless.</p>\n<p>for x in range(int(low), int(high)):</p>\n<pre><code># The rest of the code\n\nx = x + 1\n</code></pre>\n<p>You add 1 to <code>x</code>, but it's overwritten straight after because of the <code>for</code> loop.</p>\n<hr />\n<p>When you check for <code>len(primes) is prime</code>, you should realize that your code is fully duplicated from the code above. In such cases, you probably want to extract a function from your code like, <code>is_prime</code> to reduce the duplication. But, moreover, you don't want to find <em>all</em> when checking if a number is prime. What I mean is that you can stop your search once your number can be divided by any number below it.</p>\n<hr />\n<p>Now for good practices, your method <code>prime_numbers</code> should take arguments named <code>low</code> and <code>high</code>, and do the input asking outside the function. What I mean is that using <code>print</code> in a method that doesn't have the responsibility to <code>print</code> stuff (See <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>). Now, disclaimer, SRP catches lot of heat from some developers because it is easy to get over zealous with it. You need to be cautious not to separate <strong>everything</strong> in different functions/classes/etc. The idea is that you want your method to do what they're supposed to do ( = what their name is) and nothing else, because it's confusing for developers reading your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:08:20.510",
"Id": "226684",
"ParentId": "226655",
"Score": "3"
}
},
{
"body": "<p>I won't repeat the excellent comments made by the other answers on Prime Factorization, Dynamic Programming, Single Responsibility Principle, Indentation, f-Strings, Bugs, Naming, Documentation, and Separation of Input from Processing.</p>\n\n<h2>Integer conversion</h2>\n\n<p>After all those comments have been filtered out, the following programming style still jumps out and needs to be addressed:</p>\n\n<pre><code>low = int(input(\"What number would you like to start at? \"))\nhigh = int(input(\"What number would you like to go up to? \"))\nif int(low) == 1 and int(high) == 1:\n#...\n for x in range(int(low), int(high)):\n # ...\n for y in range(2, int(low)):\n # ...\n</code></pre>\n\n<p>What is up with all the calls to <code>int(...)</code>?</p>\n\n<p>Both <code>low</code> and <code>high</code> have been converted to integers in the first two statements (or an exception has been raised if they can't be). You don't need <code>int(low)</code> and <code>int(high)</code>; that is just being redundant and obfuscating.</p>\n\n<p>Similarly:</p>\n\n<pre><code> if int(len(primes)) in primes or int(len(primes)) in primes_2:\n</code></pre>\n\n<p>The length of a <code>list</code> is always an integer, so again the wrapping <code>len(...)</code> in <code>int(...)</code> calls does not add anything but clutter to the program.</p>\n\n<h2>Precedence</h2>\n\n<p>You've got more parenthesis than you need:</p>\n\n<pre><code> elif (x % i) == 1 and i <= (x - 2):\n</code></pre>\n\n<p>Both the modulo-operation (<code>%</code>) and the subtraction-operation (<code>-</code>) are higher precedence than the comparison operators (<code>==</code> and <code><=</code>), so the parenthesis may be safely omitted:</p>\n\n<pre><code> elif x % i == 1 and i <= x - 2:\n</code></pre>\n\n<h2>Limits & Looping</h2>\n\n<pre><code> for i in range(2, x):\n if (x % i) == 0 and x != i:\n</code></pre>\n\n<p>The <code>range(2, x)</code> object includes the starting point (<code>2</code>), but excludes the ending point (<code>x</code>). As such, <code>i</code> will never reach <code>x</code>, so the expression <code>x != i</code> will always be true, and may be omitted from the first <code>if</code> statement.</p>\n\n<p>When <code>i == x - 1</code>, then <code>x % i == 1</code> will always be true, so</p>\n\n<pre><code>elif (x % i) == 1 and i == (x - 1):\n</code></pre>\n\n<p>could simply be written as:</p>\n\n<pre><code>elif i == x - 1:\n</code></pre>\n\n<p>Except, what this really means is that the <code>for i in range(2, x)</code> has reached the end of the range without ever executing the <code>break</code> statement. For this you could use a <code>for ... else</code> loop.</p>\n\n<pre><code> for i in range(2, x):\n if x % i == 0:\n break\n else:\n primes.append(x)\n</code></pre>\n\n<p>Finally, we can further simply this by realizing we are asking if <strong><code>any</code></strong> value in the range from <code>2</code> (inclusive) to <code>x</code> (exclusive) divides evenly into <code>x</code> ... and Python has an <code>any()</code> function. If any value in that range does, then <code>x</code> is not prime:</p>\n\n<pre><code>if not any(x % i == 0 for i in range(2, x)):\n primes.append(x)\n</code></pre>\n\n<p>If you were generating <strong>all</strong> of the primes, starting from 2 instead of starting from <code>low</code>, you could optimize this search by just testing for prime divisors:</p>\n\n<pre><code>if not any(x % i == 0 for i in primes):\n primes.append(x)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T22:56:07.640",
"Id": "226720",
"ParentId": "226655",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T23:38:34.560",
"Id": "226655",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"primes"
],
"Title": "Calculate the number of primes in a range"
}
|
226655
|
<p>I have made a website where people write about their day and see it analyzed. In particular, the website takes event titles and groups them together if they have any common words (after stemming the event titles). It also finds miscellaneous features that I feel would be important for machine learning later. The python file that is most important is <code>views.py</code>. The class that is most important is <code>EventAnalysis</code>, and its most important methods are <code>string_clean</code> and <code>feature_engineering</code>. I've included <code>models.py</code> for one to make sense of <code>views.py</code>. For more information (and for running the complete project), <a href="https://github.com/boworkgo/Past-patterns" rel="nofollow noreferrer">here is the GitHub link</a>.</p>
<p>views.py</p>
<pre><code>import random
import re
import sqlite3
from collections import defaultdict
from datetime import datetime
from functools import reduce
import matplotlib.pyplot as plt
import numpy as np
from django import forms
from django.forms import Textarea
from django.shortcuts import get_object_or_404, render
from django.urls import reverse, reverse_lazy
from django.views import generic
import pandas as pd
from chartjs.views.lines import BaseLineChartView
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from pandas.io import sql
from .models import Event
class IndexView(generic.ListView):
template_name = "posts/index.html"
context_object_name = "latest_posts"
def get_queryset(self):
return Event.objects.all()[:10]
class HistoryView(generic.DetailView):
model = Event
template_name = "posts/history.html"
context_object_name = "post"
class CreateView(generic.edit.CreateView):
model = Event
fields = ["title", "text"]
exclude = ["pub_date"]
widgets = {"text": Textarea(attrs={"cols": 100, "rows": 15})}
template_name = "posts/create.html"
def get_success_url(self):
return reverse("posts:index")
class Graph:
def __init__(self, n):
self.number_edges = n
self.visited = [False] * n
self.adj = defaultdict(list)
self.connections = []
def add_edge(self, n1, n2):
self.adj[n1].append(n2)
self.adj[n2].append(n1)
def dfs(self):
for i in range(self.number_edges):
if not self.visited[i]:
self.connections.append([])
self.traverse_adj(i)
def traverse_adj(self, i):
self.connections[len(self.connections) - 1].append(i)
self.visited[i] = True
for j in self.adj[i]:
if not self.visited[j]:
self.traverse_adj(j)
class EventAnalysis:
def __init__(self):
conn = sqlite3.connect("db.sqlite3")
self.data = sql.read_sql("SELECT * FROM posts_event;", con=conn)
conn.close()
self.clean_data()
self.feature_engineering()
def string_clean(self, s):
s = re.sub("[^a-zA-Z ]+", "", s).lower()
s = re.sub(" +", " ", s).strip().split(" ")
stop_words = set(stopwords.words("english"))
s = [w for w in s if not w in stop_words]
ps = PorterStemmer()
s = list(set([ps.stem(w) for w in s]))
return s
def clean_data(self):
self.data["cleansed_title"] = self.data["title"].map(self.string_clean)
self.data["cleansed_text"] = self.data["text"].map(self.string_clean)
def calculate_hours(self, time1, time2):
def difference(idx1, idx2):
return int(time2[idx1:idx2]) - int(time1[idx1:idx2])
year = difference(0, 4)
month = difference(5, 7)
day = difference(8, 10)
hour = difference(11, 13)
minute = difference(14, 16)
return year * 365 * 24 + month * 30 * 24 + day * 24 + hour + minute / 60
def feature_engineering(self):
time_spent, day_id = [1], []
anchor_day, day_i = self.data["pub_date"][0][:10], 1
for i in range(self.data.shape[0]):
if i != 0:
time_spent.append(
self.calculate_hours(
self.data["pub_date"][i - 1], self.data["pub_date"][i]
)
)
if self.data["pub_date"][i][:10] != anchor_day:
day_i += 1
anchor_day = self.data["pub_date"][i][:10]
day_id.append(day_i)
self.last_day_id = day_i
self.data["time_spent"] = time_spent
self.data["day_id"] = day_id
self.data["is_important"] = self.data["title"].map(lambda x: x != "*")
connected_components = Graph(len(self.data["id"]))
added_edges = set()
for i, title in enumerate(self.data["cleansed_title"]):
for j, other in enumerate(self.data["cleansed_title"]):
if (
i != j
and set(title) & set(other)
and frozenset({i, j}) not in added_edges
):
connected_components.add_edge(i, j)
added_edges.add(frozenset({i, j}))
connected_components.dfs()
group_number = 1
id_group = dict()
for group in connected_components.connections:
for n in group:
id_group[n] = group_number
group_number += 1
self.last_group_number = group_number
self.data["group_id"] = [id_group[i] for i in range(self.data.shape[0])]
self.data["pub_date_datetime"] = pd.to_datetime(
self.data["pub_date"], format="%Y-%m-%d %H:%M:%S", errors="coerce"
)
time = pd.DataFrame(self.data[["pub_date_datetime", "time_spent"]])
time = time.set_index(["pub_date_datetime"])
time = time.resample("D").mean()
self.time_df = time
def past_day_pie(self):
past_day = self.data[self.data.day_id == self.last_day_id]
total = sum(past_day["time_spent"])
percentages = past_day["time_spent"].map(lambda x: x / total)
return list(percentages), list(past_day["title"])
def grouping_pie(self):
group_hours, group_words = [], []
for i in range(1, self.last_group_number):
group = self.data[self.data.group_id == i]
group_hours.append(sum(group["time_spent"]))
words = reduce(lambda a, b: set(a) | set(b), group["cleansed_title"], [])
group_words.append(
"\n".join(
[
w
for w in set(
random.sample(words, 4 if 4 <= len(words) else len(words))
)
]
)
)
return group_hours, group_words
def time_plot(self):
return (list(self.time_df["time_spent"]), self.time_df.index.tolist())
def analytics(request):
if len(Event.objects.all()) > 0:
print(e.data)
return render(
request, "posts/analytics.html", context={"events": Event.objects.all()}
)
class DeleteView(generic.DeleteView):
model = Event
def get_success_url(self):
return reverse("posts:index")
class ChartJSONView(BaseLineChartView):
def __init__(self, method):
self.stats, self.labels = method
def get_labels(self):
return self.labels
def get_data(self):
return [self.stats]
def get_context_data(self):
return {"labels": self.get_labels(), "datasets": self.get_datasets()}
e = EventAnalysis()
class GroupingPieChartJSONView(ChartJSONView):
def __init__(self):
super().__init__(e.grouping_pie())
class PastDayPieChartJSONView(ChartJSONView):
def __init__(self):
super().__init__(e.past_day_pie())
class AverageHoursJSONView(ChartJSONView):
def __init__(self):
super().__init__(e.time_plot())
</code></pre>
<p>models.py</p>
<pre><code>from django.db import models
class Event(models.Model):
title = models.CharField(max_length=100)
pub_date = models.DateTimeField(auto_now_add=True)
text = models.TextField()
def __str__(self):
return self.title
class Meta:
ordering = ["-pub_date"]
def was_important(self):
return self.title != "*"
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T02:15:28.133",
"Id": "226662",
"Score": "3",
"Tags": [
"python",
"graph",
"django",
"data-visualization",
"natural-language-processing"
],
"Title": "Django project for events of the day, grouped by keywords in common"
}
|
226662
|
<p><a href="https://leetcode.com/problems/group-anagrams/" rel="noreferrer">LeetCode: Group Anagrams C#</a><br>
Given an array of strings, group anagrams together.</p>
<pre><code>Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
</code></pre>
<p>Note:</p>
<p>All inputs will be in lowercase.
The order of your output does not matter.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StringQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/778/
/// </summary>
[TestClass]
public class GroupAnagramsTest
{
[TestMethod]
public void TestMethod1()
{
string[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
var result = GroupAnagramsClass.GroupAnagrams(strs);
List<IList<string>> expected = new List<IList<string>>();
expected.Add( new List<string> {"eat", "tea", "ate"});
expected.Add( new List<string> {"tan", "nat"});
expected.Add( new List<string> {"bat"});
for (int i = 0; i < result.Count; i++)
{
CollectionAssert.AreEqual(expected[i].ToList(), result[i].ToList());
}
}
}
public class GroupAnagramsClass
{
public static IList<IList<string>> GroupAnagrams(string[] strs)
{
Dictionary<char[], List<string>> dict = new Dictionary<char[], List<string>>(new CharComparer());
foreach (var str in strs)
{
var key = str.ToCharArray();
Array.Sort(key);
if (!dict.TryGetValue(key, out var temp))
{
temp = dict[key] = new List<string>();
}
temp.Add(str);
}
List<IList<string>> res = new List<IList<string>>(dict.Values.ToList());
return res;
}
}
public class CharComparer : IEqualityComparer<char[]>
{
public bool Equals(char[] x, char[] y)
{
if (x == null || y == null)
{
return false;
}
if (x.Length != y.Length)
{
return false;
}
for (int i = 0; i < x.Length; i++)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public int GetHashCode(char[] obj)
{
return 0;
}
}
}
</code></pre>
<p>Please review for performance. <br>I don't like me copying the dictionary into <code>IList<IList<string></code>. Is there a better way to do so, considering this the desired API defined by the question?</p>
|
[] |
[
{
"body": "<h1>Deriving from <code>IEqualityComparer</code> versus <code>EqualityComparer</code>.</h1>\n\n<p>The MSDN docs say the following:</p>\n\n<blockquote>\n <p>We recommend that you derive from the EqualityComparer class instead of implementing the IEqualityComparer interface, because the EqualityComparer class tests for equality using the IEquatable.Equals method instead of the Object.Equals method. This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary class and other generic collections.<br>\n <sub><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.iequalitycomparer-1?view=netframework-4.8\" rel=\"noreferrer\">MSDN docs: IEqualityComparer</a></sub></p>\n</blockquote>\n\n<h1><code>Dictionary</code> versus <code>Lookup</code></h1>\n\n<p>For grouping together objects from a sequence, where there might be a varying amount of items in each group, a <code>Lookup</code> is better than a <code>Dictionary</code>:</p>\n\n<pre><code> var lookup = strs.ToLookup(key =>\n {\n var array = key.ToCharArray();\n Array.Sort(array);\n return array;\n }, new CharComparer());\n return lookup.Select(grouping => (IList<string>)grouping.ToList()).ToList();\n</code></pre>\n\n<h1>Comparing char-arrays</h1>\n\n<p>Since we're using <code>Linq</code>, let's use <code>Linq</code>:</p>\n\n<pre><code>public override bool Equals(char[] x, char[] y)\n{\n if (x == null || y == null)\n {\n return false;\n }\n\n if (x.Length != y.Length)\n {\n return false;\n }\n\n return x.SequenceEqual(y);\n}\n</code></pre>\n\n<p>The null behaviour is different and the length shortcut may stay, but the last loop we can offload to <code>Linq</code>.</p>\n\n<h1>Hashcode</h1>\n\n<p>Both <code>Dictionary</code> and <code>Lookup</code> rely on the hashcode returned by the equalitycomparer to categorise the keys into bins. These bins is what allows these collections to get times in <span class=\"math-container\">\\$O(1)\\$</span>. Always returning the same value is going to cause problems when your inputs get bigger. It will effectively turn the collections into single arrays which have to be looped over to get to the correct key. </p>\n\n<p>Creating good hashcodes is hard though, and I don't really know a good rule of thumb for creating them.</p>\n\n<h1><code>char[]</code> versus <code>string</code></h1>\n\n<p>All in all, the hashcode and equalitycomparer is such a headache, it's probably easier, and more readable to convert the sorted <code>char[]</code> back into a <code>string</code>, and use that as the key for the lookup:</p>\n\n<pre><code> var lookup = strs.ToLookup(key =>\n {\n var array = key.ToCharArray();\n Array.Sort(array);\n return new string(array);\n });\n return lookup.Select(grouping => (IList<string>)grouping.ToList()).ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:24:29.310",
"Id": "440639",
"Score": "1",
"body": "Could you provide an interpretation of the comment from the MSDN? I can't understand it (having read the whole article and looked at the implementation); maybe you can enlighten me ;) (ah, no, I think I've got it: they mean `EqualityComparer<T>` implements `IEqualityComparer` for you... but that's not what the text says at all)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:34:32.033",
"Id": "440642",
"Score": "1",
"body": "@VisualMelon I must say, I am a bit puzzled too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:58:00.553",
"Id": "440645",
"Score": "1",
"body": "@VisualMelon The only advantage I see is that it performs some boilerplate null checks for us in _Equals(object x, object y)_ We only need to implement _Equals(T x, T y)_: https://referencesource.microsoft.com/#mscorlib/system/collections/generic/equalitycomparer.cs. In addition, it also implements the non generic interface _IEqualityComparer_ making it possible to use your comparer in contra-variant situations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:01:41.223",
"Id": "440647",
"Score": "1",
"body": "A good rule of thumb for creating hashcodes is to use a co-prime pair and perform bit shifts and exclusive or's with them on immutable key data of your instance. It should also be very fast, 2 instances that are equal must have the same hashcode, and 2 instances with different hashcode cannot be equal. 2 instances that are not equal may or may not have the same hashcode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:04:44.657",
"Id": "440649",
"Score": "0",
"body": "@dfhwze \"immutable\" That's actually kinda tricky with these char-arrays. They are not explicitly immutable. They would be in this context (after sorting them), but in that case we should make the comparer private and nest it within the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:05:13.123",
"Id": "440650",
"Score": "1",
"body": "Also: https://stackoverflow.com/questions/5707347/preferring-equalitycomparert-to-iequalitycomparert"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:08:33.877",
"Id": "440651",
"Score": "1",
"body": "@JAD once the hashcode is used as a bucket in some hash set, the state should be immutable (at least the key state that determines the hashcode and therefore also equality)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:36:34.080",
"Id": "440655",
"Score": "3",
"body": "Honestly, a lot of this bother can be avoided by converting the sorted `char[]` back into a string and using its equality and hashcode logic."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:18:30.487",
"Id": "226675",
"ParentId": "226671",
"Score": "7"
}
},
{
"body": "<p>I've reviewed another one of your question and there's a recurrent point I think needs to be addressed. Your usage of <code>IList</code>.</p>\n\n<p>When you return something, you expect the user of your method to use it in a certain scope. Say I need a method to return all numbers between a certain range.</p>\n\n<pre><code>public IList<int> Range(int low, int high)\n{\n // My C# is rusty, but if I remember correctly this works.\n return Enumerable.Range(low,high).ToList();\n}\n\npublic void FooBar()\n{\n var list = Range(0,10);\n\n //Why?\n list.Add(11);\n}\n</code></pre>\n\n<p>This might not be a strong example, but my point is : <code>IList</code> represents a data structure where you can add, remove, replace elements and use the indexer. That's a lot of things, do the users of your method <strong>need</strong> all these things? No. By returning an <code>IList</code> you tell your users that the result is expected to be modified or accessed via an index, but they don't need this. You could use <code>ICollection</code>, which let's you add/remove/modifiy elements, without index access. Then again, do you want your users to do this? Probably not. What I'd recommend is using <code>IEnumerable</code>. This states : Here's the \"list\" of things that you wanted, you can take a look, if you want to modify them change it to a list it's not my problem anymore.</p>\n\n<p>The beauty of this changes is that you don't need to change anything in your code except for the return type of your <code>GroupAnagrams</code> method.</p>\n\n<hr>\n\n<p>There's a bug in your equality checker, or at least an undocumented feature.</p>\n\n<pre><code>//Returns false, why?\nCharComparer().Equals((char[])null, (char[])null);\n</code></pre>\n\n<p>The rest of the points I wanted to address have been touched by the other (great) reviews. But I want to stress <strong>Never override <code>GetHashCode()</code> to <code>return 0</code> that's a bad idea.</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:41:50.923",
"Id": "440742",
"Score": "2",
"body": "It is the API given by leetcode IList<>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:44:03.873",
"Id": "440744",
"Score": "0",
"body": "@Gilad oh, I guess this makes sense. I think this would warrant a comment in your code, because otherwise everyone would wonder why you use this specific interface"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:15:27.870",
"Id": "226690",
"ParentId": "226671",
"Score": "5"
}
},
{
"body": "<p>Here's a one liner to have a look at.</p>\n\n<pre><code>public static IList<IList<string>> GroupAnagrams(string[] strs)\n{\n return strs.GroupBy(x => string.Concat(x.OrderBy(c => c))).Select(x => (IList<string>)x.ToList()).ToList();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T17:46:18.650",
"Id": "440906",
"Score": "1",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T17:39:14.960",
"Id": "226753",
"ParentId": "226671",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "226675",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T08:13:54.647",
"Id": "226671",
"Score": "6",
"Tags": [
"c#",
"performance",
"programming-challenge",
"strings",
"hash-map"
],
"Title": "LeetCode: Group Anagrams C#"
}
|
226671
|
<p>I have a function whose responsibility is to send a push notification to a user. I call this function from a view in flask framework.</p>
<p>I have read multiple articles around refactoring and good designs but I want to know from those who have been doing this for a while what I can improve.</p>
<p>Here is the function.</p>
<pre><code> def send_push(api_key, cid, username,request_signature):
## ---> DB CALLS
master_db = get_db('master_db')
cname = master_db.companies.find_one({'company_id': cid})['company_name']
company_db = get_db(cname)
application = company_db.applications.find_one({'app_config.api_key':api_key})
if not application:
#error_log_writer(cid=cid, error='API Key is invalid')
raise InvalidApiKey('The API Key is incorrect.')
appname = application['app_name']
# application = company_db.applications.find_one({'app_name': appname})
username_appname = username + '_' + appname
redis_db = get_redis()
## DB CALLS
if redis_db.hgetall(username_appname):
# error_log_writer(cid=cid, error='The PUSH request is already in process', appname=appname)
raise SomeCustomException(' The request is already in process.')
auth_id = generate_random_alphanumeric(10)
from pyfcm import FCMNotification
push_service = FCMNotification(
api_key="xxxxx"
)
## DB CALLS
user = company_db.users.find_one({"_id": username})
if not user:
raise UserNotFound
## DB CALLS
registration_id = company_db.users.find_one({"_id": username})['device_token']
data_message = {
"Nick" : "Mario",
"body" : "great match!",
"app_name": appname,
"cid": cid,
"username":username,
"auth_id" : auth_id,
"api_key": api_key,
"request_signature":request_signature
}
message_body = "authenticate app?"
username_appname = username + '_' + appname
username_appname_response = username_appname + 'response'
## DB CALLS
redis_db.setex(name=username_appname_response, value='waiting', time=180)
redis_data = {'auth_id': auth_id, 'ts': datetime.datetime.now().strftime('%s')}
redis_db.hmset(username_appname, redis_data)
redis_db.expire(username_appname, 180)
result = push_service.notify_single_device(registration_id=registration_id, data_message=data_message)
</code></pre>
<p>I think this has many code smells. Ideally, I would like to refactor it so that I get</p>
<ul>
<li>Easy unit testing </li>
<li>Avoiding mocks for unit testing where necessary </li>
<li>Minimal side effects</li>
<li>Readable code.</li>
</ul>
<p>Current issues that I think are there: </p>
<ul>
<li>Lots of database calls scattered around the core business logic.</li>
<li>Unit testing is difficult as lots of db calls requires mocking<br>
them. This tightly couples the test to my implementation rather than
behaviour of the function.</li>
<li>Lots of indirection to logic is introduced because of scattered calls
to mongo db & redis.</li>
</ul>
<p>Possible solutions: </p>
<ul>
<li>pass db objects to function rather than creating them inside the
function that handles business logic(but this will just defer the
object creation to a higher level so db calls will have to be mocked
anyways)</li>
</ul>
<p><strong><em>How would you refactor this function considering best practices?</em></strong> </p>
<p><strong><em>Is it a general practice while developing CRUD app to have multiple mocks on average for every function?</em></strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:32:22.953",
"Id": "440641",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:35:28.617",
"Id": "440643",
"Score": "0",
"body": "@Mast I have changed the title to be more specific"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T10:42:05.987",
"Id": "440644",
"Score": "0",
"body": "Remove the concerns from the title, put the concerns in the body of the question. The title should indicate what the code is doing, perhaps why. Not what your concerns (request to refactor, requiring to be unit-testable) are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:02:27.467",
"Id": "440648",
"Score": "0",
"body": "@Mast i ahve edited the title as you said. removed the concerns. but i was browsing other questions & they contradict what you suggested. https://codereview.stackexchange.com/questions/21417/how-to-make-static-methods-testable?rq=1\nhttps://codereview.stackexchange.com/questions/24930/unit-testing-the-importing-of-data-into-a-database?rq=1\nhttps://codereview.stackexchange.com/questions/46172/refactoring-method-to-make-it-unit-testing-friendly?rq=1\nhttps://codereview.stackexchange.com/questions/33379/make-wcf-service-testable?rq=1\n\nif the title is still unclear let me know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:38:51.040",
"Id": "440656",
"Score": "0",
"body": "Old questions are not a good example. [\"Use a title that is catchy, and describes the problem your code solves.\"](https://codereview.meta.stackexchange.com/q/2436/52915) from the [meta-tag:faq] on asking questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:39:31.337",
"Id": "440657",
"Score": "1",
"body": "But thanks for pointing those out, might have to fix their titles later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T11:40:15.210",
"Id": "440658",
"Score": "0",
"body": "@Mast I get the point. Thank you for correcting me. I hope my title is correct. I framed it in best possible way I could think of"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T12:06:57.527",
"Id": "440659",
"Score": "2",
"body": "I shortened that discussion a bit by editing your title to the actual thing your code does (you were almost there ;)) I also edited some sentence structure/grammar. Feel free to [edit] again if I misconstrued anything."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:24:14.647",
"Id": "226676",
"Score": "3",
"Tags": [
"python",
"unit-testing",
"sqlite",
"flask"
],
"Title": "Sending push notifications to a user"
}
|
226676
|
<p>[Posted yesterday on Software Engineering, but was apparently "disappeared"...maybe better here]</p>
<p>Background: I am just starting to get my head around the idea of separating the domain model from the persistence layer (per Uncle Bob), service layer/IoC/separation of concerns/dependency injection, looking at some aspects of DDD (possibly aggregates?), enforcing invariants (e.g. having all private setters below)... <em>And</em> I'm trying to come up with some patterns that assist with those goals — ones the rest of the team can follow and adapt... I'm making multiple leaps in understanding and don't want to twist my ankle when I land.</p>
<p>One result of my effort is this builder pattern for large objects (lots of fields), which implements a fluent API and tries to allow for subclassing of the Builder/target pair allowing builder superclass reuse (THAT required some generics gymnastics). My thought is for a subclass of the domain model object to become a EF Core entity with persistence-specific properties and methods in the subclass, but core business logic still able to exist (and be tested) on the core domain model objects.</p>
<p>Some notes: </p>
<ul>
<li>Classes and business logic are clearly incomplete. </li>
<li>The nested classes are used because they allow for private/protected member access by the Builder. </li>
<li>Assume that <code>Id</code> is a store-specific property and not needed for other use cases. </li>
<li>The <code>Builder</code> property on the <code>Event</code> object is mainly intended as syntactic sugar to allow clients to say <code>Event.Builder</code> instead of <code>new Event.EventBuilder<Event>()</code>. </li>
<li>And if anyone wonders, I'm not going to wrap all of EF Core in a repository/UoW pattern (for now I'm buying the arguments that DbContext <em>is</em> a UoW and DbSet <em>is</em> a repository)...though I am going to put a repository wrapper around some particular entities (like audit events) that I may want to implement with a different store type.</li>
</ul>
<p>So, here's a base <code>Event</code> class/domain model class with an inner <code>EventBuilder<T></code> class: </p>
<pre><code>using System;
using System.Collections.Generic;
namespace App.Core
{
public class Event
{
public String Title { get; private set; }
public DateTimeOffset Start { get; private set; }
public DateTimeOffset End { get; private set; }
// Lots more properties omitted here...
protected Event() { }
public static EventBuilder<Event> Builder => new Event.EventBuilder<Event>();
public class EventBuilder<T> where T : Event
{
protected virtual T Result { get; set; } = Activator.CreateInstance(typeof(T), true) as T;
public EventBuilder<T> WithTitle(String title)
{
Result.Title = title;
return this;
}
public EventBuilder<T> WithStartAndEnd(DateTimeOffset start, DateTimeOffset end)
{
if (start == null)
{
throw new ArgumentNullException(nameof(start));
}
if (end == null)
{
throw new ArgumentNullException(nameof(start));
}
if (end < start)
{
throw new ArgumentOutOfRangeException(nameof(end), end, "End date must be on or after the start date.");
}
this.Result.Start = start;
this.Result.End = end;
return this;
}
public virtual T Create()
{
// Last chance validation here!
return this.Result;
}
}
}
}
</code></pre>
<p>And here's a subclass with persistence-specific features:</p>
<pre><code>namespace App.Repository.Entities
{
public class Event : App.Core.Event
{
public int Id { get; private set; }
public new static EventBuilder<Event> Builder => new Event.EventBuilder<Event>();
public new class EventBuilder<T> : App.Core.Event.EventBuilder<T> where T : Event
{
//protected new T _result = Activator.CreateInstance<T>();
//protected new T _result = Activator.CreateInstance(typeof(T), true) as T;
public EventBuilder<T> WithId(int id)
{
this.Result.Id = id;
return this;
}
public override T Create()
{
// Last chance validation for subclass here!
// This is safe because we know it's operating on a subclass this.Result:
var result = base.Create() as T;
return result;
}
}
}
}
</code></pre>
<p>And here's some naive client code that uses the subclass:</p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using App.Repository.Entities; // <-- Note this namespace
namespace App.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{
// GET: api/Event
[HttpGet]
public ActionResult<IEnumerable<Event>> Get()
{
return new Event[] {
Repository.Entities.Event.Builder
.WithId(5126)
.WithTitle("The Apocalypse")
.WithStartAndEnd(
new DateTimeOffset(2012, 12, 21, 6, 12, 0, new TimeSpan(-4,0,0)),
new DateTimeOffset(2012, 12, 21, 6, 12, 1, new TimeSpan(-4,0,0))
)
.Create()
};
}
// Other REST methods omitted...
}
}
</code></pre>
<p>So, do you see anything glaringly stupid about the above that is going to fry me when I try to actually use it? There is certainly some naivety in the above and I would appreciate other comments/suggestions, but a good answer will point out a flaw that will make me want to substantially change the design or throw it out altogether.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:04:58.897",
"Id": "440666",
"Score": "2",
"body": "One question... what is the benefit of doing this? Usually a builder simplifies _building_ complex objects or makes _raw_ APIs convenient but your solution isn't providing any of that. Since you are using this for _dtos_, I find it's much easier to just say `new Event { Property = \"ABC\" }` and use the _usual_ model validation for other things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:37:47.767",
"Id": "440670",
"Score": "0",
"body": "Interesting subject: I found 2 similar questions, not that this is in any way a duplicate: https://codereview.stackexchange.com/questions/133066/initializing-immutable-objects-with-a-nested-builder and https://codereview.stackexchange.com/questions/151078/generic-immutable-object-builder"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:47:55.753",
"Id": "440673",
"Score": "1",
"body": "@dfhwze there is one more experiment. Have you seen this insane idea too? https://codereview.stackexchange.com/questions/210056/immutable-type-updater-using-a-special-constructor :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:50:16.203",
"Id": "440676",
"Score": "1",
"body": "@t3chb0t that one is even for your standards out of the ordinary o_0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:33:24.863",
"Id": "440684",
"Score": "0",
"body": "@t3chb0t Good question. I think I know why (but have to keep checking). I've omitted many properties in the example (including many-to-many navigation properties)--to allow creation via constructor with any or all properties gets into the telescoping constructor problem and makes it (I think) hard to validate a constructed object without calling other constructors--which gets particuarly convoluted with subclasses. In this pattern I can always validate the object at the end, in `Create()`. Also, I was looking for a pattern to apply to many cases, to help myself+team keep discipline uniformly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:37:18.797",
"Id": "440687",
"Score": "3",
"body": "You have to post the complete code so that we have the full picture of your work. Until this is done, I vote to close this question as lacking context. Let's continue this topic when the question is updated."
}
] |
[
{
"body": "<p>I'm not sure this qualifies as a review, but here we go anyways.</p>\n\n<p>Don't do this. This is one of the classic use of a design pattern where we shouldn't use one. A design pattern is a solution to a known problem with set boundaries and a very specific scenario. The builder is used to build <strong>complex</strong> objects in a <strong>flexible</strong> manner. A DTO isn't a complex object and shouldn't be built in a flexible manner. If your DTOs are complex, that is the problem you should tackle with your team, not trying to find a work to work with complex DTOs.</p>\n\n<p>When reading your first paragraph, I swear I could've written it 5 years ago. I've written <a href=\"https://codereview.stackexchange.com/questions/60054/generic-equality-checker\">a generic equality checker</a> (in hopes that it would help make equality comparison easier, where it's already really easy. What happened is :</p>\n\n<ol>\n<li>We found edge cases that weren't supported, ended up working on it a lot more to fix the edge cases</li>\n<li>It got complicated and new developers had a hard time figuring out how it worked</li>\n<li>It died and is probably to this date still marked as <code>[Deprecated]</code> in a code base</li>\n</ol>\n\n<p>Now, I ask myself three questions before I try to add a \"generic\" tool that'll \"help\" my fellow developers : </p>\n\n<ul>\n<li>Is the problem I'm trying to solve complex enough to require such a solution?</li>\n<li>Am I <strong>100%</strong> sure that what I've written won't explode in a mess of edge cases that'll cost more to maintain than not having the solution at all?</li>\n<li>Will other developers pick it up easily and understand how it works?</li>\n</ul>\n\n<p>I'd say that 9 times out of 10, the answer is no to at least one of those questions and I end up not doing it. It takes experience to know when not to do something, because as developers we always want to work with the cool stuff, but most of the time it creates more complexity than it solves.</p>\n\n<p>Now, that doesn't mean you should fiddle with ideas like these, because you can learn a lot about many things (reflection, expressions, generics, etc.). But you need to develop the reflex to ask yourself \"Should this be used in a production code that'll need to be maintained for years, potentially without me?\" and think <em>hard</em> about the possible consequences of using whatever you're going to build.</p>\n\n<hr>\n\n<p>The <code>new</code> keyword is probably the biggest \"maintainability danger\" of the C# language (In my opinion). I really think you should use whatever other way you have not to use it (ie. removing the nested class). Use interfaces, dependency injection, etc. not to use the <code>new</code> keyword. (I'm obviously not talking about class instantiation)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:41:45.953",
"Id": "440688",
"Score": "0",
"body": "Well, OP has just admitted that their code is heavily shortened so I think any review doesn't make much sense as we don't see the real complexity and the problem they're facing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:43:08.817",
"Id": "440689",
"Score": "1",
"body": "@t3chb0t Well that sucks because I took time to write my answer ahah, but I'm almost certain that whatever is added to the code won't make this builder pattern worth it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:44:07.467",
"Id": "440690",
"Score": "0",
"body": "True, your answer is so universal that whatever comes, it'll stay valid,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:47:02.750",
"Id": "440691",
"Score": "0",
"body": "Thanks for this. Question... both you and @t3chb0t have referred to me using this pattern to make DTOs... But I don't see it that way, exactly... I'm planning to use this for model objects (primarily), but my pattern is to have the DTOs be a subclass of the model object, with the persistence dependencies. Is this fundamentally flawed? If (and this is not guaranteed of course), my model object's properties closely match what I want in my persistent model, maybe plus some housekeeping properties/methods?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:50:31.310",
"Id": "440693",
"Score": "0",
"body": "I should add that I'm coming from using EF4 + MVC with pretty much all my business logic in the controllers... and trying to move domain logic into domain model objects and application logic into a service layer. This DTO-as-subclass model made sense to me if I could make it work, and this pattern was one part of getting there. Keeping the setters private is done to help me control state via behavioral model methods, hence I had to think about initializing an object with many properties (domain model or DTO, either way)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:52:32.170",
"Id": "440694",
"Score": "0",
"body": "@S'pht'Kr yes, it is flawed. Your model class will probably be complex and validation heavy with maybe nested domain classes, where your DTOs should be dummy `{get; set;}` properties. I don't really have the space to write all the reasons I think it'll probably bounce back in your face, but think of the consequences on contravariance, covariance, on the evolution of your model objects, on the dependencies your DTO will have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:53:22.370",
"Id": "440696",
"Score": "0",
"body": "@S'pht'Kr What I mean is, sit down and try to think of all the ways it could go wrong in a month, year, 5 years, if you leave, etc and ask yourself if it's still worth it to go this way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:58:58.240",
"Id": "440697",
"Score": "0",
"body": "@IEatBagels I get that... absolutely. But I'm not sure I'm convinced subclass-as-DTO is flawed just based on that comment. Maybe I need to make that a separate question over on Software Engineering. Most introductory and intermediate-level stuff using MVC + EF essentially treats the data model as *both* model object and DTO (with business logic willy-nilly all over the place), this seemed at least somewhat reasonable as a way to make that familiar while breaking the dependency on EF from the domain model layer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:01:57.413",
"Id": "440698",
"Score": "0",
"body": "@S'pht'Kr I understand your point, what I'm saying is that the experience I've had with those exact technologies and this exact mindset is that models and DTOs grow apart in the lifetime of the application and that if you couple them you end up with problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:06:22.273",
"Id": "440700",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/97770/discussion-between-ieatbagels-and-sphtkr)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:35:31.980",
"Id": "440739",
"Score": "0",
"body": "Question on DAO-as-subclass (we were saying DTO but really it's a DAO I suppose) posted to SE.SE: https://softwareengineering.stackexchange.com/questions/396409/is-making-your-orm-dao-a-subclass-of-your-domain-model-object-a-viable-strategy"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T14:40:21.237",
"Id": "226687",
"ParentId": "226682",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T12:58:14.177",
"Id": "226682",
"Score": "1",
"Tags": [
"c#",
"design-patterns",
"polymorphism",
"immutability",
"fluent-interface"
],
"Title": "Builder pattern in C# supporting subclassing with nested classes"
}
|
226682
|
<p>I am a newbie in the scientific computing in python. The function I am trying to calculate is the response of the wave equation for a given source term (For reference, See: Equation 11.67 in <a href="https://webhome.phy.duke.edu/~rgb/Class/phy319/phy319/node75.html" rel="nofollow noreferrer">https://webhome.phy.duke.edu/~rgb/Class/phy319/phy319/node75.html</a>). </p>
<p><span class="math-container">$$\phi(\pmb{x},t) = \int_V G_+(\pmb{x}, t; \pmb{x'}, t)\rho(\pmb{x'}, t')d^3x'dt'$$</span></p>
<p>To give context, the term phi in the equation 11.67 is the displacement and the term rho can be thought as a source of disturbance. </p>
<p>Now, in my case, the problem is constructed in spatial dimension of 2 (x-y). Thus, I have to iterate the equation for grid points in x, y and t. This makes the overall calculation extremely time-consuming. Below is my lines of code:</p>
<pre><code>import numpy as np
# Assigning grid points
Nx = 100
Ny = 100
Nt = 100
x = np.linspace(-Nx, Nx, 100)
y = np.linspace(-Ny, Ny, 100)
t = np.linspace(0, Nt-1, 100)
# Equation to solve
# phi(x,y,t) = ∫∫∫ G(x,y,t; x',y',t') . Source(x',y',t') dx' dy' dt'
# G(x,y,t; x',y',t') = Green's Function
# phi = displacement by the wave
phi = np.zeros((Nt,Ny,Nx))
# Define Function to realize Green's Function for Wave Equation
def gw(xx, yy, tt, mm, nn, ss):
numer = (tt-ss) - np.sqrt((xx-mm)**2+(yy-nn)**2)
denom = ((tt-ss)**2-(xx-mm)**2-(yy-nn)**2)
if denom < 0:
denom = 0
else:
denom = np.sqrt(denom)
kk = np.heaviside(numer,1)/(2*np.pi*denom+1)
return (kk)
# Define Function to realize Gaussian Disturbance
def g_source(xx, yy, tt):
spatial_sigma = 5 # spatial width of the Gaussian
temporal_sigma = 30 # temporal width of the Gaussian
onset_time = 20 # time when Gaussian Disturbance reaches its peak
kk = np.exp((-(np.sqrt((xx)**2+(yy)**2)/spatial_sigma)**2)))*np.exp(-((tt-onset_time)/temporal_sigma)**2)
return (kk)
for k in range (Nt):
for j in range (Ny):
for i in range (Nx):
# this is the Green's function evaluated in each grid points
green = np.array([gw(x[i],y[j],t[k],i_grid,j_grid,k_grid) for k_grid in t for j_grid in y for i_grid in x])
green = green.reshape(Nt, Ny, Nx)
# this is the source term (rho), here it is a Gaussian Disturbance
gauss = np.array([g_source(i_grid,j_grid,k_grid) for k_grid in t for j_grid in y for i_grid in x])
gauss = gauss.reshape(Nt, Ny, Nx)
# performing integration
phi[k,j,i] = sum(sum(sum(np.multiply(green,gauss))))
</code></pre>
<p>Please let me know if there is a faster way to do this integration. Thanks in advance. I deeply appreciate your patience and support.</p>
|
[] |
[
{
"body": "<p>I'm no mathematician, but here are some suggestions as a long-time programmer:</p>\n\n<ol>\n<li><p><strong>Naming</strong> is one of the hardest programming skills to learn, but it is also incredibly important for readability and maintainability. Renaming things can make certain bugs and code smells obvious.</p>\n\n<ul>\n<li>I would recommend <strong>expanding any abbreviations</strong> within reason, as long as writing them out makes the code even a smidge more readable, like <code>denominator</code> instead of <code>denom</code>.</li>\n<li>It is not clear what <code>Nx</code> etc. are. It looks like they are <em>half</em> of the extent of the world, since you create <code>x</code> from <code>-Nx</code> to <code>Nx</code> etc. (see below).</li>\n<li><code>x</code>, <code>y</code> and <code>t</code> are usually used as names for coordinates. In your case they are instead collections of coordinates or axes, so I would name them <code>x_axis</code> or <code>x_coordinates</code> etc.</li>\n<li><code>xx</code> etc. <em>are</em> coordinates, so I would name them <code>x_coordinate</code> or just <code>x</code>.</li>\n<li><p>A good rule of thumb is to try to \"optimize\" comments into names. So rather than</p>\n\n<pre><code># Define Function to realize Gaussian Disturbance\ndef g_source(xx, yy, tt):\n</code></pre>\n\n<p>I would probably write something like</p>\n\n<pre><code>def gaussian_disturbance(x: int, y: int, t: int) -> float:\n</code></pre>\n\n<p>As far as I can tell this should make at least some of the comments within that function redundant.</p></li>\n</ul></li>\n<li>As far as I can tell <code>np.linspace(-Nx, Nx, 100)</code> creates an array <code>[-100, -98, …, 98, 100]</code>. Is it intentional that points are separated by two, should the range be from 0 to 100, or should <code>num</code> be 200? If the range is meant to be from 0 to 100 that would cut the memory and processing requirements by a factor of eight.</li>\n</ol>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic. In terms of bang for your buck this tool is unbeatable.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>It can take some time to understand and correct for all the things it prints out, but doing so will help a lot in the long run.</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<p>This makes it clear what you are passing around, and can highlight issues such as using a variable for more than one thing.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:09:06.143",
"Id": "440784",
"Score": "0",
"body": "Thank you so much for the detailed tips and suggestions. I will try to follow these from now on. Appreciate the effort and patience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-12-01T12:26:47.783",
"Id": "534397",
"Score": "0",
"body": "\"def gaussian_disturbance(x: int, y: int, t: int) -> float:\"\n\nIf anyone unfamiliar is wondering, -> is a type annotation"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:02:06.813",
"Id": "226710",
"ParentId": "226691",
"Score": "2"
}
},
{
"body": "<h2><strong>Performance wise</strong></h2>\n\n<p><strong>In general:</strong></p>\n\n<p>You use numpy, but you write it almost like in fortran. Python with <code>numpy</code> is good for scientific programing and computing as long as you <strong>don't do many loops</strong></p>\n\n<ul>\n<li>read this first <a href=\"https://scipy-cookbook.readthedocs.io/items/PerformancePython.html\" rel=\"nofollow noreferrer\">A beginners guide to using Python for performance computing</a></li>\n<li>if you really need to do tight loops than use\n<a href=\"https://cython.readthedocs.io/en/latest/src/tutorial/numpy.html\" rel=\"nofollow noreferrer\">cython</a>.</li>\n<li>But most of the time you can avoid that by expressing the loop as some functional operation on the whole array \n\n<ul>\n<li>most numpy functions can operator on whole array in one pass, use it.\n\n<ul>\n<li>always prefer <code>y[:]=np.sqrt(x[:])</code> and avoid</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<pre><code> `for i in xrange(N): \n y[i]=np.sqrt(x[i])`\n</code></pre>\n\n<ul>\n<li>operation like <code>dot</code>,<code>convolve</code>,<code>einsum</code>,<code>ufunc.reduce</code> are very potent to express most sciencetific algorithms in more abstract way</li>\n<li><p>use <a href=\"https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\" rel=\"nofollow noreferrer\">advanced array slicing</a></p>\n\n<ul>\n<li><p>you can express most inner <code>if</code> by <code>boolen mask arrays</code> or <code>integer index array</code></p>\n\n<ul>\n<li><p>e.g. <code>f[ f>15.0 ] = 15.0</code> clamp all elements in array <code>f</code> which are <code>>15.0</code> to <code>15.0</code>; you can also store the boolean mask <code>mask = (f>15.0)</code> and than use it like <code>f[mask]+=g[mask]</code>. This way you can express branching as fully functional programs/expressions with arrays.</p></li>\n<li><p>Do not construct new <code>np.array</code> (<code>np.zeros, np.ones</code> etc.) too often (i.e. inside tight loops). Optimal performance is obtained if you prepare all arrays you need at the beggining. Avoid frequent conversion between list and array</p></li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p><strong>To address your code example in particular:</strong></p>\n\n<ul>\n<li>Green's functions are basically convolutions. I'm pretty sure you can express it using e.g. <a href=\"https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.filters.convolve.html\" rel=\"nofollow noreferrer\">scipy.ndimage.filters.convolve</a></li>\n<li><p>if your convolution kernel is large (i.e. pixels interact more than with few neighbors) than it is often much faster to do it in Fourier space (<a href=\"https://en.wikipedia.org/wiki/Convolution_theorem\" rel=\"nofollow noreferrer\">convolution transforms as multiplication</a>) and using <a href=\"https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.fft.fftn.html\" rel=\"nofollow noreferrer\">np.fftn</a> with <code>O(nlog(N))</code> cost.</p></li>\n<li><p>cannot <code>def gw(xx, yy, tt, mm, nn, ss):</code> operate on the whole array,\nrather than individual numbers?</p></li>\n<li><code>if denom < 0:</code> can be expressed using <code>boolean mask array</code> like <code>mask = denom >0; denom[mask] = np.sqrt(denom[maks])</code></li>\n<li>Never do this if you can:</li>\n</ul>\n\n<pre><code> for k in range (Nt):\n for j in range (Ny):\n for i in range (Nx):\n</code></pre>\n\n<p>the operations seems to be possible to rewrite that operate on the whole <code>x,y</code> space at once </p>\n\n<ul>\n<li>This is how you do convolution-like operations in numpy (from <a href=\"https://scipy-cookbook.readthedocs.io/items/PerformancePython.html\" rel=\"nofollow noreferrer\">here</a>)</li>\n</ul>\n\n<pre><code> # The actual iteration\n u[1:-1, 1:-1] = ((u[0:-2, 1:-1] + u[2:, 1:-1])*dy2 +\n (u[1:-1,0:-2] + u[1:-1, 2:])*dx2)*dnr_inv\n</code></pre>\n\n<ul>\n<li>this is so horrible:</li>\n</ul>\n\n<pre><code>green = np.array([gw(x[i],y[j],t[k],i_grid,j_grid,k_grid) for k_grid in t for j_grid in y for i_grid in x])\n</code></pre>\n\n<ul>\n<li>list comprehesion is relatively fast, but still much slower than numpy array operations (which are implemented in C).</li>\n<li>do not create temporary list and convert it to temporary array, you loose lot time doing that.</li>\n<li>why you cannot just prealocate <code>Green[Nx,Ny,:]</code> and <code>Gauss[Nx,Ny,:]</code> and use it as a whole?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T20:53:09.117",
"Id": "441236",
"Score": "0",
"body": "Thank you so much for the detailed answers. And thanks a lot for sharing the awesome links. I have learned a lot in last couple of days from your suggestion. I have accepted your answer as a solution of my problems and upvoted it. \n\nHowever, I am facing another problem. This line of code increases the speed superbly. But it is giving memory error for my grid (100,100,100). Any suggestions? \n\n `green = gw(x[None,None,:,None,None,None],y[None,:,None,None,None,None],t[:,None,None,None,None,None],x[None,None,None,None,None,:],y[None,None,None,None,:,None],t[None,None,None,:,None,None])`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:05:18.990",
"Id": "441292",
"Score": "1",
"body": "yes, I guess you overdo it a bit. You don't have to work with 6-dimensional arrays right away. Perhaps the best is to keep few outer loops. In this particular case when order of summationd does not matter and the size along each dimension is the same, it does not really matter which loops you keep, in other case you should choose the shorter loops (usually the size of kernel (Green, Gauss) is smaller than size of the function phi). Anyway, as I said, this is convolution, so you can perhaps simply call `scipy.ndimage.filters.convolve`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:19:55.067",
"Id": "441295",
"Score": "1",
"body": "I notice, that the kernel (Green) is translational symmetric, so you can precompute it as 3D arrays depending only of difference `Green[:,:,:]=gw( dx,dy,dz) where dx,dy,dz are 1D arrays representing tt-ss, xx-nn,yy-mm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:22:36.157",
"Id": "441297",
"Score": "1",
"body": "then you just call `phi = scipy.ndimage.filters.convolve( Gauss, Green)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:28:24.767",
"Id": "441299",
"Score": "1",
"body": "But as I say for such large kernel it is rather inefficient to do it in real space (under the hood the 3D convolve function still does 6-dimensional iteration). Therefore I strongly recommend to do it in Fourier space using FFT if you don't mind periodic boundary conditions. It it can be thousands time faster. Should be something like phi = np.ifftn( np.fftn(Green) * np.fftn(Gauss) )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T09:32:59.543",
"Id": "441301",
"Score": "2",
"body": "when you learn how to use `np.fftn` and `scipy.ndimage.filters.convolve` please post the final solution there so other people can use it as a refference. (I don't have time now to test it, and I don't want to post untested code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:11:12.280",
"Id": "441647",
"Score": "0",
"body": "I have posted the final solution below. Thanks again for your suggestions."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T17:50:29.047",
"Id": "226754",
"ParentId": "226691",
"Score": "3"
}
},
{
"body": "<p>Thanks a lot for Prokop Hapala's helpful comments and suggestions. This is the code that has done job.</p>\n\n<pre><code>import numpy as np\nfrom numpy import pi\nfrom scipy import signal\n\n# Assigning grid points\n\nNx = 100\nNy = 100\nNt = 100\n\nx = np.linspace(-Nx, Nx, 100)\ny = np.linspace(-Ny, Ny, 100)\nt = np.linspace(0, Nt-1, 100)\n\n# Equation to solve\n# phi(x,y,t) = ∫∫∫ G(x,y,t; x',y',t') . Source(x',y',t') dx' dy' dt'\n# G(x,y,t; x',y',t') = Green's Function\n\n# phi = displacement by the wave\nphi = np.zeros((Nt,Ny,Nx))\n\n\n# Define Function to realize Green's Function for Wave Equation\ndef gw(xx, yy, tt):\n\n kk = np.heaviside((tt-np.sqrt(xx**2+yy**2)),1)/(2*np.pi*np.sqrt(np.clip(tt**2-xx**2-yy**2,0,None))+1)\n return (kk)\n\n\n# Define Function to realize Gaussian Disturbance\ndef g_source(xx, yy, tt):\n\n spatial_sigma = 5 # spatial width of the Gaussian \n temporal_sigma = 30 # temporal width of the Gaussian \n onset_time = 20 # time when Gaussian Disturbance reaches its peak\n\n kk = np.exp((-(np.sqrt((xx)**2+(yy)**2)/spatial_sigma)**2)))*np.exp(-((tt-onset_time)/temporal_sigma)**2)\n return (kk)\n\n# Calculate the two function for given grid points\ngreen = gw(x[None,None,:],y[None,:,None],t[:,None,None])\ngauss = g_source(x[None,None,:],y[None,:,None],t[:,None,None])\n\n# Calculate Source Response via convolution \nphi = signal.convolve(gauss, green, mode='full')\n</code></pre>\n\n<p>Ideally, one would use scipy.signal.fftconvolve to take the advantage of doing convolution in Fourier space (which brings down the iteration to 3D in this problem, instead of 6D in real space). However, As of v0.19, signal.convolve automatically chooses fft method or the real space method based on an estimation of which is faster.</p>\n\n<p>Note: I tried to employ the scipy.ndimage.filters.convolve for my problem, but it gave back memory error which means it tried to do the 3D convolve function by 6-dimensional iteration under the hood and that was too much for my RAM (32 GB). But the scipy.signal.convolve worked fine even for much denser grid points.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:10:25.700",
"Id": "441646",
"Score": "0",
"body": "And it took only 1.01 seconds to solve. Thanks again to Prokop Hapala :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T19:08:37.417",
"Id": "227034",
"ParentId": "226691",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226754",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:16:30.953",
"Id": "226691",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Fast way to calculate source response using Green's function"
}
|
226691
|
<p>I have an AWS Elastic Search server.
Using mapping template and an index strategy.</p>
<pre><code>{
"index_patterns": "users*",
"order": 6,
"version": 6,
"aliases": {
"users": {}
},
"settings": {
"number_of_shards": 5
},
"mappings": {
"_doc": {
"dynamic": "strict",
"properties": {
"id": { "type": "keyword" },
"emailAddress": { "type": "keyword" }
}
}
}
}
</code></pre>
<p>Index strategy is <code>{index_patterns}-{yyyy}-{MM}-{order}-{version}</code></p>
<p>Using NEST SDK to index document in a background application consuming SQS messages with the below method.</p>
<pre><code>public async Task<Result> IndexAsync(
T document,
string indexName = null,
string typeName = null,
Refresh? refresh = null,
CancellationToken cancellationToken = default)
{
var response = await Client.IndexAsync(
document,
i => i.Index(indexName ?? DocumentMappings.IndexStrategy)
.Type(typeName ?? DocumentMappings.TypeName)
.Id(document.Id)
.Refresh(refresh),
cancellationToken);
var errorMessage = response.LogResponseIfError(_logger);
return errorMessage.IsNullOrEmpty() ? Result.Ok() : Result.Fail(errorMessage);
}
</code></pre>
<p>This is a base method and is called like this.</p>
<pre><code>var result = await _usersRepository.IndexAsync(userDocument, refresh: Refresh.True, cancellationToken: cancellationToken);
</code></pre>
<p>Here I am using <code>Refresh.True</code> because this is a user signup and I want the document to be available ASAP but noticed a performance hit, it takes a while for example to index 50,000 users in a load test.</p>
<p><code>Refresh.True</code> refreshes all shards for this index, now I do this for each request of 50,000 calls and it seems like I get the hit.
Any input how can I improve this?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:22:42.860",
"Id": "226692",
"Score": "1",
"Tags": [
"c#",
"performance",
"elasticsearch"
],
"Title": "Indexing documents in Elastic Search using Refresh.True - Performance hit and how can it be improved?"
}
|
226692
|
<p>There aren't enough questions about creating immutable objects... so why not try it again with another approach. This time, it's a builder that maps properties to constructor parameters. Properties are selected via the <code>With</code> method that also expects a new value for the parameter. Constructor parameters must match properties so it's primarily for DTOs that follow this pattern. <code>Build</code> tries to find that constructor and creates the object.</p>
<pre><code>// I need this primarily for the left-join of optional parameters.
internal class IgnoreCase : IEquatable<string>
{
public string Value { get; set; }
public bool Equals(string other) => StringComparer.OrdinalIgnoreCase.Equals(Value, other);
public override bool Equals(object obj) => obj is IgnoreCase ic && Equals(ic.Value);
public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value);
public static explicit operator IgnoreCase(string value) => new IgnoreCase { Value = value };
}
public class ImmutableBuilder<T>
{
private readonly IList<(MemberExpression Selector, object Value)> _selectors = new List<(MemberExpression Selector, object Value)>();
public ImmutableBuilder<T> With<TProperty>(Expression<Func<T, TProperty>> selector, TProperty value)
{
_selectors.Add(((MemberExpression)selector.Body, value));
return this;
}
public T Build()
{
var ctors =
from ctor in typeof(T).GetConstructors()
let parameters = ctor.GetParameters()
// Join parameters and values by parameter order.
// The ctor requires them sorted but they might be initialized in any order.
let requiredParameterValues =
from parameter in parameters.Where(p => !p.IsOptional)
join selector in _selectors on (IgnoreCase)parameter.Name equals (IgnoreCase)selector.Selector.Member.Name
select selector.Value
// Get optional parameters if any.
let optionalParameterValues =
from parameter in parameters.Where(p => p.IsOptional)
join selector in _selectors on (IgnoreCase)parameter.Name equals (IgnoreCase)selector.Selector.Member.Name into s
from selector in s.DefaultIfEmpty()
select selector.Value
// Make sure all required parameters are specified.
where requiredParameterValues.Count() == parameters.Where(p => !p.IsOptional).Count()
select (ctor, requiredParameterValues, optionalParameterValues);
var theOne = ctors.Single();
return (T)theOne.ctor.Invoke(theOne.requiredParameterValues.Concat(theOne.optionalParameterValues).ToArray());
}
}
public static class Immutable<T>
{
public static ImmutableBuilder<T> Builder => new ImmutableBuilder<T>();
}
</code></pre>
<p>In case we already have an immutable type and want to <em>modify</em> it by changing just some values, the <code>ImmutableHelper</code> can be used. It also provides the <code>With</code> method expecting a new value. Then matches it and other properties with the constructor and uses origianl values as defaults and for the specified property the new value.</p>
<pre><code>public static class ImmutableHelper
{
public static T With<T, TProperty>(this T obj, Expression<Func<T, TProperty>> selector, TProperty value)
{
var comparer = StringComparer.OrdinalIgnoreCase;
var propertyName = ((MemberExpression)selector.Body).Member.Name;
var properties = typeof(T).GetProperties();
var propertyNames =
properties
.Select(x => x.Name)
// A hash-set is convenient for name matching in the next step.
.ToImmutableHashSet(comparer);
// Find the constructor that matches property names.
var ctors =
from ctor in typeof(T).GetConstructors()
where propertyNames.IsProperSupersetOf(ctor.GetParameters().Select(x => x.Name))
select ctor;
var theOne = ctors.Single(); // There can be only one match.
var parameters =
from parameter in theOne.GetParameters()
join property in properties on (IgnoreCase)parameter.Name equals (IgnoreCase)property.Name
// They definitely match so no comparer is necessary.
// Use either the new value or the current one.
select property.Name == propertyName ? value : property.GetValue(obj);
return (T)theOne.Invoke(parameters.ToArray());
}
}
</code></pre>
<h3>Example</h3>
<p>This is how it can be used:</p>
<pre><code>void Main()
{
var person =
Immutable<Person>
.Builder
.With(x => x.FirstName, "Jane")
.With(x => x.LastName, null)
//.With(x => x.NickName, "JD") // Optional
.Build();
person.With(x => x.LastName, "Doe").Dump();
}
public class Person
{
public Person(string firstName, string lastName, string nickName = null)
{
FirstName = firstName;
LastName = lastName;
NickName = nickName;
}
// This ctor should confuse the API.
public Person(string other) { }
public string FirstName { get; }
public string LastName { get; }
public string NickName { get; }
// This property should confuse the API too.
public string FullName => $"{LastName}, {FirstName}";
}
</code></pre>
<hr>
<p>What do you say? Crazy? Insane? I like it? Let's improve it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:38:42.450",
"Id": "440706",
"Score": "2",
"body": "This has a use case for building controllers and what not that have dozens of parameters. Does this also work with optional ctr arguments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:41:12.193",
"Id": "440708",
"Score": "1",
"body": "@dfhwze it doesn't... but it definitelly could... and should."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:41:53.917",
"Id": "440709",
"Score": "0",
"body": "Ok ... so let's improve it! :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T16:09:58.217",
"Id": "440723",
"Score": "0",
"body": "@dfhwze done! ;-] at least the main builder can do this now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T16:17:55.983",
"Id": "440728",
"Score": "0",
"body": "As I said to a few ppl today, I'm out of votes, but this is excellent stuff. Your pace is insane o_0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:55:47.513",
"Id": "440782",
"Score": "1",
"body": "I like the `With` extensions method that helps to create modified copies of mutable types. However I didn't get the use case of the `ImmutableBuilder`.. Why not just calling the constructor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:33:07.850",
"Id": "440802",
"Score": "0",
"body": "@JanDotNet yeah, this idea wasn't the best one especially that it required all parameters. I removed this constraint. It now allows to update any property/field."
}
] |
[
{
"body": "<p>You use <code>IList<></code> where you should use <code>ICollection<></code>. I've rarely encountered a scenario where <code>IList<></code> actually needs to be used. The <code>ICollection<></code> interface has most of the list's methods, but without everything related to indexing, which you don't use anyway. It's not that big of a deal, but I think it's good knowledge.</p>\n\n<hr>\n\n<p>When you search for constructor parameters, I think you should match on parameter types in addition of parameter names. The reason behind this is that this that parameter types with names are guaranteed to be unique, where parameter names could not. For example (it's not a great one, but it's a case that would make your code potentially crash)</p>\n\n<pre><code>class Foobar\n{\n\n public Foobar(string a, int b)\n {\n }\n\n public Foobar(string a, double b)\n {\n }\n\n}\n</code></pre>\n\n<hr>\n\n<p>One problem I see with the <code>Immutable<T></code> class is that I wouldn't expect a <code>static</code> property to return a new reference every time I call it. I've been trying to find another example in the .NET framework of when this happens, and... I couldn't. I would change it for a method named something like <code>CreateBuilder()</code> or something like that, this way it's clear that we are using a new builder every time we call the method.</p>\n\n<hr>\n\n<p>I think the <code>Immutable<></code> type is misleading. When seeing this, I'd expect being able to use it to make some mutable type immutable (however that would be done), but that's not what it does. As a matter of fact, most of your code doesn't rely on the <code>T</code> type to be immutable, which makes me think a tweak or two could make your tool work on mutable types too. In that sense, claiming it's an <code>ImmutableBuilder</code> is kind of wrong, it's a builder that works on immutable types, but on mutable types too.</p>\n\n<hr>\n\n<p>According to comments, your <code>With</code> method in <code>ImmutableHelper</code> creates a copy of the object with a changed parameter, which is alright considering it doesn't modify the immutable type. What I think could be improved is a similar method with the signature <code>static T With<T, TProperty>(this T obj, IEnmerable<(Expression<Func<T, TProperty>> selector, TProperty value)>)</code>, so that if you want to modify more than one field in the object you could do so without having to create a copy of the object every time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:47:21.037",
"Id": "440745",
"Score": "0",
"body": "About the last paragraph... this will go into production (after I made it match parameter types too) because let's say you have an immutable type `Uri` with such a constructor as `scheme, authority, path, query, fragment` and you just want to _change_ its `scheme` from _nothing_ (relative uri) to `http` and maybe add a `fragment`. It's mutch easier and reliable to do this with `With(x => x.Property, value)` and let the framework handle other values than copy all the values yourself... and I once made that mistake of forgetting one of them... I was chasing the bug for 3h :-["
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:55:55.190",
"Id": "440747",
"Score": "0",
"body": "@t3chb0t But by doing this you break everything that is expected from an immutable type. If another developer uses the `Uri` class, he/she will expect it to be immutable. If you happen to use your method somewhere in the code, debugging for this other person will be much more hellish than otherwise. You could use a `Copy` method then change the necessary fields or something else, maybe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:58:00.233",
"Id": "440749",
"Score": "1",
"body": "@t3chb0t Although I understand the bug you've had, it's a tricky bug to find because it's kind of unexpected. I just don't think mutating immutable types is the right solution. Otherwise, maybe your `With` method could create a new copy of the object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:09:28.063",
"Id": "440757",
"Score": "0",
"body": "Oh, you mean this... yes! It is creating a new copy. The first class is just an initializer and the extension `ImmutableHelper.With` copies values into a new object. I probably should have put quotes around _updater_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:10:47.427",
"Id": "440758",
"Score": "0",
"body": "@t3chb0t oohhh. Let me edit my answer then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:41:32.497",
"Id": "440774",
"Score": "0",
"body": "Actually there is (at least) one type that has a `static` property returning new values everytime... but the authors admit that it was a mistake (they write about it in the book about framework design... I don't remember title of it right now)... it's the _famous_ `DateTime.(Utc)Now`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:42:30.460",
"Id": "440776",
"Score": "0",
"body": "@t3chb0t yes, that's a good example. Although, as you stated, it's probably a pattern that wouldn't be repeated today."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:36:26.883",
"Id": "226706",
"ParentId": "226694",
"Score": "7"
}
},
{
"body": "<p><em>(self-answer)</em></p>\n\n<hr>\n\n<p>The idea for not-using the constructor is indeed insane but... since it's possible I kept it in the new version too. I changed the name of this tool to <code>DtoUpdater</code>. It now can collect updates for multiple properties that at the end have to be <code>Commit</code>ed. Parameters are now matched with members not only by name but also by type and it picks the constructor with the most parameters ana matching properties. I created this helper for updating <em>simple</em> DTOs and they usually have only one constructor initializing all properties so I think its current <em>complexity</em> is sufficient for most use-cases. </p>\n\n<p>This version also no longer forces the user to specify all values that a constructor requires. I think that this new functionality now makes this utility in certain situations more useful than using the construtor... if it allows <code>default</code> values of course.</p>\n\n<pre><code>public static class DtoUpdater\n{\n public static DtoUpdater<T> For<T>() => new DtoUpdater<T>(default);\n\n public static DtoUpdater<T> Update<T>(this T obj) => new DtoUpdater<T>(obj);\n}\n\npublic class DtoUpdater<T>\n{\n private readonly T _obj;\n\n private readonly ICollection<(MemberInfo Member, object Value)> _updates = new List<(MemberInfo Member, object Value)>();\n\n public DtoUpdater(T obj) => _obj = obj;\n\n public DtoUpdater<T> With<TProperty>(Expression<Func<T, TProperty>> update, TProperty value)\n {\n _updates.Add((((MemberExpression)update.Body).Member, value));\n return this;\n }\n\n public T Commit()\n {\n var members =\n from member in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance).Where(m => m is PropertyInfo || m is FieldInfo)\n select (member.Name, Type: (member as PropertyInfo)?.PropertyType ?? (member as FieldInfo)?.FieldType);\n\n members = members.ToList();\n\n // Find the ctor that matches most properties.\n var ctors =\n from ctor in typeof(T).GetConstructors()\n let parameters = ctor.GetParameters()\n from parameter in parameters\n join member in members\n on\n new\n {\n Name = parameter.Name.AsIgnoreCase(),\n Type = parameter.ParameterType\n }\n equals\n new\n {\n Name = member.Name.AsIgnoreCase(),\n Type = member.Type\n }\n orderby parameters.Length descending\n select ctor;\n\n var theOne = ctors.First();\n\n // Join parameters and values by parameter order.\n // The ctor requires them sorted but they might be initialized in any order.\n var parameterValues =\n from parameter in theOne.GetParameters()\n join update in _updates on parameter.Name.AsIgnoreCase() equals update.Member.Name.AsIgnoreCase() into x\n from update in x.DefaultIfEmpty()\n select update.Value ?? GetMemberValueOrDefault(parameter.Name);\n\n return (T)theOne.Invoke(parameterValues.ToArray());\n }\n\n private object GetMemberValueOrDefault(string memberName)\n {\n if (_obj == null) return default;\n\n // There is for sure only one member with that name.\n switch (typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance).Single(m => m.Name.AsIgnoreCase().Equals(memberName)))\n {\n case PropertyInfo p: return p.GetValue(_obj);\n case FieldInfo f: return f.GetValue(_obj);\n default: return default; // Makes the compiler very happy.\n }\n }\n}\n\npublic static class StringExtensions\n{\n public static IEquatable<string> AsIgnoreCase(this string str) => (IgnoreCase)str;\n\n private class IgnoreCase : IEquatable<string>\n {\n private IgnoreCase(string value) => Value = value;\n private string Value { get; }\n public bool Equals(string other) => StringComparer.OrdinalIgnoreCase.Equals(Value, other);\n public override bool Equals(object obj) => obj is IgnoreCase ic && Equals(ic.Value);\n public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value);\n public static explicit operator IgnoreCase(string value) => new IgnoreCase(value);\n }\n}\n</code></pre>\n\n<p>I hid the <code>IgnoreCase</code> helper behind a new extension:</p>\n\n<pre><code>public static class StringExtensions\n{\n public static IEquatable<string> AsIgnoreCase(this string str) => (IgnoreCase)str;\n\n private class IgnoreCase : IEquatable<string>\n {\n private IgnoreCase(string value) => Value = value;\n private string Value { get; }\n public bool Equals(string other) => StringComparer.OrdinalIgnoreCase.Equals(Value, other);\n public override bool Equals(object obj) => obj is IgnoreCase ic && Equals(ic.Value);\n public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value);\n public static explicit operator IgnoreCase(string value) => new IgnoreCase(value);\n }\n}\n</code></pre>\n\n<p>The new API can now be used like this:</p>\n\n<pre><code>public class DtoBuilderTest\n{\n [Fact]\n public void Can_create_and_update_object()\n {\n var person =\n DtoUpdater\n .For<Person>()\n .With(x => x.FirstName, \"Jane\")\n .With(x => x.LastName, null)\n //.With(x => x.NickName, \"JD\") // Optional\n .Commit();\n\n Assert.Equal(\"Jane\", person.FirstName);\n Assert.Null(person.LastName);\n Assert.Null(person.NickName);\n\n person =\n person\n .Update()\n .With(x => x.LastName, \"Doe\")\n .With(x => x.NickName, \"JD\")\n .Commit();\n\n Assert.Equal(\"Jane\", person.FirstName);\n Assert.Equal(\"Doe\", person.LastName);\n Assert.Equal(\"JD\", person.NickName);\n }\n\n private class Person\n {\n public Person(string firstName, string lastName, string nickName = null)\n {\n FirstName = firstName;\n LastName = lastName;\n NickName = nickName;\n }\n\n // This ctor should confuse the API.\n public Person(string other) { }\n\n public string FirstName { get; }\n\n public string LastName { get; }\n\n public string NickName { get; set; }\n\n // This property should confuse the API too.\n public string FullName => $\"{LastName}, {FirstName}\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:11:41.917",
"Id": "440813",
"Score": "1",
"body": "This _update/commit_ pattern makes me think we can tune this up to be used as a batch updater with support for multi-level change tracking/reverting implementing _IEditableObject_, _IChangeTracking_ and _IRevertibleChangeTracking_ (up-vote pending btw)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:14:00.070",
"Id": "440814",
"Score": "0",
"body": "@dfhwze haha don't even think of it. Two more refactoring rounds and it can fly to the moon ;-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:15:24.077",
"Id": "440815",
"Score": "0",
"body": "I might ask a follow-up question about it in the weekend o_0 But change tracking is not that trivial /o\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:20:59.617",
"Id": "440816",
"Score": "0",
"body": "@dfhwze I'm not so sure we need all this tracking and undo logic. This demo doesn't show that but usually when you modify an immutable, you pass it so some deeper scope. When it returns, you pick up the previous version for this scope and continue from here. At leat this is how I mostly use immutables. They are convenient to update and use in a new context for a moment. Although it might be useful for debugging."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:22:17.273",
"Id": "440817",
"Score": "0",
"body": "We don't need it for this use case, I want to stea.. 'borrow' your code to make a change tracking API :p Basically, I want your immutable code for my mutable stuff. That's it, I'm no longer making any sense at all ... I'm off to bed, see ya."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:25:10.183",
"Id": "440818",
"Score": "1",
"body": "@dfhwze oh, now I get it. then please do. I could use one of those too. So we'll be borrowing from each other haha"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:31:40.600",
"Id": "226716",
"ParentId": "226694",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226706",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T15:30:18.920",
"Id": "226694",
"Score": "9",
"Tags": [
"c#",
"generics",
"reflection",
"immutability",
"expression-trees"
],
"Title": "Immutable builder and updater"
}
|
226694
|
<p>I have to transform a response into the internal Coordinate record, some of the fields are lists and I need to handle empty lists case.</p>
<p><strong>Records:</strong></p>
<pre><code>newtype GeoResponse =
GeoResponse
{ results :: [ResultResponse]
}
deriving (Eq, Show, Generic)
newtype ResultResponse =
ResultResponse
{ locations :: [LocationResponse]
}
deriving (Eq, Show, Generic)
newtype LocationResponse =
LocationResponse
{ latLng :: CoordinateResponse
}
deriving (Eq, Show, Generic)
data CoordinateResponse =
CoordinateResponse
{ lat :: !Double
, lng :: !Double
}
deriving (Eq, Show, Generic)
</code></pre>
<p><strong>Mapper function:</strong></p>
<pre><code>toCoordinate :: GeoResponse -> Coordinate
toCoordinate (GeoResponse (ResultResponse [LocationResponse (CoordinateResponse lat lng)]:_)) =
Coordinate lat lng
toCoordinate _ = Coordinate 0 0
</code></pre>
<p>So I didn't find a better way to get Coordinate without pattern match, but it looks a bit ugly to me.</p>
<p>Do you have any suggestion to improve my code?</p>
|
[] |
[
{
"body": "<p>Note that, if you just remove the tag <code>Response</code> from all your types (including unifying the types <code>CoordinateResponse</code> and <code>Coordinate</code> which seem like they ought to be a single type), it's already a lot more readable:</p>\n\n<pre><code>toCoordinate :: Geo -> Coordinate\ntoCoordinate (Geo (Result [Location coord]:_)) = coord\ntoCoordinate _ = Coordinate 0 0\n</code></pre>\n\n<p>Also, the <code>Location</code> newtype doesn't seem to be serving any purpose, so maybe <code>Location</code> and <code>Coordinate</code> should just be the same type, too, which would remove a level.</p>\n\n<p>Otherwise, what you've written is pretty idiomatic. It's possible to use <code>coerce</code> to \"cut through\" all of the newtypes, so you could write:</p>\n\n<pre><code>import Data.Coerce\n\ntoCoordinate' :: GeoResponse -> Coordinate\ntoCoordinate' gr = case coerce gr of\n [CoordinateResponse lat lng]:_ -> Coordinate lat lng\n _ -> Coordinate 0 0\n</code></pre>\n\n<p>or if <code>CoordinateResponse</code> and <code>Coordinate</code> were the same type:</p>\n\n<pre><code>toCoordinate' :: Geo -> Coordinate\ntoCoordinate' gr = case coerce gr of\n [coord]:_ -> coord\n _ -> Coordinate 0 0\n</code></pre>\n\n<p>That's obviously shorter, though it may hide what you're doing. It seems important that you are pattern matching against the first of (possibly many) <code>ResultResponse</code> values but requiring that response to consist of a single <code>LocationResponse</code>, and that's not so obvious from this version.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-14T19:29:20.930",
"Id": "232403",
"ParentId": "226698",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T16:22:41.540",
"Id": "226698",
"Score": "1",
"Tags": [
"haskell",
"coordinate-system"
],
"Title": "Dynamic field access in Haskell"
}
|
226698
|
<p>The input is a set of alphabets.</p>
<p>The output is a string of 32 in length.</p>
<p>For any letter in the set if it is preceded by a '¬' we replace the n-th character in our output string with '0', such that n is the position of the letter in the alphabets. If it is not preceded by a '¬' and was there in the set then we replace it with '1', And finally if it wasn't there in the set then we replace it with 'b'.</p>
<p>So for an input like: <code>{'¬g10','d13','ae6','f3','¬aa5','¬bg28','a2','¬af3'}</code></p>
<p>The output is: <code>"1bb1b10bbbbbbbbbbbbbbbbbbb0bbb10"</code></p>
<p>Note that 'd' is the fourth letter and do not have a '¬' before it so we wrote '1' in the fourth character.</p>
<p>Note also that we count 'aa' as the 27th letter and 'ae' as the 31th letter.</p>
<p>For the numbers do not mind them. Treat them like they're not exist!</p>
<p>I came up with this solution to this problem: </p>
<pre class="lang-py prettyprint-override"><code>set = {'¬g10','d13','ae6','f3','¬aa5','¬bg28','a2','¬af3'}
delemiter = 'false'
result = 'b'*32
result = list(result)
set = str(set)
i = 0
while set[i] != '}':
if set[i] == '¬':
delemiter = 'true'
elif set[i] == ',':
delemiter = 'false'
elif set[i+1] >= 'a' and set[i+1] <= 'z' and set[i] >= 'a' and set[i] <= 'z':
i = i+1
if delemiter == 'true':
if set[i] == 'a':
result[26] = '0'
elif set[i] == 'b':
result[27] = '0'
elif set[i] == 'c':
result[28] = '0'
elif set[i] == 'd':
result[29] = '0'
elif set[i] == 'e':
result[30] = '0'
elif set[i] == 'f':
result[31] = '0'
elif delemiter == 'false':
if set[i] == 'a':
result[26] = '1'
elif set[i] == 'b':
result[27] = '1'
elif set[i] == 'c':
result[28] = '1'
elif set[i] == 'd':
result[29] = '1'
elif set[i] == 'e':
result[30] = '1'
elif set[i] == 'f':
result[31] = '1'
elif set[i] >= 'a' and set[i] <= 'z':
if delemiter == 'true':
if set[i] == 'a':
result[0] = '0'
elif set[i] == 'b':
result[1] = '0'
elif set[i] == 'c':
result[2] = '0'
elif set[i] == 'd':
result[3] = '0'
elif set[i] == 'e':
result[4] = '0'
elif set[i] == 'f':
result[5] = '0'
elif set[i] == 'g':
result[6] = '0'
elif set[i] == 'h':
result[7] = '0'
elif set[i] == 'i':
result[8] = '0'
elif set[i] == 'j':
result[9] = '0'
elif set[i] == 'k':
result[10] = '0'
elif set[i] == 'l':
result[11] = '0'
elif set[i] == 'm':
result[12] = '0'
elif set[i] == 'n':
result[13] = '0'
elif set[i] == 'o':
result[14] = '0'
elif set[i] == 'p':
result[15] = '0'
elif set[i] == 'q':
result[16] = '0'
elif set[i] == 'r':
result[17] = '0'
elif set[i] == 's':
result[18] = '0'
elif set[i] == 't':
result[19] = '0'
elif set[i] == 'u':
result[20] = '0'
elif set[i] == 'v':
result[21] = '0'
elif set[i] == 'w':
result[22] = '0'
elif set[i] == 'x':
result[23] = '0'
elif set[i] == 'y':
result[24] = '0'
elif set[i] == 'z':
result[25] = '0'
elif delemiter == 'false':
if set[i] == 'a':
result[0] = '1'
elif set[i] == 'b':
result[1] = '1'
elif set[i] == 'c':
result[2] = '1'
elif set[i] == 'd':
result[3] = '1'
elif set[i] == 'e':
result[4] = '1'
elif set[i] == 'f':
result[5] = '1'
elif set[i] == 'g':
result[6] = '1'
elif set[i] == 'h':
result[7] = '1'
elif set[i] == 'i':
result[8] = '1'
elif set[i] == 'j':
result[9] = '1'
elif set[i] == 'k':
result[10] = '1'
elif set[i] == 'l':
result[11] = '1'
elif set[i] == 'm':
result[12] = '1'
elif set[i] == 'n':
result[13] = '1'
elif set[i] == 'o':
result[14] = '1'
elif set[i] == 'p':
result[15] = '1'
elif set[i] == 'q':
result[16] = '1'
elif set[i] == 'r':
result[17] = '1'
elif set[i] == 's':
result[18] = '1'
elif set[i] == 't':
result[19] = '1'
elif set[i] == 'u':
result[20] = '1'
elif set[i] == 'v':
result[21] = '1'
elif set[i] == 'w':
result[22] = '1'
elif set[i] == 'x':
result[23] = '1'
elif set[i] == 'y':
result[24] = '1'
elif set[i] == 'z':
result[25] = '1'
i += 1
result = ''.join(result)
print(result)
</code></pre>
<p>I am asking for a review to this code. Thank you</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T01:09:46.627",
"Id": "442716",
"Score": "1",
"body": "This question has been [mentioned on Meta](https://codereview.meta.stackexchange.com/q/9298/9357)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T01:11:25.177",
"Id": "442717",
"Score": "4",
"body": "Downvoted, because several comments on your [deleted older question](https://codereview.stackexchange.com/questions/226174/what-is-the-better-solution-to-this) asked about the context and motivation for this code, and those requests remain unsatisfied."
}
] |
[
{
"body": "<p><strong>DRY Code</strong><br>\nThe code is very long when it doesn't need to be, and it is very repetitive.</p>\n\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n\n<p>You can use a data structure as an array to contain the alphabet. If the current letter in the array then if delimiter is false, otherwise return true. If the current letter is not in the alphabet move on to the next letter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:00:06.320",
"Id": "226701",
"ParentId": "226699",
"Score": "3"
}
},
{
"body": "<p>I've factored out the logic for transforming the cell-like string to a number, for example a7 -> 1, z8 -> 26, aa12 > 27 and so on. I've also factored out the logic to replace a character if it falls within the length of the target string.\nFinally I've parametrised the length of the input string. This approach makes your code more readable and easier to test and to maintain.</p>\n\n<pre><code>import string\n\n\ndef str_to_num(col):\n \"\"\"\n Converts the character part of a cell-like string to number.\n For example, for col='aa3', it returns 27.\n \"\"\"\n num = 0\n for c in col:\n if c in string.ascii_letters:\n num = num * 26 + ord(c.upper()) - ord('A') + 1\n return num\n\n\ndef replace_char(txt, pos, char):\n \"\"\"Replaces character in txt at position pos with char\"\"\"\n result = list(txt)\n if pos < len(txt):\n result[pos] = char\n return ''.join(result)\n\n\ndef func(elems, length=32):\n \"\"\"\n Takes an iterable elems and a length and returns a string of that length\n with all b's, except of characters at indices that are including in elems\n in the form of cell-like notation. For elements in elems that start with\n a '¬' it replaces a 'b' with a '0', for the rest it replaces a 'b' with\n an '1'.\n \"\"\" \n output = 'b' * length\n for elem in elems:\n pos = str_to_num(elem)\n if elem.startswith('¬'):\n elem = elem.split('¬')[1]\n output = replace_char(output, pos-1, '0')\n else:\n output = replace_char(output, pos-1, '1')\n return output\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>>> input_set = {'¬g10', 'd13', 'ae6', 'f3', '¬aa5', '¬bg28', 'a2', '¬af3'}\n>> result = func(input_set, length=32)\n>> print(result)\n1bb1b10bbbbbbbbbbbbbbbbbbb0bbb10\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:53:15.027",
"Id": "226708",
"ParentId": "226699",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226708",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T16:36:56.933",
"Id": "226699",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"strings",
"converting"
],
"Title": "Converting a set into a string"
}
|
226699
|
<p>I am trying to get better at Powershell and was wondering if I could get some advice on how to make this code more efficient/cleaner/anything.</p>
<p>This code is intended to launch three batch windows running robocopy at the same time with unique log names.</p>
<p>I looked into using a foreach loop but wasn't sure how I could do that with so many unique variables. Thinking back, I probably could have imported each source, destination and log name into a CSV though but this may have been cleaner/better because it's all in one file instead.</p>
<pre><code># sets the files to exclude
$defaultDirExclusionSet = '"$Recycle.Bin" "System Volume Information"'
# setting the filename perameter so that we have some timestamps.
$filedate = "$(get-date -format 'yyyy-MM-dd-HH-MM')" # we can remove the HH and MM later... have this on now for testing.
#options for robocopy
$RoboOptions = "/MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD $defaultDirExclusionSet /NP /TEE"
#main fileshares
$source = "\\server1\D$\Shares"
$destination = "\\server2\D$"
$logname = "fileshare"
#Citrix User Store Shares
$source1 = "\\server1\D$\CitrixUserStore"
$destination1 = "\\server2\E$\CitrixUserStore"
$logname1 = "ctxusrshare"
#Citrix User Redir Shares
$source2 = "\\server1\D$\CitrixUserRedir"
$destination2 = "\\server2\E$\CitrixUserRedir"
$logname2 = "ctxusrredir"
##### launch all at once. fix the first line before using.
Start-Process robocopy.exe -ArgumentList "$($source) $($destination) $($RoboOptions.split(' ')) /log+:c:\robocopylogs<span class="math-container">\$($logname)_$($filedate).txt"
Start-Process robocopy.exe -ArgumentList "$($source1) $($destination1) $($RoboOptions.split(' ')) /log+:c:\robocopylogs\$</span>($logname1)_$($filedate).txt"
Start-Process robocopy.exe -ArgumentList "$($source2) $($destination2) $($RoboOptions.split(' ')) /log+:c:\robocopylogs\$($logname2)_$($filedate).txt"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:15:29.393",
"Id": "440737",
"Score": "2",
"body": "It is a good question, but the title should probably be changed to \"Powershell script that executes robocopy in 3 separate batch windows\". See the code review guidlines at https://codereview.stackexchange.com/help/how-to-ask."
}
] |
[
{
"body": "<ul>\n<li>If you don't want an external csv file,<br>\nuse an internal one - simulated with a here string and <code>ConvertFrom-Csv</code></li>\n<li>in a date format specifier upper case <code>MM</code> are for month, minutes are lower case <code>mm</code></li>\n<li>the following script has several variable names shorted to keep line length down.</li>\n<li>the final command is only echoed / commented out.</li>\n</ul>\n\n<hr>\n\n<pre><code>## Q:\\Test\\2019\\08\\23\\sf_226703.ps1\n# sets the files to exclude \n$defaultDirExclusionSet = '\"$Recycle.Bin\" \"System Volume Information\"'\n\n#options for robocopy\n$RoboOpts = \"/MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD $defaultDirExclusionSet /NP /TEE\"\n\n# simulate external csv with a here string and ConvertFrom-Csv\n$RCJobs = @'\ndesc,src,dst,log\n\"main fileshares\",\"\\\\server1\\D$\\Shares\",\"\\\\server2\\D$\",\"fileshare\"\n\"Citrix User Store Shares\",\"\\\\server1\\D$\\CitrixUserStore\",\"\\\\server2\\E$\\CitrixUserStore\",\"ctxusrshare\"\n\"Citrix User Redir Shares\",\"\\\\server1\\D$\\CitrixUserRedir\",\"\\\\server2\\E$\\CitrixUserRedir\",\"ctxusrredir\"\n'@ -split '\\r?\\n' | ConvertFrom-Csv\n\n$RCJobs | Format-Table -Auto\n\n##### launch all at once. fix the first line before using.\nforeach($J in $RCJobs){\n Write-Host -Fore Green \"Starting job $($J.desc)\"\n $Args = '\"{0}\" \"{1}\" {2} /log+:\"C:\\robocopylogs\\{3}_{4:yyyy-MM-dd-HH-mm}.txt\"' -f `\n $J.src,$J.dst,$RoboOpts,$J.log,(Get-Date)\n \"Start-Process robocopy.exe -ArgumentList $Args\"\n #Start-Process robocopy.exe -ArgumentList $Args \n}\n</code></pre>\n\n<p>Sample output without <strong><em>executing</em></strong> RoboCopy.</p>\n\n<pre><code>> Q:\\Test\\2019\\08\\23\\sf_226703.ps1\n\ndesc src dst log\n---- --- --- ---\nmain fileshares \\\\server1\\D$\\Shares \\\\server2\\D$ fileshare\nCitrix User Store Shares \\\\server1\\D$\\CitrixUserStore \\\\server2\\E$\\CitrixUserStore ctxusrshare\nCitrix User Redir Shares \\\\server1\\D$\\CitrixUserRedir \\\\server2\\E$\\CitrixUserRedir ctxusrredir\n\n\nStarting job main fileshares\nStart-Process robocopy.exe -ArgumentList \"\\\\server1\\D$\\Shares\" \"\\\\server2\\D$\" /MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD \"$Recycle.Bin\" \"System Volume Information\" /NP /TEE /log+:\"C:\\robocopylogs\\fileshare_2019-08-23-20-59.txt\"\nStarting job Citrix User Store Shares\nStart-Process robocopy.exe -ArgumentList \"\\\\server1\\D$\\CitrixUserStore\" \"\\\\server2\\E$\\CitrixUserStore\" /MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD \"$Recycle.Bin\" \"System Volume Information\" /NP /TEE /log+:\"C:\\robocopylogs\\ctxusrshare_2019-08-23-20-59.txt\"\nStarting job Citrix User Redir Shares\nStart-Process robocopy.exe -ArgumentList \"\\\\server1\\D$\\CitrixUserRedir\" \"\\\\server2\\E$\\CitrixUserRedir\" /MIR /COPY:DATSOU /ZB /R:1 /W:5 /XD \"$Recycle.Bin\" \"System Volume Information\" /NP /TEE /log+:\"C:\\robocopylogs\\ctxusrredir_2019-08-23-20-59.txt\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:01:25.420",
"Id": "226712",
"ParentId": "226703",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226712",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:06:27.100",
"Id": "226703",
"Score": "5",
"Tags": [
"powershell",
"batch"
],
"Title": "How could I have made this Powershell script that executes robocopy code better"
}
|
226703
|
<p>I have written a Regex to validate XML/HTML, along with any attributes. It aims to:</p>
<ul>
<li>Match any XML-like text</li>
<li>Not match any unclosed tags</li>
<li>Adapt for any spacing, newlines, etc.</li>
<li>Be as generous as possible: match as <em>much</em> as possible.</li>
<li><em>Match self-closing tags</em> (in edit)</li>
</ul>
<p>I initially created this to validate API requests I was making, to make sure the request was successfully completed without missing bytes. <strong>I am aware this is ridiculously stupid and ineffective method to do this, but it's more of an experiment with Regex. I'm not interested in being told to use a different method, that's not what I'm aiming to do.</strong> However, now I'm wondering if:</p>
<ul>
<li>There is any smart way to make it shorter</li>
<li><del>Known bug: you have to escape both types of speech mark all the time: i.e <code>placeholder="i 'love' regex"</code> will not be matched, you have to do <code>placeholder="i \'love\' regex"</code>, despite that fact that it's a <code>'</code> inside a <code>"</code>.</del> <em>fixed with a conditional operator, which I discovered by accident in the Regexr cheatsheet.</em>
<ul>
<li>Known bug with this fix: seems to work with <code>"'"</code>, but not with <code>'"'</code>. Even weirder, sometimes it fails when the speech marks inside a tag are of different types: e.g, <code><input placeholder="wait, 'no'?" /></code> works fine, but <code><input type='text' placeholder="wait, 'no'?" /></code> (note the use of <code>'</code> the first time) doesn't.</li>
</ul></li>
<li><del>There is some easy way to allow for implicitly closed tags, e.g <code><input></code> without having to do a closing tag - <code><input type="text"></input></code> (<em>is</em> currently matched) vs <code><input type="text" /></code> (not matched by this Regex)</del> <em>Done! See revision history for previous version without this feature.</em></li>
</ul>
<p>I'm very new to Regex, and especially to <code>?R</code> recursion, so I'm not sure how to go about most of these points. Of course, other general comments are also appreciated. Note that this will not run in normal JS browser Regex, so try either with the <code>regex</code> (not <code>re</code>) module in Python, or using the PCRE flavour on <a href="https://regexr.com/4jp65" rel="nofollow noreferrer">RegExr</a> (link goes to test for my Regex).</p>
<p>Anyway, here's the current Regex:</p>
<pre class="lang-regex prettyprint-override"><code><([\w!:[\]-]+)( +[\w!:[\]-]+( ?= ?((\d+)|(((')|")([ !#-&(-~]|(?(?=\8)"|')|\\\7)*([ !#-&(-[\]-~]|(?(?=\8)"|')|\\\7)\7)))?)*((>([^<])*((?>([^<])*(?R))*)([^<])*<\/\1>)|(\s*\/\s*>))
</code></pre>
<p>Or, formatted:</p>
<pre class="lang-py prettyprint-override"><code>< # Open the tag
([\w!:[\]-]+) # Match the tag name, save to capture group
( # Define group to match attributes
\ + # Match any amount of whitespace, between the tag name and attribute name
[\w!:[\]-]+ # Match the attribute name
( # Define group to match attribute value
\ ? # Match any amount of whitespace, between the attribute name and equals sign
= # Match the equals
\ ? # Match any amount of whitespace, between the equals sign and the attribute value
( # Define a group for the attribute value
(\d+) # Match a number...
| # ... or ...
( # ... match a string
( # Match speech mark, and record speech mark type in capture group
(") # Specifically record if it is a double quote for later
| # but also match (and save)
' # single quotes.
)
( # Define a group to match string contents
[ !#-&(-~] # Match any character, excluding all quotes
| # ... or ...
(? # define a conditional to...
(?= # check if...
\8 # the double quote group is empty, i.e it is a not a double quote, i.e it is a single quote
)
" # if True, allow for inclusion of double quotes in the string (since 'text"text' is fine, but 'text'text' is not)
| # if False,
' # allow for inclusion of single quotes in the string (since "text'text" is fine, but "text"text" is not)
)
| # ... or ...
\\ # Match an _escaped_...
\7 # speech mark
)
* # Match as many as possible
( # Create a group to validate last character, to avoid it being a backslash (see (1) below)
[ !#-&(-[\]-~] # Match any character, _except_ backslash
| # ... or ...
(? # define a conditional to...
(?= # check if...
\8 # the double quote group is empty, i.e it is a not a double quote, i.e it is a single quote
)
" # if True, allow for inclusion of double quotes in the string (since 'text"text' is fine, but 'text'text' is not)
| # if False,
' # allow for inclusion of single quotes in the string (since "text'text" is fine, but "text"text" is not)
)
| # ... or ...
\\ # Match an _escaped_...
\7 # speech mark
)
\7 # Match closing speech mark
)
)
) # End attribute value group
? # Make attribute value optional, to allow for boolean attributed - e.g `<input type="text" disabled></input>`
)
* # Allow for as many attributes as possible
( # Set for choosing between two possible endings for the name/attributes, which currently looks like '<tagname attr="text"' - either, '>texthere</tagname>', or simply '/>'
( # First possible ending, with text/nesting inside tag, and closing tag at end
> # End opening tag
([^<]) # Allow for text in tag, before other nested tags
*
( # Open recursion contents group
( # Define atomic recursion group
?> # Make group atomic
([^<])
* # Allow as much text as required _between_ tags (e.g allow <a>some text <span>some more text</span>__This line allows for this text here!__<span>other text</span>also text</a>)
(?R) # Call recursion group
)
* # Allow recursion group to loop as many times as required
)
([^<]) # Allow for text in tag, after all other nested tags but before closing tag
*
< # Open closing tag
\/ # Match '/' character
\1 # Refer back to tag name
> # End closing tag
)
| # Or,
( # second possible ending, with a self-closing tag - simply match '/>'
\s # allow for spaces before '/'
*
\/ # Match '/'
\s # Allow for spaces after '/', but before '>'
*
> # Match '>'
)
)
</code></pre>
<p><sup>(1): I'd also like to optimise the first string-value capture group to automatically not match backslashes on the last character, but I can't figure out a way without repeating the entire group just without the backslash character.</sup></p>
<p>Any help or questions are appreciated. Like I said, I'm quite new to Regexes, so if there are some unspoken rules/standards I've missed, I'd be happy to hear them!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:19:19.093",
"Id": "440786",
"Score": "4",
"body": "See [RegEx match open tags](https://stackoverflow.com/a/1732454/3690024) and also [html.parser](https://docs.python.org/3/library/html.parser.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:27:36.233",
"Id": "440787",
"Score": "0",
"body": "@AJNeufeld I realise this isn't the most efficient method; in my original implementation I *did* in fact use `html.parser` in an array to track opening and closing tags. However, before I realised the existance of the module, I tried with Regex, so I'm wondering, assuming the module didn't exist, how well this regex would hold up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:34:21.057",
"Id": "440788",
"Score": "2",
"body": "Well, as you noticed with self-closing tags, it doesn't hold up. Beyond that, `<![CDATA[...]]>` would likely bring it to its knees."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T14:39:58.663",
"Id": "440883",
"Score": "0",
"body": "@AJNeufeld I've improved it now to allow for self-closing tags, but I don't understand what you mean by the `<![CDATA[...]]>` example. As long as the tag is closed, it should work fine with whatever you put in it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T16:45:54.007",
"Id": "440900",
"Score": "1",
"body": "@ggorlen, regexes are not regular expressions. Exceedingly few regex libraries are limited to matching regular languages. The proof of impossibility you reference is emphatically **not** for a regex with explicit recursion capabilities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T17:02:32.180",
"Id": "440902",
"Score": "0",
"body": "@PeterTaylor I see, thanks for clarifying. Even so, it still seems pretty foolhardy to attempt this."
}
] |
[
{
"body": "<p>It is simply not feasible to just parse the full set of (X|HT)ML with regex. I can't provide too much feedback on your solution as it simply isn't the correct solution for the problem, but I can provide plenty of examples where it fails to match valid input.</p>\n\n<ol>\n<li><code><tag attr='\"'></tag></code></li>\n<li><code><tag attr=\"\"></tag></code></li>\n<li><code><tag attr=attr></tag></code> - fine in HTML</li>\n<li><code><tag><!-- html comment --></tag></code></li>\n<li><code><tag> </tag ></code></li>\n</ol>\n\n<p>You also need to decide - XML or HTML? Each brings its own set of problems. How should this be parsed? <code><tag><![CDATA[</tag>]]></tag></code>. In XML, this is the equivalent of <code><tag>&lt;/tag&gt;</tag></code>. In HTML, <code><. I've rolled back the changes you made after this answer was posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T19:03:57.353",
"Id": "440914",
"Score": "0",
"body": "@PeterTaylor OK, see the edit I've just made."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T16:48:45.517",
"Id": "226750",
"ParentId": "226704",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:09:00.677",
"Id": "226704",
"Score": "5",
"Tags": [
"python",
"beginner",
"regex",
"validation",
"xml"
],
"Title": "Regex XML validator"
}
|
226704
|
<p>I got caught in the trap of implementing my own data structure. I've created a very general tree structure, where each node gets one parent, some children, and holds a value.</p>
<p>I'm mostly looking for advice on how to make this code more idiomatic, but also functionality that might be missing from this class, or that isn't necessary. I would also like thoughts on how idiomatic the traverse function is, and if there's a better way to implement it.</p>
<pre><code>function Node(value = 0, children = []) {
this.value = value;
this.children = children;
this.parent = undefined;
}
Node.from = function(node) {
let that = Object.assign(new Node(), node);
that.parent = undefined;
that.children = node.children.map(n => (Node.from(n), n.parent = that));
return that;
};
Node.prototype.add = function(...children) {
for (child of children) {
child.parent = this;
this.children.push(child);
}
};
Node.Traversal = {
BreadthFirst: 1,
DepthFirst: 2
};
Node.prototype.traverse = function(callback, mode = Node.Traversal.BreadthFirst) {
if (mode == Node.Traversal.BreadthFirst) {
let nodes = [this];
while (nodes.length > 0) {
const current = nodes.shift();
callback(current);
nodes = nodes.concat(current.children);
}
} else if (mode == Node.Traversal.DepthFirst) {
callback(this);
this.children.forEach(n => n.traverse(callback, false));
}
return this;
};
Node.prototype.reduce = function(callback, initial, mode) {
let acc = initial;
this.traverse(n => acc = callback(acc, n), mode);
return acc;
};
Node.prototype.every = function(callback) {
return this.reduce((a, n) => a && callback(n), true);
};
Node.prototype.some = function(callback) {
return this.reduce((a, n) => a || callback(n), false);
};
Node.prototype.find = function(callback, mode) {
return this.reduce((a, n) => a || (callback(n)? n: false), false, mode);
};
Node.prototype.includes = function(value) {
return this.some(n => n.value === value);
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:10:26.537",
"Id": "440791",
"Score": "0",
"body": "Hello, could you maybe explain in more detail what your tree structure is, because there are many of them. This would help having a better review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:11:42.593",
"Id": "440792",
"Score": "0",
"body": "The goal is to provide an extremely general tree. Each node should have one parent, some number of children, and hold a value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:13:09.960",
"Id": "440794",
"Score": "1",
"body": "Alright that's a pretty good explanation, you should add it to your post. There's a close vote on your question, I suspect this is the reason. I wouldn't worry if I were you, in the event your question was to get closed, I'm sure it would be reopened, it's a good question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:19:26.280",
"Id": "440797",
"Score": "0",
"body": "How can I know if my question has a close vote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:23:18.457",
"Id": "440799",
"Score": "0",
"body": "Where can I see the close votes? Shouldn't the question author be able to see close votes on their question, even if they have low rep?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:29:03.173",
"Id": "440800",
"Score": "1",
"body": "here's a post about it: https://codereview.meta.stackexchange.com/questions/8744/wouldnt-it-be-more-useful-to-notify-ops-automatically-about-close-votes-instea"
}
] |
[
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>Your code is compact and well organised. Reusing <code>traverse</code> and <code>reduce</code> allows for easy extensibility.</li>\n<li>Your <code>tree</code> could be a graph, or even worse a cyclic one: <code>traverse</code> could iterate to infinity.</li>\n<li>By adding additional methods such as <code>descendants</code> and <code>ancestors</code> you could guard that the structure remains a tree. When adding a node, it cannot have a parent, it cannot be the node self, it cannot be a descendant or an ancestor.</li>\n<li>You're allowing BFS and DFS, but only in <em>pre-order</em>. I would also include <em>post-order</em> (and perhaps also <em>in-order</em>).</li>\n<li>Adding additional properties in a node might be useful for certain use cases: <code>root</code>, <code>depth</code>, <code>height</code>, <code>isleaf</code>, <code>isbranch</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:05:21.507",
"Id": "440783",
"Score": "0",
"body": "inorder traversal makes sense only for a binary tree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:15:30.547",
"Id": "440785",
"Score": "0",
"body": "@ScottSauyet For me, the pre- and post-order are the most important ones. The in-order probably doesn't have that many applications here. I would agree with you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:00:42.820",
"Id": "440790",
"Score": "1",
"body": "I do use `inorder` reasonably often, but it simply makes no sense when you don't have specific `left` and `right` children."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:12:32.920",
"Id": "440793",
"Score": "0",
"body": "If I am going to add postorder traversal, would it make sense to split `traverse` into two different functions (one for breadth-first and one for depth-first)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:13:24.310",
"Id": "440795",
"Score": "0",
"body": "Yes with an optional parameter _order_; see the other answer how the split could be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:18:05.880",
"Id": "440796",
"Score": "2",
"body": "But I wouldn't split all other methods into different search strategy and order. Does it really matter how you search for items (maybe it does)? But when executing actions when walking the tree, strategy and order definately must be available parameters/split methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:33:04.293",
"Id": "440801",
"Score": "0",
"body": "@dfhwze: Agreed, I wouldn't bother unless there is some real reason to search or whatever in the order of a different traversal. That would also require updating the traversals to allow for early escapes. It's not worth it without a powerful reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:55:05.637",
"Id": "440807",
"Score": "0",
"body": "@dfhwze It can matter when searching for items, because `find` only returns the first element that it matches (in order to act like `find` for arrays)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:58:09.773",
"Id": "440809",
"Score": "0",
"body": "Ah good call didn't think about that one"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T18:31:24.093",
"Id": "226711",
"ParentId": "226709",
"Score": "2"
}
},
{
"body": "<p>This is overall well-thought-out, well-organized, and well-written.</p>\n<p>There's at least one bug, and one oversight that I would consider a bug:</p>\n<ul>\n<li><p>In <code>traverse</code> your recursive call is passing the wrong second parameter:</p>\n<pre><code>} else if (mode == Node.Traversal.DepthFirst) {\n callback(this);\n this.children.forEach(n => n.traverse(callback, <b>false</b>));\n}</code></pre>\n<p>should read</p>\n<pre><code>} else if (mode == Node.Traversal.DepthFirst) {\n callback(this);\n this.children.forEach(n => n.traverse(callback, <b>Node.Traversal.DepthFirst</b>));\n}</code></pre>\n</li>\n<li><p>in <code>add</code> you don't declare <code>child</code>. Presumably is should read <code>for (<b>let</b> child of children)</code></p>\n</li>\n</ul>\n<p>As to design decisions, there are several things you might want to consider.</p>\n<ul>\n<li><p><code>add</code> might be improved with <code>return this</code>.</p>\n</li>\n<li><p>I think a <code>clone</code> method might be a more common choice here than a static <code>from</code> function.</p>\n</li>\n<li><p>You might find the ES6 <code>class</code> syntax slightly more explicit. I wasn't a big fan of it when it was proposed, and I'm still not; I don't like the implication it suggests that JS OOP is particularly similar to Java/C# style OOP. But it does carry a bit less cruft than the constant repetition of <code>Node.prototype</code>.</p>\n</li>\n<li><p>Rather than use an enumeration of traversal types, you might want to consider simply using functions instead. That is,</p>\n<pre><code>Node.Traversal = {\n BreadthFirst: function(callback) {\n let nodes = [this];\n while (nodes.length > 0) {\n const current = nodes.shift();\n callback(current);\n nodes = nodes.concat(current.children);\n } \n },\n DepthFirst: function(callback) {\n callback(this);\n this.children.forEach(n => n.traverse(callback, Node.Traversal.DepthFirst));\n }\n};\n\nNode.prototype.traverse = function(callback, traversal = Node.Traversal.BreadthFirst) \n{\n traversal.call(this, callback);\n return this;\n};\n</code></pre>\n<p>This would make it easier for you to add another traversal, since you only have to do it in one place, and it lets users supply their own instead.</p>\n</li>\n<li><p>Perhaps most importantly, you might want to drop the <code>parent</code> property. You do not use it anywhere except in building or cloning a tree, and it can lead to real problems. For instance, if you cloned a tree with <code>from</code> (and therefore ended up with non-empty parent nodes), you will not be able to call <code>JSON.stringify</code> on it due to the cyclic nature.</p>\n</li>\n</ul>\n<p>Putting this all together, here's an alternate version:</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>console.clear() \n\nclass Node {\n constructor (value = 0, children = []) {\n this.value = value;\n this.children = children;\n }\n \n static Traversal = {\n BreadthFirst: function(callback) {\n let nodes = [this];\n while (nodes.length > 0) {\n const current = nodes.shift();\n callback(current);\n nodes = nodes.concat(current.children);\n } \n },\n DepthFirst: function(callback) {\n callback(this);\n this.children.forEach(n => n.traverse(callback, Node.Traversal.DepthFirst));\n }\n }\n \n clone () {\n let that = Object.assign(new Node(), this);\n that.children = this.children.map(n => n.clone());\n return that;\n }\n \n add (...children) {\n for (let child of children) {\n this.children.push(child);\n }\n return this;\n }\n\n traverse (callback, traversal = Node.Traversal.BreadthFirst) {\n traversal.call(this, callback);\n return this;\n }\n\n reduce (callback, initial, mode) {\n let acc = initial;\n this.traverse(n => acc = callback(acc, n), mode);\n return acc;\n }\n\n every (callback) {\n return this.reduce((a, n) => a && callback(n), true);\n }\n\n some (callback) {\n return this.reduce((a, n) => a || callback(n), false);\n }\n\n find (callback, mode) {\n return this.reduce((a, n) => a || (callback(n)? n: false), false, mode);\n }\n\n includes (value) {\n return this.some(n => n.value === value);\n } \n}\n\nconst tree = new Node ('A', [\n new Node(' B', [\n new Node(' D'),\n new Node(' E', [\n new Node(' G'),\n ]),\n new Node(' F')\n ]),\n new Node(' C') \n])\n\ntree.children[0].children[2].add(new Node(' H')).add(new Node(' I'))\n\nconst log = ({value}) => console.log(value)\nconsole.log('===============================')\nconsole.log('Breadth-first')\nconsole.log('===============================')\ntree.traverse(log)\nconsole.log('===============================')\nconsole.log('Depth-first')\nconsole.log('===============================')\ntree.traverse(log, Node.Traversal.DepthFirst)\nconsole.log('===============================')\nconsole.log('Clone, Breadth-first')\nconsole.log('===============================')\ntree.clone().traverse(log)\nconsole.log('===============================')\nconsole.log('Clone, Depth-first')\nconsole.log('===============================')\ntree.clone().traverse(log, Node.Traversal.DepthFirst)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:06:16.623",
"Id": "440812",
"Score": "0",
"body": "Is there a way to move `Node.traversal` inside the class block? It feels weird and too separate from the rest of the functions right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T00:50:06.247",
"Id": "440952",
"Score": "0",
"body": "I agree that it's odd. It's one of the many reasons that I don't like the current `class` syntax. There is now a widely supported static *method* syntax, but nothing for other properties. I've never really tried to learn why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-26T17:56:25.523",
"Id": "509090",
"Score": "0",
"body": "+1 For the class version"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-26T18:03:15.313",
"Id": "509092",
"Score": "0",
"body": "@AlexF There is now, you can use static for properties `static Traversal = {\n BreadthFirst(callback) {... }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-26T18:13:57.673",
"Id": "509095",
"Score": "0",
"body": "@Tofandel: Good to know. Updated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-27T14:19:03.637",
"Id": "510170",
"Score": "0",
"body": "@ScottSauyet Forgot to remove the old one ;) A suggestion on the add method as well `if (child instanceof Node) {\n this.children.push(child);\n } else {\n this.children.push(new Node(child));\n }`\nand in the constructor `this.add(...children);` (you will need to initialize the children property in the class) `children = [];`\nSo you don't have to write `new Node` every time when writing a tree"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-27T20:50:19.637",
"Id": "510208",
"Score": "0",
"body": "@Tofandel: I removed the redundant code. The other suggestion is less likely to me. I'd suggest that you add another answer with that if you find it important. Feel free to start from this code if you want. I'm much more of a FP person than an OOP one, but if I do OOP, I prefer consistent interfaces -- either always use `new` or never use it. If I were to write this for myself and not a code review, I would use just functions, no classes, no `new`s anywhere. But that's not what this answer is for."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T19:59:43.433",
"Id": "226713",
"ParentId": "226709",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "226713",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T17:56:13.323",
"Id": "226709",
"Score": "4",
"Tags": [
"javascript",
"tree",
"reinventing-the-wheel",
"breadth-first-search",
"depth-first-search"
],
"Title": "Javascript Tree Class"
}
|
226709
|
<p>I am a member of a university team designing a nanosatellite.
We decided to implement our own (more lite) logging library to use, instead of, say, Google's <code>glog</code>, <code>spdlog</code>, <code>plog</code> and <code>Boost::Log</code>.</p>
<ul>
<li>The concept of different log levels is introduced, as a means of dividing the log messages into subcategories, according to their severity and whether they were expected to occur.</li>
<li>Furthermore, there will be a "global log level" that can be defined.
Everything less severe than the severity set as the global log level, will <em>not</em> be logged.</li>
</ul>
<p>Due to obvious restrictions, it is imperative that log calls below the global log level get optimized away at compile time.</p>
<p>The first attempt was something like this (single header file):
log levels:</p>
<pre class="lang-cpp prettyprint-override"><code>// We can set the global log level by defining one of these
#if defined LOGLEVEL_TRACE
#define LOGLEVEL Logger::trace
#elif defined LOGLEVEL_DEBUG
#define LOGLEVEL Logger::debug
#elif defined LOGLEVEL_INFO
[...]
#else
#define LOGLEVEL Logger::disabled
#endif
</code></pre>
<p>the levels themselves are <code>enum</code> members:</p>
<pre class="lang-cpp prettyprint-override"><code>enum LogLevel {
trace = 32, // Very detailed information, useful for tracking the individual steps of an operation
debug = 64, // General debugging information
info = 96, // Noteworthy or periodical events
[...]
};
</code></pre>
<p>A <code>operator<<</code> overload for better readability:</p>
<pre class="lang-cpp prettyprint-override"><code>template <class T>
Logger::LogEntry& operator<<(Logger::LogEntry& entry, const T value) {
etl::to_string(value, entry.message, entry.format, true);
return entry;
}
</code></pre>
<p>And the macro-<code>constexpr</code> sorcery to make the compiler do what we want:</p>
<pre class="lang-cpp prettyprint-override"><code>#define LOG(level)
if (Logger::isLogged(level)) \
if (Logger::LogEntry entry(level); true) \
entry
// [...]
static constexpr bool isLogged(LogLevelType level) {
return static_cast<LogLevelType>(LOGLEVEL) <= level;
}
</code></pre>
<p>There were many issues with this code (see the <a href="https://gitlab.com/acubesat/obc/ecss-services/merge_requests/44#7f70288c0af0c93596020b4a0cf98732bd506151" rel="nofollow noreferrer">MR discussion</a> for more).</p>
<ul>
<li>A call operator to the <code>enum LogLevel</code> has been added to return a new <code>static LogEntry</code>.</li>
<li>It is <code>inline</code>d to force <code>const</code> propagation at <code>-O1</code>.</li>
<li>Two <code>LogEntry</code> <code>enums</code> have been created.</li>
<li>The second one is a <code>nop</code> with everything <code>inline</code>.</li>
<li><code>if constexpr</code> syntax has been added.</li>
</ul>
<p>and more (see <a href="https://gitlab.com/acubesat/obc/ecss-services/merge_requests/44#note_206390254" rel="nofollow noreferrer">here</a> and below for justification.)</p>
<p>That's the (chopped) state of the code currently:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cstdint>
#include <string>
#define LOGLEVEL_EMERGENCY
#if defined LOGLEVEL_TRACE
#define LOGLEVEL Logger::trace
#elif defined LOGLEVEL_DEBUG
#define LOGLEVEL Logger::debug
#elif defined LOGLEVEL_INFO
#define LOGLEVEL Logger::info
#elif defined LOGLEVEL_NOTICE
#define LOGLEVEL Logger::notice
#elif defined LOGLEVEL_WARNING
#define LOGLEVEL Logger::warning
#elif defined LOGLEVEL_ERROR
#define LOGLEVEL Logger::error
#elif defined LOGLEVEL_EMERGENCY
#define LOGLEVEL Logger::emergency
#else
#define LOGLEVEL Logger::disabled
#endif
#define LOG_TRACE (LOG<Logger::trace>())
#define LOG_DEBUG (LOG<Logger::debug>())
#define LOG_INFO (LOG<Logger::info>())
#define LOG_NOTICE (LOG<Logger::notice>())
#define LOG_WARNING (LOG<Logger::warning>())
#define LOG_ERROR (LOG<Logger::error>())
#define LOG_EMERGENCY (LOG<Logger::emergency>())
class Logger {
public:
Logger() = delete;
typedef uint8_t LogLevelType;
enum LogLevel : LogLevelType {
trace = 32,
debug = 64,
info = 96,
notice = 128,
warning = 160,
error = 192,
emergency = 254,
disabled = 255,
};
enum class NoLogEntry {};
struct LogEntry {
std::string message = "";
LogLevel level;
explicit LogEntry(LogLevel level);
~LogEntry();
LogEntry(LogEntry const&) = delete;
template <class T>
Logger::LogEntry& operator<<(const T value) noexcept {
message.append(value);
return *this;
}
Logger::LogEntry& operator<<(const std::string& value);
};
static constexpr bool isLogged(LogLevelType level) {
return static_cast<LogLevelType>(LOGLEVEL) <= level;
}
static void log(LogLevel level, std::string & message);
};
template <Logger::LogLevel level>
constexpr inline auto LOG() {
if constexpr (Logger::isLogged(level)) {
return Logger::LogEntry(level);
} else {
return Logger::NoLogEntry();
}
};
template <typename T>
[[maybe_unused]] constexpr Logger::NoLogEntry operator<<(const Logger::NoLogEntry noLogEntry, T value) {
return noLogEntry;
}
int main() {
LOG_NOTICE << "I am getting optimized away!";
LOG_EMERGENCY << "I am not getting optimized away, and rightfully so";
return 0;
}
</code></pre>
<p>As you can see in e.g.<a href="https://godbolt.org/z/lnLFy-" rel="nofollow noreferrer">Compiler Explorer</a>, the <code>LOG_NOTICE</code> is getting optimized away at <code>-O1</code>.</p>
<p>Do you have any suggestions?</p>
<ul>
<li>Caveats and pitfalls I might have missed?</li>
<li>Better ways to implement this?</li>
<li>Ways to decrease overhead?</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n<p>Due to obvious restrictions, it is imperative that log calls below the global log level get optimized away at compile time.</p>\n</blockquote>\n<p>If such restrictions exist, they are not obvious at all. It sounds like you're designing a piece of software to run <em>exactly once</em> in a <em>completely understood environment</em> — namely a cubesat. ("Completely understood" doesn't mean "completely controlled" — things can still go wrong at runtime — but at least you don't have to worry about different customers with different installation-specific requirements.)</p>\n<ul>\n<li><p>Why does it need the "global log level" to be configurable at all? Surely for each given log message in your current codebase, you can just look at it and ask, "Will this message be helpful during the mission?" If it is, then it should be logged during the mission. If it is not, then it should not be logged during the mission (and since that's the only time this code will run, the message can be entirely removed from the codebase).</p>\n</li>\n<li><p>OTOH, if it's <em>not</em> intuitively obvious which messages will be useful during the mission, then what you need is a <em>runtime</em>-configurable log level. "Oh shoot, something's going wrong. Quick, bump up the log level and let's see if the debug messages can give us a clue!" If the compiler has completely removed all the code that was involved with printing those debug messages, then you're screwed.</p>\n</li>\n</ul>\n<hr />\n<pre><code>enum LogLevel : LogLevelType {\n trace = 32,\n debug = 64,\n info = 96,\n notice = 128,\n warning = 160,\n error = 192,\n emergency = 254,\n disabled = 255, \n};\n</code></pre>\n<p>You've placed <code>disabled</code> in the wrong place (assuming it means "a message which is never ever printed"). Emergency messages should <em>always</em> be printed; error messages usually printed; warnings and notices less often; info and trace messages least often; and then disabled messages <em>never</em>. So in your current scheme, <code>disabled</code> should be <code>0</code>, and if you have a name for <code>255</code>, it should be something like <code>always</code>.</p>\n<p>Except that in practice I'd actually flip the ordering around, so that <code>0</code> messages were always printed (emergency) and <code>255</code> messages were hardly ever printed (debug). That way, when someone said "I'm turning the log level <em>down</em>," it would be clear which way they meant — lower integer number, fewer messages logged.</p>\n<p><a href=\"https://www.rfc-editor.org/rfc/rfc5424#page-11\" rel=\"nofollow noreferrer\">POSIX <code>syslog</code> severity levels work exactly the way I just described: <code>0</code> for emergencies, <code>7</code> for debug traces.</a></p>\n<hr />\n<pre><code> template <class T>\n Logger::LogEntry& operator<<(const T value) noexcept {\n message.append(value);\n\n return *this;\n }\n\n Logger::LogEntry& operator<<(const std::string& value);\n</code></pre>\n<p>Why do you have a separate overload of <code><<</code> for strings? Surely the definition of that overload (not shown in your post) would just be <code>message.append(value)</code> anyway.</p>\n<p>Also, consider using move semantics. Personally, I would write the entire overload set as</p>\n<pre><code> template<class T>\n Logger::LogEntry& operator<<(T value) {\n message.append(std::move(value));\n return *this;\n }\n</code></pre>\n<p>I've removed the incorrect <code>noexcept</code> specifier — <code>std::string::append</code> is totally capable of throwing exceptions. Now, <em>maybe</em> you've decided that you want "out-of-memory during a logging operation" to call <code>std::terminate</code> and crash the whole process, but that really seems like something you should think carefully about. "Best practices for heap-allocation in space" is a whole rabbit hole you might not want to go down, but leaving that aside, just thinking about the behavior <em>with</em> <code>noexcept</code> and <em>without</em> <code>noexcept</code>, I'm pretty sure I'd prefer the behavior <em>without</em> <code>noexcept</code>.</p>\n<p>(Removing <code>noexcept</code> will also decrease your code size, because it won't have to generate code to catch exceptions and call <code>terminate</code>. Rule of thumb: <code>noexcept</code> should go on move-constructors to avoid the vector pessimization; and maybe move-assignment and swap; and nowhere else.)</p>\n<hr />\n<pre><code>template <typename T>\n[[maybe_unused]] constexpr Logger::NoLogEntry operator<<(const Logger::NoLogEntry noLogEntry, T value) {\n return noLogEntry;\n}\n</code></pre>\n<p>It seems silly to use a different idiom here than you already used for the <code>LogEntry</code> case, especially when it means you have to cruft up your code with <code>[[maybe_unused]]</code> to suppress warnings. (Would any compiler actually warn on this code, though?) I would write this as a cut-and-paste of the <code>LogEntry</code> case:</p>\n<pre><code> template<class T>\n Logger::NoLogEntry& operator<<(const T&) {\n // do not log it\n return *this;\n }\n</code></pre>\n<p>I guess for bonus metaprogramming points you could implement the entire thing as</p>\n<pre><code>template<LogLevelType Lvl>\nstruct LogEntry {\n std::string message;\n explicit LogEntry() = default;\n LogEntry(LogEntry const&) = delete;\n ~LogEntry();\n\n template<class T>\n LogEntry& operator<<(T value) {\n if (Lvl <= GLOBAL_LOG_LEVEL) {\n message.append(std::move(value));\n }\n return *this;\n }\n};\n\n#define LOG_ALWAYS LogEntry<0>()\n#define LOG_ERROR LogEntry<10>()\n#define LOG_NOTICE LogEntry<100>()\n#define LOG_INFO LogEntry<200>()\n#define LOG_DEBUG LogEntry<255>()\n</code></pre>\n<p>Notice that I'm not using <code>if constexpr</code> on my compile-time-constant condition there. The compiler will constant-fold it away without my help, and if I do use <code>if constexpr</code> then I don't get the extra compile-time sanity-checking to make sure that the body of the <code>if</code> is well-formed. <code>if constexpr</code> is a tool for template metaprogramming; if you're not doing template metaprogramming then you probably shouldn't be using it.</p>\n<pre><code>LOG_TRACE << 42.0;\n // If I never build your code with GLOBAL_LOG_LEVEL==TRACE,\n // I'll never see any indication that appending a double to a string\n // is ill-formed! This could lead me to write a lot of wrong code\n // that will cost me a lot of fixup time when I eventually do try\n // to build it in TRACE mode.\n</code></pre>\n<hr />\n<p>Watch out! You aren't using the tried-and-true <code>assert</code> idiom here — unwanted calls to <code>LOG_DEBUG</code> don't get macro'ed away. So for example</p>\n<pre><code>#include <assert.h>\nassert(some_expensive_sanity_check()); // produces no code\n\n#include <glog/logging.h>\nLOG(INFO) << (some_expensive_sanity_check() ? "Yes" : "No"); // produces no code\n\n#include <your-thing.h>\nLOG_INFO << (some_expensive_sanity_check() ? "Yes" : "No"); // produces very much code\n</code></pre>\n<p>If you anticipate logging expensive things, then either:</p>\n<ul>\n<li><p>Use the macro tricks from <code>assert</code> or <code>LOG(INFO)</code> to ensure that <code>some_expensive_sanity_check()</code> is macro'ed away when unwanted, or</p>\n</li>\n<li><p>Provide a "getter" for the log level, so that you can explicitly guard expensive log messages:</p>\n<pre><code> #include <your-thing.h>\n if (INFO_IS_LOGGED) {\n LOG_INFO << (some_expensive_sanity_check() ? "Yes" : "No");\n // produces very much code, but the code\n // won't be executed unless INFO_IS_LOGGED\n }\n</code></pre>\n</li>\n</ul>\n<hr />\n<p>TLDR: if you're going to Not-Invented-Here a piece of code, then you owe it to yourself to make your replacement <em>as simple as possible.</em> The more "tricks" you use, the more places you have to screw up and thus end up <em>worse</em> than the established code you could have used for free in the first place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T00:39:57.887",
"Id": "440949",
"Score": "0",
"body": "You are correct in that `LOG_INFO << f()` doesn't go away.\nThe point about the possibility of writing wrong code is valid, CI can help with that.\nThe `enum` reordering feels more intuitive to some, and to other not that much (e.g. [log4j](https://logging.apache.org/log4j/2.x/manual/customloglevels.html) vs [monolog](https://github.com/Seldaek/monolog/blob/master/doc/01-usage.md)).\nAbout the `append`: gah, sorry.\nOur implementation uses ETL's `istring` and `to_string`, I converted it to a regular `std::string` for simplicity, my mistake.\n`noexcept` _increases_ the code size; play with CE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T00:43:37.593",
"Id": "440950",
"Score": "0",
"body": "About the `noLogEntry` `return`: My thought (could be wrong) was that by making two `enum`s, one regular, the other `nop`(with everything) force `inline` (`__attribute__((always_inline))` helps, there's no assembly produced), if you give enough information to the compiler that the class is contained and cannot be accessed from the outside, it will happily nuke the vtables and any calls until it is unsure if something has side effects.\nLastly, the compiler would complain without `[[maybe_unused]]`.\nCheck CE."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T15:34:19.277",
"Id": "226747",
"ParentId": "226715",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226747",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T20:14:30.917",
"Id": "226715",
"Score": "4",
"Tags": [
"c++",
"logging",
"memory-optimization"
],
"Title": "Optimizing away log function calls depending on global log level"
}
|
226715
|
<p>I'd like to know if there's any issues with this implementation of <code>qsort_r</code> (which is not available in all implementations, so I'm trying to provide one that allows to compare values in a dynamic environment) and whether it could be improved upon.</p>
<pre><code>typedef int32_t compare_fn(void *data, const void *val1, const void *val2);
void memswap(void *mem1, void *mem2, size_t size)
{
uint8_t buffer[size];
memcpy(buffer, mem1, size);
memcpy(mem1, mem2, size);
memcpy(mem2, buffer, size);
}
void qsort_r(void *mem_low, void *mem_hi, size_t size, compare_fn compare, void *data)
{
if (mem_low >= mem_hi || mem_hi < mem_low)
{
return;
}
uint8_t *mem_i = mem_low;
uint8_t *mem_j = mem_low;
while (mem_j < mem_hi)
{
if (compare(data, mem_j, mem_hi) < 0)
{
memswap(mem_i, mem_j, size);
mem_i += size;
}
mem_j += size;
}
memswap(mem_i, mem_hi, size);
qsort_r(mem_low, mem_i - size, size, compare, data);
qsort_r(mem_i + size, mem_hi, size, compare, data);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T23:41:39.717",
"Id": "440821",
"Score": "0",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 2"
}
] |
[
{
"body": "<ol>\n<li><p>Pointer-arithmetic on <code>void*</code> is an error in standard c. Yes, gcc/clang have an extension assuming that <code>sizeof(void) == 1</code>. Ramp up your warning-level and specify the standard.</p></li>\n<li><p>That's an interesting method to swap two blocks of memory.</p>\n\n<p>Using a variable length array invites undefined behavior though, as the amount of stack requested is pretty much unbounded.</p>\n\n<p>Anyway, it would probably be a good idea to implement it directly, without such a buffer.</p>\n\n<pre><code>void memswap(void* a, void* b, size_t n) {\n unsigned char *c = a, *d = b;\n while (n--) {\n unsigned char x = *c;\n *c++ = *d;\n *d++ = x;\n }\n}\n</code></pre></li>\n<li><p>I somewhat expected all the elements to be between <code>mem_low</code> and <code>mem_hi</code>. You seem to have an element at <code>mem_hi</code>.<br>\nAt least if you sort a null terminated string, it just sorts the terminator too.</p></li>\n</ol>\n\n<p>Did you try to run your code? See it break a basic test-case <a href=\"https://coliru.stacked-crooked.com/a/6cf415d6ca237932\" rel=\"noreferrer\">live on coliru</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T23:25:28.150",
"Id": "440820",
"Score": "0",
"body": "I had tried it on an integer array of 10k elements, but it hid a nasty bug. My pivot cannot be `mem_hi`, it must be `mem_hi - size`. This change will solve (1). As for (2), it is very interesting, would there be a performance difference? I'll update the code with the changes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T22:43:05.483",
"Id": "226719",
"ParentId": "226717",
"Score": "6"
}
},
{
"body": "<p><code>if (mem_low >= mem_hi || mem_hi < mem_low)</code></p>\n\n<p>The second part of that if is completely redundant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T11:04:44.843",
"Id": "226737",
"ParentId": "226717",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:01:00.190",
"Id": "226717",
"Score": "5",
"Tags": [
"c",
"sorting",
"reinventing-the-wheel"
],
"Title": "Quick Sort in C"
}
|
226717
|
<p>I adapted a makefile to re-compile for changed header files by generating a list of dependencies.
The code framework already existed and all I had to do was adding a little bit of code for the compiling rules.
Now I get linker warnings. Which is confusing because when I compile my program, the linker links all object files which have changed.
Here is the part of the makefile that generates the dependencies and makes everything.</p>
<pre><code># Define Messages
MSG_LINKING = Linking:
MSG_COMPILING = Compiling:
MSG_ASSEMBLING = Assembling:
MSG_DEPENDENCY = Collecting dependencies for:
MSG_BINARY = Generate binary:
DEPENDENCY_RELATIVE = $(CSRC:.c=.d) $(CXXSRC:.cpp=.d)
DEPENDENCIES_ABSOLUTE = $(addprefix $(DEPENDDIR)/, $(DEPENDENCY_RELATIVE))
CPPFLAGS = Some flags
CFLAGS += some flags
.PHONY: clean all
# building the binary
all: $(BUILDDIR)/$(BINARY_NAME).bin
clean:
-rm -rf $(BUILDDIR)
-rm -rf $(DEPENDDIR)
$(BUILDDIR)/$(BINARY_NAME).bin: $(BUILDDIR)/$(BINARY_NAME).elf
@echo
@echo $(MSG_BINARY)
$(BIN) $< $@
$(BUILDDIR)/$(BINARY_NAME).hex: $(BUILDDIR)/$(BINARY_NAME).elf
$(HEX) $< $@
$(BUILDDIR)/$(BINARY_NAME).elf: $(addprefix $(BUILDDIR)/, $(OBJ))
@echo
@echo $(MSG_LINKING)
$(CXX) -Wl,-L,$(BUILDDIR) -specs=nosys.specs $(MCU) -T linker.ld $(LIBS) -o $@ $^
@echo $@ was generated.
# I added $(DEPENDDIR)/.%d ... to get the makefile to re-compile for changed headers
$(BUILDDIR)/%.o : %.cpp
$(BUILDDIR)/%.o : %.cpp $(DEPENDDIR)/%.d | $(DEPENDDIR)
@echo
@echo $(MSG_COMPILING) $<
@mkdir -p $(@D)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $^
# I added $(DEPENDDIR)/.%d ... to get the makefile to re-compile for changed headers
$(BUILDDIR)/%.o : %.c
$(BUILDDIR)/%.o : %.c $(DEPENDDIR)/%.d | $(DEPENDDIR)
@echo
@echo $(MSG_COMPILING) $<
@mkdir -p $(@D)
$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^
# Dependency Handling
DEPFLAGS = -MM -MQ
$(DEPENDDIR)/%.d: %.c
@echo
@echo $(MSG_DEPENDENCY) $<
@mkdir -p $(@D)
@set -e; rm -f $@; \
$(CC) $(DEPFLAGS) $(@:.d=.o) $(CPPFLAGS) $(CFLAGS) $< > $@.<span class="math-container">$$$$</span>; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.<span class="math-container">$$$$</span> > $@; \
rm -f $@.<span class="math-container">$$$$</span>
$(DEPENDDIR)/%.d: %.cpp
@echo
@echo $(MSG_DEPENDENCY) $<
@mkdir -p $(@D)
@set -e; rm -f $@; \
$(CXX) $(DEPFLAGS) $(@:.d=.o) $(CPPFLAGS) $(CXXFLAGS) $< > $@.<span class="math-container">$$$$</span>; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.<span class="math-container">$$$$</span> > $@; \
rm -f $@.<span class="math-container">$$$$</span>
ifneq ($(MAKECMDGOALS),clean)
include $(DEPENDENCIES_ABSOLUTE)
endif
</code></pre>
<p>When compiling, I get the following output. The code is working and the changes in the headers were included in the compiled and linked code, but I still get the linker error</p>
<pre><code>wsl make -j16 all
Collecting dependencies for: Service8.cpp
Collecting dependencies for: Service6.cpp
Collecting dependencies for: Service2.cpp
Collecting dependencies for: Factory.cpp
Compiling: Factory.cpp
# A lot of output and flags followed by
-c -o _build/Factory.o Factory.cpp _dependencies/Factory.d
Compiling: Service6.cpp
# A lot of output and flags followed by
-c -o _build/Service6.o Service6.cpp _dependencies/Service6.d
Compiling: Service2.cpp
# A lot of output and flags followed by
-c -o _build/Service2.o Service2.cpp _dependencies/Service2.d
Compiling: Service8.cpp
# A lot of output and flags followed by
-c -o _build/Service8.o Service8.cpp _dependencies/Service8.d
</code></pre>
<p>Linker warnings</p>
<pre><code>arm-none-eabi-g++: warning: _dependencies/Service8.d: linker input file unused because linking not done
arm-none-eabi-g++: warning: _dependencies/Factory.d: linker input file unused because linking not done
arm-none-eabi-g++: warning: _dependencies/Service2.d: linker input file unused because linking not done
arm-none-eabi-g++: warning: _dependencies/Service6.d: linker input file unused because linking not done
</code></pre>
<p>And last of all the Linking Process</p>
<pre><code>Linking:
# A lot of object files
_build/stm32h743zit6.elf was generated.
Generate binary:
arm-none-eabi-objcopy -O binary -S _build/stm32h743zit6.elf _build/stm32h743zit6.bin
23:00:54 Build Finished. 0 errors, 0 warnings. (took 4s.51ms)
</code></pre>
<p>So how can I get rid of this linker warning? Why are the dependency files classified as linker files? Is there any option to change that? I do not have al ot of experience with makefiles and am trying to learn the concepts, maybe you have some ideas how to make this code more efficient or clean?</p>
<p>Thanks a lot in advance !</p>
<p>Kind Regards,
R.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T08:26:22.103",
"Id": "440967",
"Score": "0",
"body": "Okay, I by replaced $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $^ in the compiling rule with $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $(<:.d = .cpp) or the .c equivalent. Everything still seems to work and the linker warnings are gone."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T21:52:36.680",
"Id": "226718",
"Score": "1",
"Tags": [
"makefile",
"make"
],
"Title": "Compiling dependency files: Linker Warning"
}
|
226718
|
<p>I have written a cashflow calculator.
Any suggestions on how to improve the code below?
Income and expenses have a similar pattern.</p>
<pre><code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStringListModel>
#include <QSettings>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_AddIncome_clicked();
void on_AddExpenses_clicked();
void on_DeleteIncome_clicked();
void on_DeleteExpenses_clicked();
void AppendIncomeList();
void AppendExpensesList();
void CalculateTotalIncome();
void CalculateTotalExpenses();
void CalculateCashFLow();
void CashOnCashReturn();
void LoadSettings();
void SaveSettings();
void on_Investment_editingFinished();
private:
Ui::MainWindow *ui;
QString m_SettingsFile;
QStringListModel *m_CashFlowModel;
QStringListModel *m_IncomeModel;
QStringListModel *m_ExpensesModel;
QStringListModel *m_CashOnCashModel;
QStringList m_ExpensesList;
QStringList m_IncomeList;
std::vector<double> m_IncomeVector;
std::vector<double> m_ExpensesVector;
};
#endif // MAINWINDOW_H
</code></pre>
<hr>
<pre><code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_SettingsFile = "C:/Temp/config.ini";
m_IncomeModel = new QStringListModel();
m_ExpensesModel = new QStringListModel();
m_CashFlowModel = new QStringListModel();
m_CashOnCashModel = new QStringListModel();
ui->IncomeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->IncomeView->setModel(m_IncomeModel);
ui->ExpensesView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->ExpensesView->setModel(m_ExpensesModel);
LoadSettings();
CalculateTotalIncome();
CalculateTotalExpenses();
CalculateCashFLow();
CashOnCashReturn();
}
MainWindow::~MainWindow()
{
SaveSettings();
delete ui;
}
void MainWindow::on_AddIncome_clicked()
{
AppendIncomeList();
CalculateTotalIncome();
CalculateCashFLow();
CashOnCashReturn();
}
void MainWindow::on_AddExpenses_clicked()
{
AppendExpensesList();
CalculateTotalExpenses();
CalculateCashFLow();
CashOnCashReturn();
}
void MainWindow::on_DeleteIncome_clicked()
{
QModelIndex index = ui->IncomeView->currentIndex();
m_IncomeModel->removeRows(index.row(),1);
CalculateTotalIncome();
ui->IncomeView->setModel(m_IncomeModel);
CalculateCashFLow();
CashOnCashReturn();
}
void MainWindow::on_DeleteExpenses_clicked()
{
QModelIndex index = ui->ExpensesView->currentIndex();
m_ExpensesModel->removeRows(index.row(),1);
CalculateTotalExpenses();
ui->ExpensesView->setModel(m_ExpensesModel);
CalculateCashFLow();
CashOnCashReturn();
}
void MainWindow::AppendIncomeList()
{
QString Text(ui->Income->text());
Text.append(" ").append(QString::number(ui->IncomePrice->value()));
m_IncomeList << Text;
m_IncomeModel->setStringList(m_IncomeList);
}
void MainWindow::AppendExpensesList()
{
QString Text(ui->Expenses->text());
Text.append(" ").append(QString::number(ui->ExpensesPrice->value()));
m_ExpensesList << Text;
m_ExpensesModel->setStringList(m_ExpensesList);
}
void MainWindow::CalculateTotalIncome()
{
m_IncomeList = m_IncomeModel->stringList();
m_IncomeVector.clear();
foreach(QString item, m_IncomeList)
{
QStringList items = item.split(" ");
m_IncomeVector.push_back(items[1].toDouble());
}
ui->IncomeTotal->setText(QString::number(std::accumulate(m_IncomeVector.begin(),m_IncomeVector.end(),0.0)));
}
void MainWindow::CalculateTotalExpenses()
{
m_ExpensesList = m_ExpensesModel->stringList();
m_ExpensesVector.clear();
foreach(QString item, m_ExpensesList)
{
QStringList items = item.split(" ");
m_ExpensesVector.push_back(items[1].toDouble());
}
ui->ExpensesTotal->setText(QString::number(std::accumulate(m_ExpensesVector.begin(),m_ExpensesVector.end(),0.0)));
}
void MainWindow::CalculateCashFLow()
{
double CashFlow = ui->IncomeTotal->text().toDouble() - ui->ExpensesTotal->text().toDouble();
QStringList StringList;
StringList << "Monthly Cash Flow " << QString::number(CashFlow);
StringList << "Annual Cash Flow " << QString::number(CashFlow * 12);
m_CashFlowModel->setStringList(StringList);
ui->CashFlow->setModel(m_CashFlowModel);
}
void MainWindow::CashOnCashReturn()
{
QAbstractItemModel *m_model = ui->CashFlow->model();
QModelIndex index = m_model->index(1,0);
double result = (index.data().toDouble() / ui->Investment->value()) * 100.0;
QStringList list;
list << "Monthly " << QString::number(result).append("%");
index = m_model->index(3,0);
result = (index.data().toDouble() / ui->Investment->value()) * 100.0;
list << "Annual " << QString::number(result).append("%");
m_CashOnCashModel->setStringList(list);
ui->CashOnCash->setModel(m_CashOnCashModel);
}
void MainWindow::LoadSettings()
{
QSettings Settings(m_SettingsFile, QSettings::IniFormat);
double IncomePrice = Settings.value("IncomePrice", "").toDouble();
ui->IncomePrice->setValue(IncomePrice);
double ExpensesPrice = Settings.value("ExpensesPrice","").toDouble();
ui->ExpensesPrice->setValue(ExpensesPrice);
QString IncomeId = Settings.value("IncomeId","").toString();
ui->Income->setText(IncomeId);
QString ExpensesId = Settings.value("ExpensesId","").toString();
ui->Expenses->setText(ExpensesId);
double InitialInvestment = Settings.value("InitialInvestment","").toDouble();
ui->Investment->setValue(InitialInvestment);
QStringList IncomeList = Settings.value("IncomeModel","").toStringList();
m_IncomeModel->setStringList(IncomeList);
QStringList ExpensesList = Settings.value("ExpensesModel","").toStringList();
m_ExpensesModel->setStringList(ExpensesList);
restoreGeometry(Settings.value("mainWindowGeometry").toByteArray());
restoreState(Settings.value("mainWindowState").toByteArray());
}
void MainWindow::SaveSettings()
{
QSettings Settings(m_SettingsFile, QSettings::IniFormat);
double IncomePrice = ui->IncomePrice->value();
double ExpensesPrice = ui->ExpensesPrice->value();
double InitialInvestment = ui->Investment->value();
QString IncomeId = ui->Income->text();
QString ExpensesId = ui->Expenses->text();
QStringList IncomeModel = m_IncomeModel->stringList();
QStringList ExpensesModel = m_ExpensesModel->stringList();
Settings.setValue("IncomeModel",IncomeModel);
Settings.setValue("ExpensesModel",ExpensesModel);
Settings.setValue("InitialInvestment",InitialInvestment);
Settings.setValue("IncomeId", IncomeId);
Settings.setValue("ExpensesId", ExpensesId);
Settings.setValue("IncomePrice", IncomePrice);
Settings.setValue("ExpensesPrice", ExpensesPrice);
Settings.setValue("mainWindowGeometry", saveGeometry());
Settings.setValue("mainWindowState", saveState());
}
void MainWindow::on_Investment_editingFinished()
{
CashOnCashReturn();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T08:05:54.463",
"Id": "447578",
"Score": "0",
"body": "Doesn't compile - `\"ui_mainwindow.h\"` is missing."
}
] |
[
{
"body": "<p>Here's my suggestions:</p>\n\n<ol>\n<li><p>This is strange:</p>\n\n<pre><code>namespace Ui {\nclass MainWindow;\n}\n</code></pre>\n\n<p>it should be like this:</p>\n\n<pre><code>namespace Ui {\n class MainWindow;\n}\n</code></pre></li>\n<li><p>In C++, the type is very important, so C++ programmers tend to emphasize the type in declarations. Therefore, the base type of the pointer type is put together with the asterisk — instead of:</p>\n\n<pre><code>explicit MainWindow(QWidget *parent = nullptr);\n</code></pre>\n\n<p>it is more common to do:</p>\n\n<pre><code>explicit MainWindow(QWidget* parent = nullptr);\n</code></pre></li>\n<li><p>You are holding a raw pointer to <code>Ui::MainWindow</code>:</p>\n\n<pre><code>Ui::MainWindow *ui;\n</code></pre>\n\n<p>initializing it with <code>new</code>:</p>\n\n<pre><code>ui(new Ui::MainWindow)\n</code></pre>\n\n<p>and then call <code>delete</code> in the destructor:</p>\n\n<pre><code>delete ui;\n</code></pre>\n\n<p>This is error prone, and makes your class have undefined behavior when copied. And the memory is leaked if the destructor doesn't get called (i.e., the constructor failed later). The preferred way is to use a <code>unique_ptr</code>: (given that <code>Ui::MainWindow</code> is an incomplete type)</p>\n\n<pre><code>std::unique_ptr<Ui::MainWindow> ui;\n</code></pre>\n\n<p>This avoids all problems — your class automatically releases the object on destruction, and the class is not copyable.</p>\n\n<p>Same for the string list models.</p></li>\n<li><p>The constructor is exception unsafe — memory is leaked if the <code>new</code>s throw. Use <code>std::unique_ptr</code> for all the pointers. However, there's a subtlety here — it seems that you are transferring the ownership of the string list models to the Qt controller. You need to use <code>release</code> here. Like this: (assumes that the pointers are changed to <code>std::unique_ptr</code>)</p>\n\n<pre><code>MainWindow::MainWindow(QWidget* parent) :\n // same\n{\n // same\n\n // the relevant constructor of std::unique_ptr is explicit\n m_IncomeModel = std::make_unique<QStringListModel>();\n m_ExpensesModel = std::make_unique<QStringListModel>();\n m_CashFlowModel = std::make_unique<QStringListModel>();\n m_CashOnCashModel = std::make_unique<QStringListModel>();\n\n ui->IncomeView->setEditTriggers(QAbstractItemView::NoEditTriggers);\n ui->IncomeView->setModel(m_IncomeModel.release()); // use release\n\n ui->ExpensesView->setEditTriggers(QAbstractItemView::NoEditTriggers);\n ui->ExpensesView->setModel(m_ExpensesModel.release()); // use release\n\n // same\n}\n</code></pre></li>\n<li><p>Does <code>auto</code> help here?</p>\n\n<pre><code>QModelIndex index = ui->IncomeView->currentIndex();\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T08:08:53.793",
"Id": "447579",
"Score": "0",
"body": "`MainWindow` is not copyable, as it inherits from non-copyable `QMainWindow`, so point 4 is less of a problem. It's still better to use a unique pointer, of course (one usually also has to declare the constructor, so we can define it `=default` in the implementation, where `Ui::MainWindow` would be a complete type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-01T08:36:13.260",
"Id": "447582",
"Score": "0",
"body": "@L.F. **Qt** has some interesting quirks and features... For Point 2: `MainWindow` and `Ui::MainWindow` result from a `MainWindow.ui` form file being parsed, with `Ui::MainWindow` containing the autogenerated code and `MainWindow` being the class/file to hold use-written code, so that is rather common and even sensible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-02T07:04:17.683",
"Id": "447759",
"Score": "0",
"body": "@CharonX Thank you. I have removed the (Note A)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T07:46:38.960",
"Id": "227257",
"ParentId": "226721",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T23:26:51.393",
"Id": "226721",
"Score": "3",
"Tags": [
"c++",
"calculator",
"qt"
],
"Title": "Calculate Cash Flow"
}
|
226721
|
<p>I am trying to send data from an Arduino into Python via USB every 100 ms. What improvements can be made to my code? I feel like it is kind of bloated and can be better written, but I'm not sure which improvements should be made.</p>
<h3>read_arduino.py</h3>
<pre class="lang-py prettyprint-override"><code>import serial
def _has_digits(string):
return any(char.isdigit() for char in str(string))
def _check_for_overflowed_digits(string):
if _has_digits(string):
overflowed_digits = [ char for char in string.split() if char.isdigit() ]
digits_to_string = ("").join(overflowed_digits)
return digits_to_string
else:
return None
def _compute_state_vector(data_string):
data_array = data_string.split(",")
state_vector = {
'pendulum_angle': data_array[0],
'cart_position': data_array[1],
'pendulum_angular_velocity': data_array[2],
# Sometimes the carriage return "\r" remains in the string, so get rid of it
'cart_velocity': (data_array[3] if '\r' not in data_array[3] else data_array[3].split('\r')[0])
}
return state_vector
def _compute_input(state):
state_vector = [state['pendulum_angle'], state['cart_position'], state['pendulum_angular_velocity'], state['cart_velocity']]
gain_matrix = np.array([
[1000, 0, 0, 0],
[0, 10, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
])
control_input = -gain_matrix * state_vector
return control_input
class Arduino():
def __init__(self, port, baud_rate, timeout):
self.serial = serial.Serial(port, baud_rate, timeout = timeout)
def start_control(self):
last_line_recieved = ""
try:
while True:
serial_bytes = self.serial.readline()
decoded_line = str(serial_bytes.decode('utf8'))
# Read from serial until we capture the whole line of data
if (len(serial_bytes) != 0) and (b'\n' in serial_bytes):
# Sometimes digits overflow from one line onto the next
overflowed_digits = _check_for_overflowed_digits(decoded_line)
if overflowed_digits is not None:
last_line_recieved += overflowed_digits
# Parse data into state_vector and compute control input using LQR
state_vector = _compute_state_vector(last_line_recieved)
control_input = compute_input(state_vector)
print(control_input)
# Reset the variable
last_line_recieved = ""
elif len(serial_bytes) != 0:
last_line_recieved += decoded_line
else:
pass
except KeyboardInterrupt:
print("You have quit reading from the serial port.")
pass
if __name__ == "__main__":
arduino = Arduino("/dev/cu.usbmodem14101", baud_rate = 9400, timeout = 0)
arduino.start_control()
</code></pre>
<h3>main.cpp</h3>
<pre class="lang-cpp prettyprint-override"><code>#define ENCODER_OPTIMIZE_INTERRUPTS
#include <Arduino.h>
#include <Encoder.h>
#include "motorControllerDrokL298.h"
#include "pythonUtils.h"
// Initialize encoders
#define cartEncoderPhaseA 3
#define cartEncoderPhaseB 4
#define pendulumEncoderPhaseA 2
#define pendulumEncoderPhaseB 5
Encoder cartEncoder(cartEncoderPhaseA, cartEncoderPhaseB);
Encoder pendulumEncoder(pendulumEncoderPhaseA, pendulumEncoderPhaseB);
// Initialize named constants
const unsigned long TIMEFRAME = 100; // milliseconds
const double ENCODER_PPR = 2400.0;
// Initialize variables
unsigned long previousMilliseconds = 0;
float previousCartPosition = 0;
float previousPendulumAngle = 0;
void setup()
{
Serial.begin(9400);
// Motor controller
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(ENA, OUTPUT);
}
void loop()
{
unsigned long currentMilliseconds = millis();
long cartEncoderCount = cartEncoder.read();
long pendulumEncoderCount = pendulumEncoder.read();
// Send values to python every n milliseconds
if ( (currentMilliseconds - previousMilliseconds) > TIMEFRAME ) {
// Compute the state
stateVector state;
state.pendulumAngle = encoderCountToAngleRadians(pendulumEncoderCount, ENCODER_PPR); // radians
state.cartPosition = encoderCountToCartPositionInches(cartEncoderCount, ENCODER_PPR); // in
state.pendulumAngularVelocity = (state.pendulumAngle - previousPendulumAngle)/(TIMEFRAME/1000.0); // radians/s
state.cartVelocity = (state.cartPosition - previousCartPosition)/(TIMEFRAME/1000.0); // in/s
sendStateVectorToPython(state);
// Store the current data for computation in the next loop
previousMilliseconds = millis();
previousPendulumAngle = state.pendulumAngle;
previousCartPosition = state.cartPosition;
}
}
</code></pre>
<h3>pythonUtils.h</h3>
<pre class="lang-cpp prettyprint-override"><code>#ifndef PYTHON_UTILS
#define PYTHON_UTILS
#include <Arduino.h>
struct stateVector
{
double pendulumAngle;
double cartPosition;
double pendulumAngularVelocity = 6.0;
double cartVelocity = 5.0;
};
float encoderCountToAngleDegrees(long encoderCount);
float encoderCountToCartPositionInches(long cartEncoderCount, double encoderPPR);
void sendStateVectorToPython(stateVector state);
float encoderCountToAngleRadians(long encoderCount, double encoderPPR)
{
return (encoderCount / encoderPPR) * (2.0 * PI);
}
float encoderCountToCartPositionInches(long cartEncoderCount, double encoderPPR) {
float idlerPulleyRadius = 0.189; // inches
float cartAngle = encoderCountToAngleRadians(cartEncoderCount, encoderPPR); // radians
return idlerPulleyRadius * cartAngle;
}
void sendStateVectorToPython(stateVector state)
{
Serial.print(state.pendulumAngle);
Serial.print(",");
Serial.print(state.cartPosition);
Serial.print(",");
Serial.print(state.pendulumAngularVelocity);
Serial.print(",");
Serial.print(state.cartVelocity);
Serial.println();
}
#endif
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The Python program looks fairly good. I wouldn't call it bloated, but there are a few structural problems related to the <code>Arduino</code> class. They boil down to:</p>\n\n<ul>\n<li>Interpreting the data received from the Arduino is done in the <code>Arduino</code> class, which will make it harder to reuse the code it the future, and makes the code harder to quickly read and understand.</li>\n<li>The helper functions <code>_has_digits</code> and <code>_check_for_overflowed_digits</code> are only really useful in the <code>Arduino</code> class, so they should be static methods of the class.</li>\n<li>In the program's current state, there is little reason for the <code>Arduino</code> class to exist. Instead, a single function would work just as well.</li>\n</ul>\n\n<h2>Interpreting the received data separately from reading it</h2>\n\n<p>In any program, you want each piece of code separated so that each piece only deals with the particular problem it is trying to solve. This helps to make it easier to reason about what a program is doing, as well as improve the ability for code to be reused in the future.</p>\n\n<p>When looking at this program, the <code>start_control</code> is in violation of this idea. The method is performing two distinct actions:</p>\n\n<ul>\n<li>Reading data from the serial port until a complete chunk of data is received.</li>\n<li>Interpreting the data received from the first action.</li>\n</ul>\n\n<p>Having these two tasks defined in the same function causes some problems. The first is that in order to figure out how the data is interpreted, you must also understand how the data is extracted from the serial port. In this program, you need to interpret the different branches of the if/else structure to figure out which path is executed when a complete chunk of data is available. The second problem is that it ties the function to exactly one way of interpreting the data, which is impossible to change without also changing the <code>start_control</code> function. In addition, it is impossible to reuse the code extracting data from the serial port without some nasty copy and pasting.</p>\n\n<p>To fix this, place your interpreting code in a function:</p>\n\n<pre><code>def interpret_data(data):\n state_vector = _compute_state_vector(data)\n control_input = compute_input(state_vector)\n print(control_input)\n</code></pre>\n\n<p>and pass the function as a parameter to the <code>Arduino</code> class:</p>\n\n<pre><code>class Arduino():\n def __init__(self, action, port, baud_rate, timeout):\n self.interpret_func = action\n self.serial = serial.Serial(port, baud_rate, timeout = timeout)\n\n def start_control(self):\n\n last_line_recieved = \"\"\n\n try:\n while True:\n serial_bytes = self.serial.readline()\n decoded_line = str(serial_bytes.decode('utf8'))\n\n # Read from serial until we capture the whole line of data\n if (len(serial_bytes) != 0) and (b'\\n' in serial_bytes):\n\n # Sometimes digits overflow from one line onto the next\n overflowed_digits = _check_for_overflowed_digits(decoded_line)\n if overflowed_digits is not None:\n last_line_recieved += overflowed_digits\n\n # Use the data interpret function given in the constructor:\n self.interpret_func(data)\n\n # Reset the variable\n last_line_recieved = \"\"\n\n elif len(serial_bytes) != 0:\n last_line_recieved += decoded_line\n\n else:\n pass\n\n except KeyboardInterrupt:\n print(\"You have quit reading from the serial port.\")\n pass\n\nif __name__ == \"__main__\":\n arduino = Arduino(interpret_data,\n \"/dev/cu.usbmodem14101\", baud_rate = 9400, timeout = 0)\n arduino.start_control()\n</code></pre>\n\n<h2>Use static methods</h2>\n\n<p>This one is fairly self-explanatory. Since <code>_has_digits</code> and <code>_check_for_overflowed_digits</code> are only used in the <code>Arduino</code> class, and do not modify the any of the <code>Arduino</code> class's variables, they should be static methods of the class:</p>\n\n<pre><code>class Arduino():\n @staticmethod\n def _has_digits(string):\n # implementation here\n @staticmethod\n def _check_for_overflowed_digits(string):\n # implementiation here\n\n # rest of Arduino class\n</code></pre>\n\n<p>Of course, you will need to prepend <code>self</code> in front of these methods when you call them.</p>\n\n<h2>Consider removing the <code>Arduino</code> class</h2>\n\n<p>This is more of a stylistic choice than anything else, but it in the way it is currently being used, the <code>Arduino</code> class doesn't provide any more utility than just having the function</p>\n\n<pre><code>def read_from_serial(action, port, baud_rate, timeout)\n</code></pre>\n\n<p>. Objects and classes are used to preserve data across function calls. Right now, the object is created, used once, and then never touched again. The data reuse properties that using an class provides is unused, making the <code>Arduino</code> class somewhat unneeded. If you were to connect to the same port multiple times after disconnecting from it, it may make sense to use an object to hold the data.</p>\n\n<h1>Other Observations</h1>\n\n<ul>\n<li>The serial port needs to be closed when you are done using <code>serial.close()</code>. In your case, it would probably go in the <code>except KeyboardInterrupt:</code> clause in the program.</li>\n<li><code>start_control</code> isn't a great name for the function. Consider using <code>run_read_loop</code> or something similar.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:58:42.470",
"Id": "440991",
"Score": "0",
"body": "Awesome, thank you so much for the help!! I'm going to remove the `Arduino` class as you suggest. The goal of this program is to read data in from the Arduino every 100 ms and then once python receives the data, it's going to calculate a couple (expensive) things and send it back to the Arduino. This would be the `interpret_data()` in your example. Where should I write the data to the Serial port? Should this be done in `interpret_data()`, or should I create a separate function that takes an input argument and writes it to the serial port, something like `def write_to_serial(string)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T15:06:30.980",
"Id": "440992",
"Score": "0",
"body": "More specifically, the writing to the serial port would replace the line `print(control_input)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T16:47:57.363",
"Id": "440999",
"Score": "0",
"body": "Ok so I have another question. Each person who passes in their `action` function is going to want to do different things with the data. Some will want to write back to the Arduino, others might just want to write the data to a CSV. That is, some want access to the serial port and others don't. How can the call `interpret_func(data)` be as reusable as possible? If only using functions, this would look like `interpret_func(serial_port, data)` which means every person must have a `serial_port` argument in their function. But I suppose it wouldn't be any different if using the class."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T07:25:01.340",
"Id": "226727",
"ParentId": "226724",
"Score": "1"
}
},
{
"body": "<h2>The 100ms time interval isn't.</h2>\n\n<p>The way <code>loop()</code> is coded, the loop isn't 100ms. It's 101ms plus the time to execute the code between the two calls to <code>millis()</code></p>\n\n<pre><code>unsigned long currentMilliseconds = millis();\n...\npreviousMilliseconds = millis();\n</code></pre>\n\n<p>The 101ms is because the test is:</p>\n\n<pre><code>if ( (currentMilliseconds - previousMilliseconds) > TIMEFRAME ) {\n</code></pre>\n\n<p>Maybe it doesn't matter, but to get a consistent interval it could be coded like so:</p>\n\n<pre><code>void loop()\n{\n unsigned long currentMilliseconds = millis();\n ...\n if ( (currentMilliseconds - previousMilliseconds) >= TIMEFRAME ) {\n\n ...\n\n // this advances previousMilliseconds by the exact interval\n previousMilliseconds += TIMEFRAME;\n\n ... \n }\n}\n</code></pre>\n\n<p>A useful trick is to toggle an output bit in <code>loop()</code> or in the body of the <code>if</code> statement:</p>\n\n<pre><code>digitalWrite(LED_BUILTIN, ! digitalRead(LED_BUILTIN));\n</code></pre>\n\n<p>You can then monitor that pin with an o-scope or logic analyzer. Depending on where you put the toggle you can see how long it takes to run the loop, how often it runs, how much jitter there is in sending the data, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:19:00.773",
"Id": "441589",
"Score": "0",
"body": "This was really helpful, I didn't catch that at all. Thank you!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T03:52:56.887",
"Id": "226887",
"ParentId": "226724",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226727",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T03:28:21.927",
"Id": "226724",
"Score": "3",
"Tags": [
"python",
"c++",
"python-3.x"
],
"Title": "Reading serial data from Arduino into Python every 100 ms"
}
|
226724
|
<p>This takes a user inputted string, then tries to randomly 'guess' it. The problem is that whenever the input's length is 6 digits or more, it takes an incredibly long time to process it. Is there a more efficient way of doing this?</p>
<pre><code>import random as rand
import string
def main(word):
len_word = len(word)
ntries = 0
while True:
letters = []
for i in range(len_word):
letters.append(rand.choice(string.ascii_lowercase))
ntries += 1
b = ''.join(letters)
if b==word:
print('Mission accomplished. It took ' + str(ntries) + ' tries.')
break
if __name__ == '__main__':
main(input('input a word: '))
</code></pre>
<p>Note: I have tried making the program guess the letters one by one, and then check if said letter was right, but it seemed to make the problem even worse.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T06:04:56.567",
"Id": "440832",
"Score": "6",
"body": "How \"efficient\" could you expect random guessing to possibly be? What does it even mean to \"optimize\" a hopelessly lengthy task that is also kind of pointless?"
}
] |
[
{
"body": "<p>Random guessing will always take a long time.\nYou can improve your code a bit if you dont append to a list and instead use <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\">random.choices</a>.</p>\n\n<pre><code>import random\nimport string\ndef main(word):\n ntries = 0\n while True:\n ntries += 1\n b = \"\".join(random.choices(string.ascii_lowercase, k=len(word)))\n if b == word:\n print(\"Mission accomplished. It took \" + str(ntries) + \" tries.\")\n break\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T07:40:20.967",
"Id": "226729",
"ParentId": "226725",
"Score": "1"
}
},
{
"body": "<h1>Docstrings</h1>\n\n<p>Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition.</p>\n\n<pre><code>def guess_word():\n \"\"\"Do calculations and return correct guessed word.\"\"\"\n</code></pre>\n\n<h1>Style</h1>\n\n<p>check pep0008 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide and here are some comments:</p>\n\n<pre><code>import string\n\ndef main(word):\n</code></pre>\n\n<p>Surround top-level function and class definitions with two blank lines. </p>\n\n<pre><code>ntries = 0\nif b==word:\n</code></pre>\n\n<ul>\n<li>Use descriptive variable names, improves readability and general\nunderstanding of the code.</li>\n<li>Always surround these binary operators with a single space on either\nside: assignment (=), augmented assignment (+=, -= etc.), comparisons\n(==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and,\nor, not). Except when = is used to set a function parameter.</li>\n</ul>\n\n<h1>The code</h1>\n\n<p>len_word</p>\n\n<pre><code>len_word = len(word)\nntries = 0\nwhile True:\n letters = []\n for i in range(len_word):\n</code></pre>\n\n<p>the variable len_word is unnecessary, can be expressed:</p>\n\n<pre><code>while True:\n letters = []\n for i in range(len(word)):\n</code></pre>\n\n<h1>Random brute forcing:</h1>\n\n<p>a sample size of 6 out of 26 alphabets has 230230 possible combinations (where order is unimportant and each combination has n! re-orderings where n = combination length (letters in the word) what is very obvious is that with such algorithms, it is very likely that zombie dinosaurs start showing up before the code guesses the correct word (10 years to be able to guess a 10 letter word for 500,000 secret words/passwords examined per second). So if what you are trying to build is a password cracker, the algorithms that are better than brute forcing are beyond the scope of this review.</p>\n\n<p>What your mini-program does is trying n digit random choices and comparing them to the secret word which number of trials is variable</p>\n\n<p>input a word: red\nMission accomplished. It took 8428 tries.</p>\n\n<p>input a word: red\nMission accomplished. It took 16894 tries.</p>\n\n<p>and since it's a random choice(not entirely random because it's based on a so-called 'pseudo-random' algorithm, you might generate the same number of trials for a random.seed(n)) this is not the case however, it tries different possibilities, so with some bad luck, that with some word lengths might keep running until aliens start making documentaries about us.</p>\n\n<h1>Assuming we can check each character separately:</h1>\n\n<p>(** This is not the case of password crackers in the real world which must guess the exact word).</p>\n\n<pre><code># Note: I have tried making the program guess the letters one by one, and then \n# check if said letter was right, but it seemed to make the problem even worse.\n</code></pre>\n\n<p>and since you asked about separate letter comparison:</p>\n\n<pre><code>import string\n\n\ndef guess_word():\n \"\"\"Match characters with user input and return number of iterations, correct guess.\"\"\"\n possible = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation + ' '\n secret_word = input('Enter word: ')\n yield len(possible) * len(secret_word)\n for index in range(len(secret_word)):\n for char in possible:\n if secret_word[index] == char:\n yield char\n\n\nif __name__ == '__main__':\n word = list(guess_word())\n print(f\"Total: {word[0]} iterations.\\nWord: {''.join(word[1:])}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T07:44:41.080",
"Id": "226730",
"ParentId": "226725",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226730",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T03:37:05.490",
"Id": "226725",
"Score": "0",
"Tags": [
"python",
"strings",
"random"
],
"Title": "Random string generator that 'guesses' user inputted word"
}
|
226725
|
<p>In this SO post <a href="https://stackoverflow.com/questions/57632427/dynamically-choose-class-from-string">Dynamically choose class from string</a> Alexander Platonov creates a Function on the fly and then uses <code>Application.Run()</code> to instantiate an Object by it's class name. Eureka Reflection in VBA!! How evil! How inspiring!! So that began my journey into the darkness. </p>
<p>My quest for power over Reflection spawn the <code>ReflectionFactory</code> class. The default instance of this class modifies itself by adding clauses to a <code>Select Case</code>. This allows me to instantiate the Objects by their class names using the <code>New</code> keyword.</p>
<h2>IAnimal:Interface</h2>
<pre><code>Option Explicit
Public Function Speak() As String
End Function
</code></pre>
<h2>Dog:Class</h2>
<pre><code>Option Explicit
Implements IAnimal
Public Function Speak() As String
Const Phrase As String = "Ruff Ruff Ruff"
Debug.Print TypeName(Me); " says:"; """"; Phrase; """"
Application.Speech.Speak Phrase
Speak = Phrase
End Function
Private Function IAnimal_Speak() As String
Speak
End Function
</code></pre>
<h2>Cat:Class</h2>
<pre><code>Option Explicit
Implements IAnimal
Public Function Speak() As String
Const Phrase As String = "Meow Meow Meow"
Debug.Print TypeName(Me); " says:"; """"; Phrase; """"
Application.Speech.Speak Phrase
Speak = Phrase
End Function
Private Function IAnimal_Speak() As String
Speak
End Function
</code></pre>
<h2>ReflectionFactory:Class</h2>
<pre><code>Attribute VB_Name = "ReflectionFactory"
Attribute VB_PredeclaredId = True
Option Explicit
Private Const InsertAfter As String = "'" & "@Case ClassName InsertAfter"
Private Const vbext_ct_ClassModule As Long = 2
Public Sub AddClasses(ParamArray ClassNames() As Variant)
Dim StartLine As Long
Dim ClassName
With getCodeModule
For Each ClassName In ClassNames
If Not .Find("Case*New " & ClassName, 1, 1, 1, 1, , , True) Then
.Find InsertAfter, StartLine, 1, 1, 1
.InsertLines StartLine + 1, getClassNameCase(CStr(ClassName))
End If
Next
End With
End Sub
Public Sub Build()
Dim VBComp As Object
For Each VBComp In ThisWorkbook.VBProject.VBComponents
If VBComp.Type = vbext_ct_ClassModule Then
AddClasses VBComp.Name
End If
Next
End Sub
Private Function getCodeModule() As Object
Set getCodeModule = ThisWorkbook.VBProject.VBComponents(TypeName(Me)).CodeModule
End Function
Private Function getClassNameCase(ByVal ClassName As String) As String
getClassNameCase = vbTab & vbTab & "Case " & Chr(34) & ClassName & Chr(34) & ": Set CreateObject = New " & ClassName
End Function
Public Property Get CreateObject(ByVal ClassName As String) As Object
Select Case ClassName
'@Case ClassName InsertAfter
Case "IAnimal": Set CreateObject = New IAnimal
Case "MasterFactory": Set CreateObject = New MasterFactory
Case "Dog": Set CreateObject = New Dog
Case "Cat": Set CreateObject = New Cat
End Select
End Property
</code></pre>
<h2>Test</h2>
<pre><code>Sub ThisIsTooFun()
Dim kitty As IAnimal, puppy As IAnimal, Animal As IAnimal
ReflectionFactory.Build
Set kitty = ReflectionFactory.CreateObject("Cat")
Set puppy = ReflectionFactory.CreateObject("Dog")
Set Animal = ReflectionFactory.CreateObject(Choose(WorksheetFunction.RandBetween(1, 2), "Cat", "Dog"))
kitty.Speak
puppy.Speak
Animal.Speak
End Sub
</code></pre>
<h2>Results</h2>
<p><a href="https://i.stack.imgur.com/2DfRQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2DfRQ.png" alt="Immediate Window Results"></a></p>
<p>In truth, I will probably never use it but boy was it fun to get it working!!!</p>
<p>I'm still interested in your feedback. Do you think that it has any real world applications? Hmmm... <strike>Java Bean</strike> too outdated. VBA Bean for use in a Visual Bean Application.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T14:33:47.780",
"Id": "440890",
"Score": "0",
"body": "Glad to hear that you found my approach interesting. The main point of this approach was to avoid such hardcoding classnames in constructions as \"Select Case ClassName\" or \"If classnames = \"\" then\". I will probably not going to use it either, but yes, it was fun =)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T05:57:39.710",
"Id": "226726",
"Score": "5",
"Tags": [
"object-oriented",
"vba",
"reflection",
"factory-method"
],
"Title": "Factory class that uses reflection to instantiate objects by class name"
}
|
226726
|
<p>There are different methods to get data from server in Angular application:</p>
<ol>
<li>Get Observable from the service and subscribe to it at component</li>
<li>Create Subject at the service and subscribe to the Subject at component</li>
</ol>
<p>Both of this methods work for me but I can't understand which should I use. </p>
<p><strong>First method</strong>. <em>Get Observable from the service and subscribe to it at component</em>:</p>
<p>article.service.ts</p>
<pre><code>import { Injectable } from '@angular/core';
import { Article } from '../models/article';
import { AngularFirestore } from '@angular/fire/firestore';
import { map, take } from 'rxjs/operators';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: "root"
})
export class ArticleService {
public articlesChanged: Subject<Article[]> = new Subject<Article[]>();
articles: Article[];
constructor(private db: AngularFirestore) {}
get() {
return this.db.collection('articles').valueChanges({ idField: 'id' });
}
}
</code></pre>
<p>home.component.ts</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { ArticleService } from 'src/app/services/article.service';
import { Observable, Subscription } from 'rxjs';
import { Article } from 'src/app/models/article';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
articles: Article[];
constructor(private articlesService: ArticleService) { }
ngOnInit() {
this.articlesService.get().subscribe(articles => this.articles = articles as Article[]);
}
}
</code></pre>
<p><strong>Second method.</strong> <em>Create Subject at the service and subscribe to the Subject at component:</em></p>
<p>article.service.ts</p>
<pre><code>import { Injectable } from '@angular/core';
import { Article } from '../models/article';
import { AngularFirestore } from '@angular/fire/firestore';
import { map, take } from 'rxjs/operators';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: "root"
})
export class ArticleService {
public articlesChanged: Subject<Article[]> = new Subject<Article[]>();
articles: Article[];
constructor(private db: AngularFirestore) {}
get(): void {
this.db
.collection('articles')
.valueChanges({ idField: 'id' }).subscribe(articles => {
this.articles = articles as Article[];
this.articlesChanged.next(this.articles);
});
}
}
</code></pre>
<p>home.component.ts</p>
<pre><code>import { Component, OnInit, OnDestroy } from '@angular/core';
import { ArticleService } from 'src/app/services/article.service';
import { Observable, Subscription } from 'rxjs';
import { Article } from 'src/app/models/article';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, OnDestroy {
articlesSubscription: Subscription;
articles: Article[];
constructor(private articlesService: ArticleService) { }
ngOnInit() {
this.articlesSubscription = this.articlesService.articlesChanged.subscribe(articles => this.articles = articles);
this.articlesService.get();
}
ngOnDestroy(): void {
this.articlesSubscription.unsubscribe();
}
}
</code></pre>
<p>Is there a best practice which I should use? </p>
|
[] |
[
{
"body": "<p>I think at the end it depends on the use case.<br>\nFor a simple loading of data, i would use the approach of getting the Observable directly. \nWhen the backendcall is not anymore the single source of changes (for example when i could change the data in the frontend and persist it later), or when i want to \"store\" the data, so that i do not have to call the backend for each request, then i would start thinking about providing an extra observable.</p>\n\n<p>But i would not make the \"storage\" public, because then others would be able to emit values on it. I would make it private and provide a method that gives access to the data.</p>\n\n<pre><code>// ...\nprivate articles$ : BehaviorSubject<Article[]>([]);\n\npublic getArticles(): Observable<Article[]> {\n return this.articles$.pipe(\n distinctUntilChanged();\n )\n}\n\npublic loadArticles(): void {\n this.db.collection('articles').valueChanges({ idField: 'id' })\n .subscribe( \n (articles: Article[]) => this.articles.next(articles)\n );\n}\n</code></pre>\n\n<p>In my experience i worked mostly with a direct connected backend call. Perhaps with a pipe to map the backend data format into my frontend data format, but thats it.<br>\nThe other approach i use mostly when i want to implement a central data source.</p>\n\n<p>By the way, i have the tendency to type the return types of my methods, so that the transpiler can provide me some support. :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:59:47.533",
"Id": "237918",
"ParentId": "226731",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:06:14.013",
"Id": "226731",
"Score": "3",
"Tags": [
"typescript",
"angular-2+",
"firebase"
],
"Title": "Managing Angular subscriptions"
}
|
226731
|
<p>I wrote an <code>helper</code> class which allow me to request the body content from a site that is created by <code>AJAX</code>, for doing so I'm using <a href="https://github.com/kblok/puppeteer-sharp" rel="nofollow noreferrer"><code>Puppeteer Sharp</code></a>. This is the class:</p>
<pre><code>using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using PuppeteerSharp;
namespace App.Helpers
{
public class NetworkHelper
{
/// <summary>
/// Get the html of a page waiting for an AJAX call until the selector is visible.
/// </summary>
/// <param name="url">Link needed for execute the request.</param>
/// <param name="selector">Selector to wait.</param>
/// <param name="attempts">Max attempts until request fail.</param>
/// <returns>Contains the html of the requested page.</returns>
public static async Task<string> LoadAndWaitForSelector(Uri url, string selector, int attempts = 5)
{
try
{
//Create new browser page
using (Page page = await Handler.Browser.NewPageAsync())
{
//Navigate on the requested content and wait for selector
await page.GoToAsync(url.ToString(), timeout: 0);
await page.WaitForSelectorAsync(selector); //may throw error for timeout
return await page.GetContentAsync();
}
}
catch (WaitTaskTimeoutException)
{
//there are other attempts, rerty
if (attempts != 0)
{
attempts--;
//add some delay
await Task.Delay(10000);
return await LoadAndWaitForSelector(url, selector, attempts);
}
throw;
}
}
}
</code></pre>
<p>Question: Could this class be improved more?</p>
<p>Also, the <code>Browser</code> is static, so each instance use the same browser for avoid memory leak:</p>
<pre><code>public static Browser Browser { get; set; }
</code></pre>
<p>the method is called in the following way:</p>
<pre><code>var html = await NetworkHelper.LoadAndWaitForSelector(
new Uri("some url"), "#archive-tables");
</code></pre>
<p>thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:21:07.710",
"Id": "440837",
"Score": "2",
"body": "You don't need the static fields, you can use the same two parameters on a failed request as you're calling it within the same method and you are not modifying them so you have direct access to them. This can end up nasty if run in parallel. The threads would overwrite each other's fields. You could also add one more parameter for attemps and decrease it on each recursive call. The default value could be `=5`. Then there would be no static state and it would be safe to run it in parallel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:25:35.300",
"Id": "440838",
"Score": "1",
"body": "@t3chb0t I'm executing this method in parallel, I just removed the static fields `_storedUrl` and `_storedSelector`. Do you have any other suggestions for improve the class? Thanks. The optional parameter for attempts is a good idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:36:30.553",
"Id": "440839",
"Score": "1",
"body": "The exception that you handle could be `WaitTaskTimeoutException` instead of just `Exception`. You wouldn't need the `if` and the entire `catch` would be simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:38:07.793",
"Id": "440840",
"Score": "1",
"body": "@t3chb0t what if another `Exception` type is raised? eg: `503` or some other server error? If I remove `Exception` from the `catch` block I'm not covered to other exceptions..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:39:10.137",
"Id": "440841",
"Score": "2",
"body": "You are, they won't be caught and it will behave exactly as it does now where you just rethrow it. `catch(Exception ex) throw` is the same as not doing anything and if you use a more specific exception type then only this one will be handled. All others will be rethrown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:41:56.503",
"Id": "440842",
"Score": "1",
"body": "@t3chb0t I didn't know that, thanks. I updated the class. I also added some delay before the next request"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:44:26.930",
"Id": "440844",
"Score": "2",
"body": "@dfhwze and I lost like 40 green internet points for that review in comments :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:45:50.123",
"Id": "440846",
"Score": "2",
"body": "@t3chb0t If you add answer I will accept it, I appreciate your help. Let me update the question removing the original code"
}
] |
[
{
"body": "<p>After our initial comment-review-update sequence/loop there is not much left for a review but still, one more thing. You can get rid of the <code>if</code> entirely when you add a <code>when</code> filter to the excpetion:</p>\n\n<pre><code> catch (WaitTaskTimeoutException) when (attempts > 0)\n {\n //add some delay\n await Task.Delay(10000);\n\n return await LoadAndWaitForSelector(url, selector, attempts - 1);\n }\n</code></pre>\n\n<p>It's also better to pass a new value to the recursive call like <code>attempts - 1</code> than modifying the argument with <code>attempts--</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:54:24.140",
"Id": "226733",
"ParentId": "226732",
"Score": "7"
}
},
{
"body": "<p>Just wanted to add that you may want to consider using <a href=\"https://github.com/App-vNext/Polly#polly\" rel=\"noreferrer\">Polly</a> instead of rolling your own retry mechanism - this is a library built specifically for this kind of retry mechanism (as well as many more complicated scenarios). Using Polly would look something like the following.</p>\n\n<p>Note that I have renamed the <code>attempts</code> parameter to <code>retryAttempts</code> to make it clear that this does not define the total number of attempts but rather the total number of retry attempts after the initial one, to keep the behaviour the same as your sample code.</p>\n\n<pre><code>public class NetworkHelper\n{\n public static Task<string> LoadAndWaitForSelectorAsync(\n Uri url, string selector, int retryAttempts = 5)\n {\n // Create a policy that will...\n var policy = Policy\n // Retry for any `WaitTaskTimeoutException` raised during execution.\n .Handle<WaitTaskTimeoutException>()\n .WaitAndRetryAsync(\n // Retry the specified number of times after the initial attempt.\n retryCount: retryAttempts,\n // Wait for the given duration between each retry attempt. Note that\n // this can depend on the retry number if required.\n sleepDurationProvider: retryNumber => TimeSpan.FromSeconds(10));\n\n // Execute the operation to get the selector within the retry policy. If the\n // final retry attempt does not succeed, the resulting `WaitTaskTimeoutException`\n // will not be handled by the policy and will be thrown.\n return policy.ExecuteAsync(() => TryGetSelectorAsync(url, selector));\n }\n\n private static async Task<string> TryGetSelectorAsync(Uri url, string selector)\n {\n using (Page page = await Handler.Browser.NewPageAsync())\n {\n await page.GoToAsync(url.ToString(), timeout: 0);\n await page.WaitForSelectorAsync(selector);\n return await page.GetContentAsync();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T12:03:32.887",
"Id": "440857",
"Score": "1",
"body": "Nice solution too, didn't know this library"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T10:58:02.743",
"Id": "226736",
"ParentId": "226732",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "226733",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T08:14:01.760",
"Id": "226732",
"Score": "7",
"Tags": [
"c#",
"error-handling",
"web-scraping",
"async-await"
],
"Title": "Network helper class with retry logic on failure"
}
|
226732
|
<p>I wrote the following Bash script to upgrade All-core MediaWiki websites (no added extensions/skins or images - besides logo image).</p>
<p>I already tested the essence of this script and it worked for me; MediaWiki was upgraded from 1.32.0. to 1.33.0 and I can use the site regularly; yet I'd be glad for a review:</p>
<pre class="lang-bash prettyprint-override"><code>#!/bin/sh
date="$(date +%F-%T)"
db_user_name_and_db_name="SOME_IDENTICAL_NAMES" # DB user name and DB name must be the same;
war="SOME_WEB_APPLICATION_ROOT"
domain="SOME_DOMAIN" # As site's directory;
target_url="LINK_TO_LATEST_MEDIA_WIKI_ARCHIVE_DOWNLOAD"
mkdir -p "${war}/mediawiki_general_backups"
mkdir -p "${war}/mediawiki_specific_backups"
zip -r "${war}/mediawiki_general_backups/${domain}-directory-backup-${date}.zip" "${war}/${domain}"
mysqldump -u "${db_user_name_and_db_name}" -p "${db_user_name_and_db_name}" > "${war}/mediawiki_general_backups/${domain}-database-backup-${date}.sql"
files=(
LocalSettings.php
robots.txt
.htaccess*
${domain}.png
googlec69e044fede13fdc.html
)
cd "${war}/${domain}"
cp "${files[@]}" "${war}/mediawiki_specific_backups"
rm -rf "${war}/${domain}"
mkdir "${war}/${domain}"
wget ${target_url} -O - | tar -xzv --strip-components 1 -C ${war}/${domain}
cp -a "${war}/mediawiki_specific_backups"/* "${war}/${domain}"
cd "${war}/${domain}"/maintenance
php update.php
### Sitemap creation ###
mkdir -p "${war}/${domain}/sitemap"
php maintenance/generateSitemap.php \
--memory-limit=50M \
--fspath=/"${war}/${domain}/sitemap" \
--identifier="${domain}" \
--urlpath=/sitemap/ \
--server=https://"${domain}" \
--compress=yes
# Sitemap should be declared in robots.txt / preferred search engine's search console, or both;
</code></pre>
|
[] |
[
{
"body": "<p><strong>Naming</strong>\nTry not to use generic names like <code>$file</code>. Make your code read easy for others. Say <code>$files_to_backup</code> for example.</p>\n\n<p><strong>Check for errors when it matters</strong>\nIf backup is important: check that the backups succeeded:</p>\n\n<pre><code>if cp \"${files[@]}\"${war}/mediawiki_specific_backups\";then\n rm -rf \"${war}/${domain}\"\n mkdir \"${war}/${domain}\"\n ...\n ...\n else\n # handle error condition\nfi\n</code></pre>\n\n<p><strong>Document the code</strong>\nI prefer a comment in the script header describing what the script. If the script does useful work, document what it does so others understand what it does and how to use it. Similarly, comment anything in the code which is important and you think might require some explanation to help readers.</p>\n\n<pre><code>#!/bin/sh\n# Usage: how-to-use-script\n# Purpose: upgrade all core MediaWiki websites\n# etc\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T19:59:32.087",
"Id": "440920",
"Score": "0",
"body": "Code generally ends up looking cleaner if you handle the error case before the success case, because the error handler is usually shorter. Also, there are usually many paths to failure, and only one path to success, which should ideally appear at the end of the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:08:14.477",
"Id": "442959",
"Score": "0",
"body": "Hello, I up voted; is that okay for you that I'll add 2 more parts to the script (the original script won't change as it is always reviewed by one)? I want to add an mkdir command and a sitemap generation command (very common for many MediaWiki websites as it doesn't require extension and has a unique namespace)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-05T11:29:49.980",
"Id": "442963",
"Score": "0",
"body": "@JohnDoea thanks, of course it's fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T03:05:52.673",
"Id": "444682",
"Score": "0",
"body": "Hi, done, thanks so much; sorry for delaying and sorry for not accepting before - I should definitely have done that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T07:31:48.000",
"Id": "444705",
"Score": "0",
"body": "@JohnDoea For the record, usually we're against updating the code in the question after answers have been received. It creates a mess if more answers come in, reviews of all different kinds of versions make it hard to follow what's going on. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. However, since the author of the only answer so far is ok with it and the changes are minor, it's fine this time. Just, try not to do it again, ok? Thanks :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-11T07:58:21.217",
"Id": "444707",
"Score": "0",
"body": "Hello dear @Mast ; there seems to be a prejudgment here --- I am fully aware of the strict reservation from editing questions here and generally never do so --- it is only after suspectus agreed that I allowed myself doing so. I greatly respect the laws of this community --- a nice idea; maybe it's good to add a button \"the answer's author agreed to this edit\" just for this site. Thanks,"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T17:03:09.330",
"Id": "226752",
"ParentId": "226734",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226752",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T09:06:31.257",
"Id": "226734",
"Score": "6",
"Tags": [
"mysql",
"bash",
"shell",
"installer"
],
"Title": "All-core MediaWiki website upgrade script"
}
|
226734
|
<p>I wrote this tiny F# project yesterday, but I am a bit rusty and I would like to know if there is anything I can refactor and make more elegant.</p>
<pre><code>open System
open System.Collections.Generic
open System.Globalization
open MetadataExtractor
open MetadataExtractor.Formats.Exif
open System.IO
type Config =
{
culture : string
format : string
threshold : TimeSpan
dryRun : bool
}
// My .NET version is old so no anonymous records, I'll update the code when I update it.
let config =
{//{|
culture = "it-IT"
format = "dd-MMM-yyyy"
threshold = TimeSpan.FromHours(1.)
dryRun = false
}//|}
let multipleDaysFormat (date : DateTime) format = sprintf "%i-%s" date.Day format
type Metadata = MetadataExtractor.Directory
[<EntryPoint>]
let main argv =
let (|File|Folder|) path =
match path with
| x when File.Exists(x) -> File x
| x when Directory.Exists(x) -> Folder x
| x -> failwithf "Invalid file or direcyory: %s" x
let getFiles path =
match path with
| File file -> [ file ]
| Folder folder -> Directory.EnumerateFiles(folder) |> Seq.toList
let getTimestamp (data : IReadOnlyList<Metadata>) =
data |>
Seq.choose (fun d -> match d with
| :? ExifSubIfdDirectory as x ->
x.GetDescription(ExifDirectoryBase.TagDateTimeOriginal) |>
Some
| _ -> None) |>
Seq.map (fun d -> DateTime.ParseExact(d, "yyyy:MM:dd HH:mm:ss", null)) |>
Seq.exactlyOne
let formatDate (dateTime : DateTime) =
dateTime.ToString(config.format, new CultureInfo(config.culture))
let getNewFileName (fileInfo : FileInfo) formattedDate =
fileInfo.Extension.ToLower() |>
sprintf "%s.%s%s" formattedDate (fileInfo.Name |> Path.GetFileNameWithoutExtension)
let updateFolderGroup (map : Map<DateTime, ('a * DateTime * 'b) list>) fileInfo dateTime newName =
let (KeyValue(referenceDateTime, list)) = map |> Seq.maxBy (fun kvp -> kvp.Key)
map |>
Map.remove referenceDateTime |>
Map.add dateTime ((fileInfo, dateTime, newName) :: list)
let (|Empty|NonEmpty|) map =
match Map.count map with
| 0 -> Empty
| _ -> NonEmpty map
let lastDateAddedIsAwayFrom dateTime (map : Map<DateTime, 'b>) =
map |>
Seq.maxBy (fun kvp -> kvp.Key) |>
(function KeyValue (key, _) -> dateTime - key > config.threshold)
let addToGroups map fileInfo dateTime newName =
match map with
| Empty -> Map [(dateTime, [(fileInfo, dateTime, newName)])]
| NonEmpty map when map |>
lastDateAddedIsAwayFrom dateTime -> map.Add (dateTime, [(fileInfo, dateTime, newName)])
| NonEmpty map -> updateFolderGroup map fileInfo dateTime newName
let createDirectory =
match config.dryRun with
| true -> printfn "Creating directory %s"
| false -> Directory.CreateDirectory >> ignore
let moveTo path (fileInfo : FileInfo) =
match config.dryRun with
| true -> printfn "%s -> %s" fileInfo.Name path
| false -> path |> fileInfo.MoveTo
let processImageGroup (list : (FileInfo * DateTime * string) list) =
let getDateBy func =
list |> func (fun (_, dateTime, _) -> dateTime) |> (fun (_, x, _) -> x)
let maxDate = getDateBy List.maxBy
let minDate = getDateBy List.minBy
let daysString =
match minDate.Day = maxDate.Day with
| true -> minDate |> formatDate
| false -> maxDate |> formatDate |> multipleDaysFormat minDate
let (fileInfo, _, _) = list.Head
let getNewPath newName =
let basePath =
match list.Length with
| 0 | 1 -> fileInfo.Directory.FullName
| _ -> let folderPath = Path.Combine(fileInfo.Directory.FullName, daysString)
if Directory.Exists(folderPath) then
()
else
createDirectory folderPath
folderPath
Path.Combine(basePath, newName)
list |>
List.map (fun (fileInfo, _, newName) -> (fileInfo, getNewPath newName)) |>
List.iter (fun (fileInfo, newPath) -> fileInfo |> moveTo newPath)
argv |>
Array.fold (fun fileList path -> getFiles path @ fileList) [] |>
List.map (fun fileName -> (FileInfo(fileName), ImageMetadataReader.ReadMetadata(fileName) |> getTimestamp)) |>
List.map (fun (file, dateTime) -> (file, dateTime, dateTime |> formatDate |> getNewFileName file)) |>
List.sortBy (fun (_, dateTime, _) -> dateTime) |>
List.fold (fun map (fileInfo, dateTime, newName) -> addToGroups map fileInfo dateTime newName) Map.empty |>
Seq.map (function KeyValue (_, v) -> v) |>
Seq.iter processImageGroup
0
</code></pre>
<p>It's also here on GitHub: <a href="https://github.com/UnoSD/phren/tree/4c5515b4b6b565627fc20d7f34caa98b8b83301c" rel="nofollow noreferrer">https://github.com/UnoSD/phren</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T11:08:28.937",
"Id": "226738",
"Score": "1",
"Tags": [
"file",
"image",
"file-system",
"f#"
],
"Title": "Photo rename by Exif date and group into folders with a threshold"
}
|
226738
|
<p>I was feeling like writing a new <code>Uri</code> parser. The <a href="https://codereview.stackexchange.com/questions/209777/replacing-uri-with-a-more-convenient-class">previous one</a> was too limited and wasn't able to parse the authority part. This one is also based on the pretty image <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier" rel="nofollow noreferrer">here</a> and can tokenize all parts. I drew the image as an ascii art below. </p>
<hr>
<p><strong><a href="https://codereview.stackexchange.com/questions/226863/simple-tokenizer-v2-reading-all-matching-chars-at-once">follow-up</a></strong></p>
<hr>
<h2>Core</h2>
<p>The implementation has a single method <code>Tokenize</code> that is the state-machine. It's so short that I thought it's not necessary to move any functionality into other methods (would you agree?).</p>
<p>This is inspired by the <a href="https://medium.com/@brianray_7981/tutorial-write-a-finite-state-machine-to-parse-a-custom-language-in-pure-python-1c11ade9bd43" rel="nofollow noreferrer">Tutorial: Write a Finite State Machine to parse a custom language in pure Python</a>. However, I find the original implementation was too complex for C# because we can define states and their transitions in a more convenient way with tuples, attributes and a little bit of reflection. So I use the <code>PatternAttribute</code> to decorate each token of an <code>enum</code>. Later, <code>State<TToken></code> uses them with an <code>enum</code> reflection to try to match the current <code>char</code>.</p>
<p><code>State<TToken></code> and <code>Token<TToken></code> are generic because I'm going to use this also for parsing of command-line arguments.</p>
<p>The process starts with the first state on the list. Would you say this is fine or should I create one more state for this like <code>Start</code> or <code>NewUri</code> etc.? The linked examples does that.</p>
<pre><code>public static class Tokenizer
{
public static IEnumerable<Token<TToken>> Tokenize<TToken>(string value, IEnumerable<State<TToken>> states, Func<Token<TToken>> createToken)
{
states = states.ToList(); // Materialize states.
var state = states.First();
var token = createToken();
token.Type = state.Next;
foreach (var (oneChar, index) in value.Select((c, i) => (c.ToString(), i)))
{
// The state matches itself.
if (state.IsMatch(oneChar))
{
token.Text.Append(oneChar);
}
else
{
yield return token;
var isMatch = false;
// Find states where the current one is `Prev`.
foreach (var next in states.Where(s => s.Prev.Equals(token.Type)))
{
// There is a match. Use this state from now on.
if ((isMatch = next.IsMatch(oneChar)))
{
// Initialize the new token.
token = createToken();
token.StartIndex = index;
token.Type = next.Next;
token.Text.Append(oneChar);
state = next;
// Got to the next character.
break;
}
}
// There was no match. This means the current char is invalid.
if (!isMatch)
{
throw new ArgumentException($"Invalid character at: {index}.");
}
}
}
// Yield the last token.
if (token.Text.Length > 0)
{
yield return token;
}
}
}
public class PatternAttribute : Attribute
{
private readonly string _pattern;
public PatternAttribute([RegexPattern] string pattern) => _pattern = pattern;
public bool IsMatch(string value) => Regex.IsMatch(value, _pattern);
}
public class State<TToken>
{
public TToken Prev { get; set; }
public TToken Next { get; set; }
public bool IsMatch(string value)
{
return
typeof(TToken)
.GetField(Next.ToString())
.GetCustomAttribute<PatternAttribute>()
.IsMatch(value);
}
public override string ToString() => $"<-- {Prev} | {Next} -->";
}
public class Token<TToken>
{
public int StartIndex { get; set; }
public StringBuilder Text { get; set; } = new StringBuilder();
public TToken Type { get; set; }
public override string ToString() => $"{StartIndex}: {Text} ({Type})";
}
</code></pre>
<h2><code>UriStringTokenizer</code></h2>
<p>I encapsulate the raw API with my <code>UriStringTokenizer</code> to make easier to use. It defines all tokens and state transitions.</p>
<pre><code>public static class UriStringTokenizer
{
/*
scheme:[//[userinfo@]host[:port]]path[?key=value&key=value][#fragment]
[ ----- authority ----- ] [ ----- query ------ ]
scheme: ------------------------- path ------------------------- --------- UriString
\ / \ /\ /
// --------- host ---- '/' ?key ------ &key ------ / #fragment
\ / \ / \ / \ /
userinfo@ :port =value =value
*/
public static readonly ICollection<State<UriToken>> States = new (UriToken Prev, UriToken Next)[]
{
// self
(Scheme, Scheme),
(UserInfo, UserInfo),
(Host, Host),
(Port, Port),
(Path, Path),
(Key, Key),
(Value, Value),
(Fragment, Fragment),
// transitions
(Scheme, SchemeSuffix),
(SchemeSuffix, Path),
(SchemeSuffix, AuthorityPrefix),
(AuthorityPrefix, UserInfo),
(AuthorityPrefix, Host),
(UserInfo, UserInfoSuffix),
(UserInfoSuffix, Host),
(Host, PathPrefix),
(Host, PortPrefix),
(PortPrefix, Port),
(Port, PathPrefix),
(PathPrefix, Path),
(Path, KeyPrefix),
(KeyPrefix, Key),
(Key, ValuePrefix),
(ValuePrefix, Value),
(Value, KeyPrefix),
(Key, FragmentPrefix),
(Value, FragmentPrefix),
(FragmentPrefix, Fragment)
// --
}.Select(t => new State<UriToken> { Prev = t.Prev, Next = t.Next, }).ToList();
public static IEnumerable<Token<UriToken>> Tokenize(string value)
{
return Tokenizer.Tokenize(value, States, () => new Token<UriToken>());
}
}
public enum UriToken
{
[Pattern(@"[a-z]")]
Scheme,
[Pattern(@":")]
SchemeSuffix,
[Pattern(@"\/")]
AuthorityPrefix,
[Pattern(@"[a-z]")]
UserInfo,
[Pattern(@"@")]
UserInfoSuffix,
[Pattern(@"[a-z]")]
Host,
[Pattern(@":")]
PortPrefix,
[Pattern(@"[0-9]")]
Port,
[Pattern(@"\/")]
PathPrefix,
[Pattern(@"[a-z]")]
Path,
//QueryPrefix,
[Pattern(@"[\?\&]")]
KeyPrefix,
[Pattern(@"[a-z]")]
Key,
[Pattern(@"=")]
ValuePrefix,
[Pattern(@"[a-z]")]
Value,
[Pattern(@"#")]
FragmentPrefix,
[Pattern(@"[a-z]")]
Fragment,
}
</code></pre>
<h2>Tests</h2>
<p>Tests that I created are all green.</p>
<pre><code>using static UriToken;
public class UriStringParserTest
{
[Fact]
public void Can_tokenize_full_URI()
{
// Using single letters for easier debugging.
var uri = "s://u@h:1/p?k=v&k=v#f";
var tokens = UriStringTokenizer.Tokenize(uri).ToList();
var expectedTokens = new[]
{
Scheme,
SchemeSuffix,
AuthorityPrefix,
UserInfo,
UserInfoSuffix,
Host,
PortPrefix,
Port,
PathPrefix,
Path,
KeyPrefix,
Key,
ValuePrefix,
Value,
KeyPrefix,
Key,
ValuePrefix,
Value,
FragmentPrefix,
Fragment
};
Assert.Equal(expectedTokens, tokens.Select(t => t.Type).ToArray());
var actual = string.Join("", tokens.Select(t => t.Text));
Assert.Equal(uri, actual);
}
[Theory]
[InlineData("s://u@h:1/p?k=v&k=v#f")]
[InlineData("s://u@h:1/p?k=v&k=v")]
[InlineData("s://u@h:1/p?k=v")]
[InlineData("s://u@h:1/p")]
[InlineData("s:///p")]
public void Can_tokenize_partial_URI(string uri)
{
// Using single letters for faster debugging.
var tokens = UriStringTokenizer.Tokenize(uri).ToList();
var actual = string.Join("", tokens.Select(t => t.Text));
Assert.Equal(uri, actual);
}
[Fact]
public void Throws_when_invalid_character()
{
var uri = "s://:u@h:1/p?k=v&k=v#f";
// ^ - invalid character
var ex = Assert.Throws<ArgumentException>(() => UriStringTokenizer.Tokenize(uri).ToList());
Assert.Equal("Invalid character at: 4.", ex.Message);
}
}
</code></pre>
<hr>
<h3>Questions</h3>
<p>Did I do anything terribly wrong? Does this solution have any <em>obvious</em> flaws that I have missed? How else would you improve it?</p>
<hr>
<p>I use only basic patterns here because I was focused on the API and the state-machine. I will extend them later to match all characters that are valid for a <code>Uri</code> and its parts.</p>
<p>You can consider the input of the <code>Tokenize</code> method as already properly <code>%</code> encoded.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T12:38:10.767",
"Id": "440858",
"Score": "1",
"body": "It's also on [GitHub](https://github.com/he-dev/reusable/blob/dev/Reusable.Tests/src/Experimental/UriStringTokenizerTest.cs)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T14:00:12.233",
"Id": "440880",
"Score": "1",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/97815/discussion-on-question-by-t3chb0t-uri-tokenizer-as-a-simple-state-machine)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T12:46:47.523",
"Id": "440978",
"Score": "0",
"body": "I couldn't try out your code because of missing references, but I am pretty sure that it is not correct and will e.g. fail to parse several of [the example URIs in the Wikipedia article you linked to](https://wikipedia.org/wiki/Uniform_Resource_Identifier#Examples)."
}
] |
[
{
"body": "<p>This isn't exhaustive, because I don't have much time now, so I might add some more later.</p>\n\n<hr />\n\n<p>As I said in a comment, I don't buy the idea of looping over one char at a time: it's not documented that the patterns should match exactly one character, and it complicates the definitions of things like <code>Scheme</code>, which could be <code>[a-z]+</code> and everyone would be happy. Of course, anytime you allow the user to use non-trivial regexes you have to take precautions, but this would allow things like look-aheads which could be useful.</p>\n\n<p>My main complaint would be that it means you can't realisticly parse surrogate pairs, and if you expect to use this for anything other than URL-encoded URIs, then I think you need something more powerful. You could of course deal with surrogate pairs specifically, but that would just add complexity.</p>\n\n<p>It also means that comments like <code>// Using single letters for easier debugging</code> are somewhat frighening, because they fail to test that the thing copes with non-single-length tokens. Most importantly, <code>AuthorityPrefix</code> appears to be required to be <code>//</code>, but your system will match <code>/</code> as well: this would require two states to parse one-char-at-a-time.</p>\n\n<p>This seems like a grand oportunity to exploit the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.match?view=netframework-4.8#System_Text_RegularExpressions_Regex_Match_System_String_System_Int32_\" rel=\"noreferrer\">Regex.Match(string, int) overload</a>, and parse the whole token at once, which may even simplify the implementation. I'll leave you the fun of implementing it... ;)</p>\n\n<hr />\n\n<p>I don't like this:</p>\n\n<pre><code>foreach (var next in states.Where(s => s.Prev.Equals(token.Type)))\n</code></pre>\n\n<p>You should build a dictionary of prev/next pairs so that this things can hope with large numbers of transitions.</p>\n\n<p>I'd be inclined to make <code>Tokenize</code> an instance member, so you can initialise a <code>Tokenizer</code> and reuse it. In my opinion this would provide a clearer API, and would make it easier to extend in future.</p>\n\n<hr />\n\n<p>I'm not wild about <code>Token</code> having a <code>StringBuilder</code>. Rather, it looks like a good candidate for an immutable class with a <code>string</code>. This would complicate the token creation.</p>\n\n<p>Either way, you should initialize the first token fully: there is no guarentee that <code>createToken</code> will set the <code>StateIndex</code> to <code>0</code>. </p>\n\n<hr />\n\n<p>It would be nice if the <code>invalid character</code> exception gave some more information (e.g. what the current state is, how much has already been parsed).</p>\n\n<hr />\n\n<p><code>State.Next</code> is a confusing name: I think this is what dfhwze was getting at in the comments: all your states are tied to a transition, and the naming goes a bit funky as a result.</p>\n\n<hr />\n\n<p>The implemention of <code>State.IsMatch</code> is horrifying! I have no complaint with reflection, but this really should be cached, and you should probably build a single <code>Regex</code> object to reuse. Pre-loading the pattern would also create an exception somewhere useful (when the <code>State</code> is initialised) rather than when it is used. I also don't like that <code>State</code> is tied to the \"enum with attribute\" pattern: I'd rather it just had a regex attached, and a static method was provided to build it from the \"enum with attribute\" pattern. This would make the thing much more reusable. I'd actually be inclined to make <code>IState</code> (or whatever you call the thing that does the matching) an interface, so that it is completely general.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T14:00:36.567",
"Id": "440881",
"Score": "1",
"body": "this is pretty convincing ;-] back to the drawing board"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T14:17:12.643",
"Id": "440882",
"Score": "2",
"body": "Wait for my addendum on this fine answer, or it's back to the drawing board again :p"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T13:43:00.657",
"Id": "226742",
"ParentId": "226739",
"Score": "6"
}
},
{
"body": "<h2>State Machine Review</h2>\n\n<p>This is an interesting, yet unorthodox implementation of a state machine. Your states are actually transitions. You don't really have a state, since the state machine (<code>Tokenize</code> method) processes input and performs all lifetime management of tokens itself. The only behavior dispatched to the transitions (unfortunately named <code>State</code>) is asking whether a match is available (<code>IsMatch</code>).</p>\n\n<hr>\n\n<p>The problem with this approach, as VisualMelon has stated, is that you are walking each character at a time, which could lead to the wrong transition firing. The resolve this, you need to allow for look-ahead, and possibly also for backtracking. Rather than letting <code>Tokenize</code> traverse the input, you should let the current state handle the input. Each state is responsible for consuming as much characters it can. To allow this, wrap the input in a stream that supports look-ahead. Either create such class or use an existing API such as <code>ANTLRInputStream</code>.</p>\n\n<hr>\n\n<p>Each state should have its own <code>StringBuilder</code> for building the current token. Once a token is completely built, create a token from the builder and store its result as immutable string in the result set of tokens.</p>\n\n<hr>\n\n<p>The input of transitions should be cached, not in a global list, but dispatched to each state. Let each state store its own transitions (where transition.<code>From</code> == state). Whenever the state machine tells a state to process and cosume the input, the state should check its transitions whether a transition to a next state should be triggered. The self-transitions could be removed from the input and added in each state by default.</p>\n\n<hr>\n\n<p>Creation of tokens and completing tokens should not be part of the state machine, but of <code>entry</code> and <code>exit</code> operations of the individual states. The state machine should only set the initial state and let that state consume the input. Whenever a transition fires from within a state, the state machine should set the current state to <code>transition.To</code>. The state machine should keep feeding the current state with the input until it's been completely processed.</p>\n\n<hr>\n\n<p>As an overview:</p>\n\n<ul>\n<li>let the state machine create the states and dispatch the provided transitions to each state</li>\n<li>let the state machine set the initial state and feed the input to the current state</li>\n<li>let each state create a token builder on entry</li>\n<li>let each state process the input from current position and consume as much tokens possible</li>\n<li>let each state check for transitions that could fire</li>\n<li>let the state machine set the current state after a transition fired</li>\n<li>let each state create a token from token builder on exit and store it in the result set</li>\n</ul>\n\n<hr>\n\n<h2>General Review</h2>\n\n<p>If you're materializing the states, why allowing the argument to be possibly lazy (<code>IEnumerable</code>)?</p>\n\n<blockquote>\n<pre><code>states = states.ToList(); // Materialize states.\n</code></pre>\n</blockquote>\n\n<p>Picking the initial state is by convention the first state. This should be well documented. Another option is provide a pseudo initial state with initial transitions. This way, you allow for multiple possible initial states (if more than just <code>Scheme</code> could start an URI, or when you want to reuse the API for other purposes).</p>\n\n<blockquote>\n<pre><code>var state = states.First();\n</code></pre>\n</blockquote>\n\n<p>The single character loop has been discussed by VisualMelon, and I have suggested an alternative where each state should consume the input stream at own expense.</p>\n\n<blockquote>\n<pre><code>foreach (var (oneChar, index) in value.Select((c, i) => (c.ToString(), i)))\n</code></pre>\n</blockquote>\n\n<p>A state machine should not need to care about handling actions on state and/or transition changes. Let states handle <code>entry</code> and <code>exit</code> (<strong>Moore machine</strong>). And let transitions handle their transition guard and optionally action (<strong>Mealy machine</strong>). <code>UML</code> specifies both Moore and Mealy support.</p>\n\n<blockquote>\n<pre><code>if (state.IsMatch(oneChar))\n{\n token.Text.Append(oneChar);\n}\n</code></pre>\n</blockquote>\n\n<p>Each state should have its own transitions, so this global lookup should no longer be required:</p>\n\n<blockquote>\n<pre><code>foreach (var next in states.Where(s => s.Prev.Equals(token.Type)))\n</code></pre>\n</blockquote>\n\n<p>The following part should be split into entry and exit behavior of the current state.</p>\n\n<blockquote>\n<pre><code>token = createToken();\ntoken.StartIndex = index;\ntoken.Type = next.Next;\ntoken.Text.Append(oneChar);\n</code></pre>\n</blockquote>\n\n<p>On entry: create a token and token text builder, store the index, type. On exit: set the token builder's result as Text on the token and add the token to the result set.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T15:18:06.670",
"Id": "440888",
"Score": "1",
"body": "digesting... but this much more complex then I expected it to be/have o_O I'm still not convinced that this is _the only right_ way... I'll do it my way ;-P at least I'll try... this will be the lookahead... I migh have to backtrack later lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T15:22:37.957",
"Id": "440889",
"Score": "0",
"body": "When the behavior is well distributed over states and transitions, you can make a mature API for modelling many and complex use cases. You should at least taste such pattern ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T08:14:44.527",
"Id": "440964",
"Score": "1",
"body": "I have rewritten my tokenizer by implementing many of your suggestion. I'm not sure you'll be proud of me however :-P some parts may still be unorthodox."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T08:15:15.913",
"Id": "440965",
"Score": "0",
"body": "I am happy you considered my approach :p Now I have to rewrite my change trackers according to your suggestions! o_0"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T14:58:44.067",
"Id": "226745",
"ParentId": "226739",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226745",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T12:31:05.580",
"Id": "226739",
"Score": "3",
"Tags": [
"c#",
"state-machine",
"lexer"
],
"Title": "Simple tokenizer v1 - reading char by char"
}
|
226739
|
<p>I download a page to get it's source code. I then extract the first segment of the page that is between two strings that appear in the source code more than once.</p>
<p>How can my code be improved?</p>
<pre><code>url = "https://www.zapimoveis.com.br/lancamento/apartamento+venda+vl-mariana+zona-sul+sao-paulo+sp+ibirapuera-boulevard+mofarrej-empreendimentos+246m2-391m2/ID-16760/?contato=0"
sourcecode = requests.get(url)
r = sourcecode.text
string1 = '","billing":"'
string2 = '"},"createdDate":"'
start = re.findall(string1, r)
start = start[0]
end = re.findall(string2, r)
end = end[0]
text= r[r.find(start)+len(start):r.rfind(end)]
print(text)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T16:25:21.603",
"Id": "440897",
"Score": "0",
"body": "I have edited your question to improve the readability. If I have made any mistakes please feel free to edit to fix it. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T16:29:31.627",
"Id": "440899",
"Score": "5",
"body": "Could you provide us an example of what `r` or `sourcecode.text` is? Unfortunately I don't have access to the site to get it myself. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T17:55:43.967",
"Id": "440907",
"Score": "2",
"body": "Please provide examples of how the code should be used which demonstrate that it works as expected. I don't believe this works, because it will always find the last instance of `string2` despite your attempts to achieve otherwise."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T14:20:22.390",
"Id": "226743",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "Find text between two strings in data"
}
|
226743
|
<p>I have implemented the introductory challenge of University of Pennsylvania's <em>CIS 194: Introduction to Haskell (Spring 2013)</em> course. I have added the most important information of the problem statement below, and the full assignment is available as a PDF <a href="https://www.seas.upenn.edu/%7Ecis194/spring13/hw/01-intro.pdf" rel="nofollow noreferrer">on the course website</a>.</p>
<h1>Problem statement</h1>
<p>It starts with a short description of the <a href="https://en.wikipedia.org/wiki/Luhn_algorithm" rel="nofollow noreferrer">Luhn algorithm</a>:</p>
<blockquote>
<h2>Validating Credit Card Numbers</h2>
<p>[…]</p>
<p>In this section, you will implement the validation algorithm for credit cards. It follows these steps:</p>
<ol>
<li>Double the value of every second digit beginning from the right. That is, the last digit is unchanged; the second-to-last digit is doubled; the third-to-last digit is unchanged; and so on. For example, <code>[1,3,8,6]</code> becomes <code>[2,3,16,6]</code>.</li>
<li>Add the digits of the doubled values and the undoubled digits from the original number. For example, <code>[2,3,16,6]</code> becomes <span class="math-container">\$2+3+1+6+6 = 18\$</span>.</li>
<li>Calculate the remainder when the sum is divided by <span class="math-container">\$10\$</span>. For the above example, the remainder would be <span class="math-container">\$8\$</span>.</li>
<li>If the result equals <span class="math-container">\$0\$</span>, then the number is valid.</li>
</ol>
<p>[…]</p>
</blockquote>
<p>Then, over the course of four exercises, it has you implement the following functions:</p>
<h2><code>toDigits :: Integer -> [Integer]</code> and <code>toDigitsRev :: Integer -> [Integer]</code></h2>
<p><code>toDigits</code> should convert positive Integers to a list of digits. (For 0 or negative inputs, <code>toDigits</code> should return the empty list.) <code>toDigitsRev</code> should do the same, but with the digits reversed.</p>
<h2><code>doubleEveryOther :: [Integer] -> [Integer]</code></h2>
<p>Once we have the digits in the proper order, we need to double every other one.</p>
<p>Remember that <code>doubleEveryOther</code> should double every other number <em>beginning from the right</em>, that is, the second-to-last, fourth-to-last … numbers are doubled.</p>
<h2><code>sumDigits :: [Integer] -> Integer</code></h2>
<p>The output of <code>doubleEveryOther</code> has a mix of one-digit and two-digit numbers, and <code>sumDigits</code> calculates the sum of all digits</p>
<h2><code>validate :: Integer -> Bool</code></h2>
<p>Function that indicates whether an <code>Integer</code> could be a valid credit card number. This will use all functions defined in the previous exercises.</p>
<h1>My code</h1>
<p>This is my first "big" program after "Hello, World!". I've added <code>isValid</code>, which returns a string with the
credit card number and whether it is valid, and <code>main</code>, so it can be compiled. If you want, you can <a href="https://glot.io/snippets/ffc23migp4" rel="nofollow noreferrer">run it online</a>.</p>
<pre><code>import Data.Char
{- toDigits returns the digits of a number as an array.
It returns an empty list if n is zero or less. -}
toDigits :: Integer -> [Integer]
toDigits n
| n > 0 = map (\c -> toInteger $ digitToInt c) $ show n
| otherwise = []
-- toDigitsRev is like toDigits, except it reverses the array.
toDigitsRev :: Integer -> [Integer]
toDigitsRev n = reverse $ toDigits n
{- doubleAtEvenIndex is a helper function for doubleEveryOther.
It doubles a number (the second argument) if the index (the first argument)
is even. -}
doubleAtEvenIndex :: (Integer, Integer) -> Integer
doubleAtEvenIndex (index, n)
| index `mod` 2 == 0 = n * 2
| otherwise = n
-- doubleEveryOther doubles every other integer in an array.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther [] = []
doubleEveryOther v = map doubleAtEvenIndex (zip [1..] v)
-- sumDigits sums the digits in a list of integers.
sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:xs) = sum (toDigits x) + sumDigits xs
{- validate validates the creditCardNumber using the Luhn formula:
- Double the value of every second digit beginning from the right.
- Add the digits of the doubled values and the undoubled digits from the
original number.
- Calculate the remainder when the sum is divided by 10.
- If the result equals 0, then the number is valid. -}
validate :: Integer -> Bool
validate creditCardNumber = digitSum `mod` 10 == 0
where
digitSum = sumDigits $ doubleEveryOther $ toDigitsRev creditCardNumber
{- isValid exists purely for cosmetic reasons. It returns a string with the
credit card number and whether it is valid according to the Luhn algorithm
(see `validate`). -}
isValid :: Integer -> String
isValid creditCardNumber = case validate creditCardNumber of
True -> "Credit card number " ++ show creditCardNumber ++ " is valid!"
False -> "Credit card number " ++ show creditCardNumber ++ " is invalid."
main :: IO ()
main = do
putStrLn $ isValid 4012888888881881 -- Valid
putStrLn $ isValid 4012888888881882 -- Invalid
</code></pre>
|
[] |
[
{
"body": "<p>The way you have divided the problem into subproblems seems fine, so I'll comment on the way you have solved each subproblem.</p>\n\n<ul>\n<li><p><code>toDigits</code>: With the strategy of using <code>show</code> to generate a string and then convert each element in that string back to a number, you could also use <code>read :: Read a => String -> a</code> which takes a string (remember that <code>String</code> is an alias for <code>[Char]</code>, so <code>[c]</code> is a string with one character in it) and parses and returns a <em><code>Read a => a</code></em> which in this case is <code>Integer</code> (inferred from the type signature).</p>\n\n<pre><code>toDigits :: Integer -> [Integer]\ntoDigits\n | n > 0 = map (\\c -> read [c]) (show n)\n | otherwise = []\n</code></pre>\n\n<p>Even though the function becomes less robust, I might still move the error handling of non-positive numbers out of it and handle errors earlier in the chain of function calls. This might look like:</p>\n\n<pre><code>toDigits :: Integer -> [Integer]\ntoDigits n = map (\\c -> read [c]) (show n)\n</code></pre>\n\n<p>A fancy name for the function <code>\\c -> [c]</code> is <code>return</code>. Doing a few transformations this function could look like:</p>\n\n<pre><code>toDigits n = map (\\c -> read [c]) (show n)\ntoDigits n = map (\\c -> read (return c)) (show n)\ntoDigits n = map (\\c -> (read . return) c) (show n)\ntoDigits n = map (read . return) (show n)\ntoDigits = map (read . return) . show\n</code></pre>\n\n<p>with a final result of:</p>\n\n<pre><code>toDigits :: Integer -> [Integer]\ntoDigits = map (read . return) . show\n</code></pre>\n\n<p>Another strategy is to recursively remove the last digit from <code>n</code> using integer modulo / division. This has the peculiar side-effect that you'll generate the list backwards (because you start by adding the least significant digit). But since this is what you wanted after all, you're just saving a <code>reverse</code> here:</p>\n\n<pre><code>toDigitsRev :: Integer -> [Integer]\ntoDigitsRev n\n | n <= 0 = []\n | otherwise = (n `rem` 10) : toDigits' (n `quot` 10)\n</code></pre>\n\n<p>Here, <code>rem</code> is remainder and <code>quot</code> is integer division. There's <code>mod</code> and <code>div</code>, but they only differ for negative integers. I like this solution better because converting something to <code>String</code> and then back seems a bit screwy. Still, it's very readable.</p>\n\n<p>Another thing you could do here is to remove explicit recursion by using a higher-order function. In this case it might be <code>unfoldr :: (b -> Maybe (a, b)) -> b -> [a]</code> which produces a list of values (the digits) by feeding an input (<code>n</code>) to a function again and again with one digit less each time.</p>\n\n<pre><code>import Data.List (unfoldr)\nimport Data.Tuple (swap)\n\ntoDigitsRev :: Integer -> [Integer]\ntoDigitsRev n = unfoldr next n\n where\n next 0 = Nothing\n next n = Just (swap (n `divMod` 10))\n</code></pre>\n\n<p>For example, <code>12345 `divMod` 10</code> produces both the division and the remainder, <code>(1234, 5)</code>. Unfortunately, <code>unfoldr</code> expects the digit to be in the first part (with type <em><code>a</code></em>) and the next <code>n</code> to be in the second part (with type <em><code>b</code></em>), so we <code>swap</code> the result into <code>(5, 1234)</code>. A final improvement we can do here is to eta-reduce the outer <code>n</code> and use <code>quotRem</code> instead of <code>divMod</code>:</p>\n\n<pre><code>toDigitsRev :: Integer -> [Integer]\ntoDigitsRev = unfoldr next\n where\n next 0 = Nothing\n next n = Just (swap (n `quotRem` 10))\n</code></pre></li>\n<li><p><code>doubleEveryOther</code>: It's very good to see that you employ both <code>map</code> and <code>zip</code> here, but since you also need to write a manually recursive helper function, <code>doubleAtEvenIndex</code>, the effort seems a bit lost. Here's how I'd do it using explicit recursion only:</p>\n\n<pre><code>doubleEveryOther :: [Integer] -> [Integer]\ndoubleEveryOther (x:y:xs) = x : y*2 : doubleEveryOther xs\ndoubleEveryOther xs = xs\n</code></pre>\n\n<p>With pattern matching you can match arbitrarily deep into a data type, so for lists, you can match lists with at least two elements. The fallback pattern <code>xs</code> matches both lists of one and zero elements.</p>\n\n<p>How might a higher-order solution look like? You're already using <code>zip</code> and <code>map</code>, but rather than zipping the indices <code>[1..]</code> you could also zip the factors <code>[1,2,1,2,...]</code>:</p>\n\n<pre><code>> zip [1,2,3,4,5] [1,2,1,2,1]\n[(1,1),(2,2),(3,1),(4,2),(5,1)]\n</code></pre>\n\n<p>and then <code>map (\\(x,y) -> x * y)</code> the result:</p>\n\n<pre><code>> map (\\(x,y) -> x * y) (zip [1,2,3,4,5] [1,2,1,2,1])\n [(1 * 1),(2 * 2),(3 * 1),(4 * 2),(5 * 1)]\n= [1,4,3,8,5]\n</code></pre>\n\n<p>You can also write that as <code>map (uncurry (*))</code>, but something even neater is to use <code>zipWith (*)</code> which is a combination of <code>map</code> and <code>zip</code> where you save the intermediate tuple representation: You just take one element of each list and combine them using <code>(*)</code> to produce the zipped-with element.</p>\n\n<p>Finally, if you <code>cycle [1,2]</code> you get an infinite list of <code>[1,2,...]</code> which <code>zipWith</code> will shorten to the point that it matches the length of the digits:</p>\n\n<pre><code>doubleEveryOther :: [Integer] -> [Integer]\ndoubleEveryOther digits = zipWith (*) digits (cycle [1,2])\n</code></pre>\n\n<p>If we wanted to eta-reduce <code>digits</code>, we'd have a bit of a problem since it's not the last argument to <code>zipWith</code>. Fortunately we're zipping with a commutative operator, so we might as well write</p>\n\n<pre><code>doubleEveryOther :: [Integer] -> [Integer]\ndoubleEveryOther digits = zipWith (*) (cycle [1,2]) digits\n</code></pre>\n\n<p>which is equivalent to</p>\n\n<pre><code>doubleEveryOther :: [Integer] -> [Integer]\ndoubleEveryOther = zipWith (*) (cycle [1,2])\n</code></pre></li>\n<li><p><code>sumDigits</code>: Excellent. The only thing I can think of improving here is to remove explicit recursion. What we're doing here is to sum the digits of each integer in the list and then sum the result of that. You already found <code>sum</code> and <code>map</code>, so combining those:</p>\n\n<pre><code>sumDigits :: [Integer] -> Integer\nsumDigits ns = sum (map (\\n -> sum (toDigits n)) ns)\n</code></pre>\n\n<p>which can be eta-reduced as:</p>\n\n<pre><code>sumDigits ns = sum (map (\\n -> sum (toDigits n)) ns)\nsumDigits ns = sum (map (\\n -> (sum . toDigits) n) ns)\nsumDigits ns = sum (map (sum . toDigits) ns)\nsumDigits ns = (sum . map (sum . toDigits)) ns\nsumDigits = sum . map (sum . toDigits)\n</code></pre>\n\n<p>giving</p>\n\n<pre><code>sumDigits :: [Integer] -> Integer\nsumDigits = sum . map (sum . toDigits)\n</code></pre></li>\n<li><p><code>validate</code>: Excellent. The only thing I can think of improving here is to remove the <code>where</code>:</p>\n\n<pre><code>validate :: Integer -> Bool\nvalidate creditCardNumber =\n sumDigits (doubleEveryOther (toDigitsRev creditCardNumber)) `mod` 10 == 0\n</code></pre>\n\n<p>You <em>could</em> eta-reduce this, too, but I don't think it looks any better:</p>\n\n<pre><code>validate :: Integer -> Bool\nvalidate =\n (== 0) . (`mod` 10) . sumDigits . doubleEveryOther . toDigitsRev\n</code></pre></li>\n</ul>\n\n<p>At this point your solution would look like:</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>toDigits :: Integer -> [Integer]\ntoDigits = map (read . return) . show\n\ntoDigitsRev :: Integer -> [Integer]\ntoDigitsRev = unfoldr next\n where\n next 0 = Nothing\n next n = Just (swap (n `quotRem` 10))\n\ndoubleEveryOther :: [Integer] -> [Integer]\ndoubleEveryOther = zipWith (*) (cycle [1,2])\n\nsumDigits :: [Integer] -> Integer\nsumDigits = sum . map (sum . toDigits)\n\nvalidate :: Integer -> Bool\nvalidate creditCardNumber =\n sumDigits (doubleEveryOther (toDigitsRev creditCardNumber)) `mod` 10 == 0\n</code></pre>\n\n<p>The error handling that was removed from <code>toDigits</code> could be inserted back into <code>validate</code>, for which the name indicates that it actually does validation, and it could be extended to check that the input is not just a positive number but also has the exact amount of digits that a credit card has.</p>\n\n<p>I hope this feedback was useful and not too low-level.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T13:18:01.197",
"Id": "442817",
"Score": "0",
"body": "Simon, thank you *so* much! This is more than I could ever ask for (and, some of it, more than I understand at this point—which will come in handy as I learn more). Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T06:33:37.943",
"Id": "227448",
"ParentId": "226748",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "227448",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T15:40:01.303",
"Id": "226748",
"Score": "3",
"Tags": [
"beginner",
"programming-challenge",
"haskell",
"checksum"
],
"Title": "Introduction to Haskell: Validating credit card numbers"
}
|
226748
|
<p>In many cases, we want a variable-size array like <code>std::vector</code>, but we know an upper limit on the size. In such cases, the vector can be allocated on the stack. We have been doing this in C:</p>
<blockquote>
<pre><code>char a[100];
fgets(a, 100, STDIN);
</code></pre>
</blockquote>
<p>The problem is that the array doesn't know how many elements are actually there. All it knows is the "100" and it is up to us to keep track of the length of the string. <code>std::vector</code> doesn't allow us to allocate the memory on stack either. Therefore, I invested several weekends to write <code>static_vector</code> to solve this problem. To quote from my documentation:</p>
<blockquote>
<pre><code>template<typename T, std::size_t N>
class ethereal::static_vector< T, N >
</code></pre>
<p>Vector with stack storage.</p>
<p><code>static_vector</code> never allocates dynamic memory. (The <code>static_vector</code>
object itself may still be placed on the heap if the user prefers to.)
The elements are allocated as part of the vector object itself. This
can be useful when dynamic memory allocation is to be avoided. As a
result, there is a compile-time determined limit on the size, supplied
as the template parameter <code>N</code>. Internally, <code>static_vector</code> holds a
data member of type <code>std::array<std::aligned_storage_t<sizeof(T),
alignof(T)>, N></code>. [...]</p>
</blockquote>
<p><code>static_vector</code> can be used pretty much the same way <code>std::vector</code> can. It throws an exception of type <code>std::length_error</code> if the size limit is exceeded. See the documentation for details. As a bonus, the <code>std::vector<bool></code> problem is fixed.</p>
<pre><code>/**
* @file static_vector.hpp
*/
#ifndef INC_STATIC_VECTOR_HPP_o5GgaN4bAq
#define INC_STATIC_VECTOR_HPP_o5GgaN4bAq
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <limits>
#include <memory>
#include <new>
#include <type_traits>
/**
* @cond DETAIL
*/
#define REQUIRES(...) std::enable_if_t<(__VA_ARGS__), int> = 0
/**
* @endcond
*/
// inspired by Merriam-Webster's word of the day on August 20, 2019
namespace ethereal {
/**
* @cond DETAIL
*/
namespace detail {
template <typename It>
using iter_category_t = typename std::iterator_traits<It>::iterator_category;
template <typename It>
using iter_reference_t = typename std::iterator_traits<It>::reference;
// determines whether T is contextually convertible to bool
template <typename T>
struct is_boolean :std::is_constructible<bool, T> {};
template <typename T>
inline constexpr bool is_boolean_v = is_boolean<T>::value;
// define the copy constructor and copy assignment as deleted
template <bool Enabled>
struct copy_base {};
template <>
struct copy_base<false> {
copy_base() = default;
copy_base(const copy_base&) = delete;
copy_base(copy_base&&) = default;
copy_base& operator=(const copy_base&) = delete;
copy_base& operator=(copy_base&&) = default;
~copy_base() = default;
};
// define the move constructor and move assignment as deleted
template <bool Enabled>
struct move_base {};
template <>
struct move_base<false> {
move_base() = default;
move_base(const move_base&) = delete;
move_base(move_base&&) = delete;
move_base& operator=(const move_base&) = delete;
move_base& operator=(move_base&&) = delete;
~move_base() = default;
};
} // namespace detail
/**
* @endcond
*/
/**
* @brief Vector with stack storage.
*
* [Documentation removed due to Code Review limitations.]
*
* @tparam T The element type.
* @tparam N The maximum size of the vector.
*/
/**
* @cond DETAIL
*/
// The actual stuff is implemented in `detail::static_vector`, and
// make the actual `static_vector` derive from it to make the copy
// operations and move operations conditionally enabled. This
// shouldn't be exposed to Doxygen.
namespace detail {
/**
* @endcond
*/
template <typename T, std::size_t N>
class static_vector {
static_assert(std::is_destructible_v<T>,
"static_vector<T, N> requires std::is_destructible_v<T>");
static_assert(N <= std::numeric_limits<std::ptrdiff_t>::max(),
"static_vector<T, N> requires "
"N <= std::numeric_limits<std::ptrdiff_t>::max()");
public:
/**
* @name Member types
* @{
*/
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
/**
* @}
*/
/**
* @name Constructors
* @{
*/
/**
* @brief Constructs an empty vector.
*
* Does not construct any elements.
*/
static_vector() noexcept = default;
/**
* @brief Constructs a vector with `n` value-initialized
* elements.
*
* Equivalent to `static_vector()` followed by
* `insert_back(n);`.
*
* This function does not participate in overload resolution
* unless `std::is_default_constructible_v<T>`.
*
* @param n The number of elements to construct. Can be zero.
*/
template <typename..., typename U = T, REQUIRES(std::is_default_constructible_v<U>)>
explicit static_vector(size_type n)
{
insert_back(n);
}
/**
* @brief Constructs a vector with `n` elements
* copy-initialized from `value`.
*
* Equivalent to `static_vector()` followed by `insert_back(n,
* value);`.
*
* Unlike the corresponding constructor in `std::vector`, this
* constructor is `explicit`. Therefore,
* `static_vector<std::string, 3> vec = {2, "foo"}` is
* ill-formed.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*
* @param n The number of elements to construct. Can be
* zero.
* @param value The value of the elements.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
explicit static_vector(size_type n, const_reference value)
{
insert_back(n, value);
}
/**
* @brief Constructs a vector from the range `[first, last)`.
*
* Equivalent to `static_vector()` followed by
* `insert_back(first, last);`.
*
* This function does not participate in overload resolution
* unless `std::iterator_traits<It>::%iterator_category` is
* valid and denotes a type and `std::is_constructible_v<T,
* typename std::iterator_traits<It>::%reference>`.
*
* @param first `[first, last)` denotes the range to construct
* the vector from. The range can be empty.
* @param last See `first`.
*/
template <typename It, typename..., typename = detail::iter_category_t<It>,
REQUIRES(std::is_constructible_v<T, detail::iter_reference_t<It>>)>
static_vector(It first, It last)
{
insert_back(first, last);
}
/**
* @brief Constructs a vector from `ilist`.
*
* Equivalent to `static_vector(ilist.begin(), ilist.end())`.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*
* @param ilist The list of elements. Can be empty.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
static_vector(std::initializer_list<T> ilist)
:static_vector(ilist.begin(), ilist.end())
{
}
/**
* @brief Constructs a vector by copying from the elements in
* `other`.
*
* Equivalent to `static_vector(other.begin(), other.end())`.
*
* This function is defined as deleted unless
* `std::is_copy_constructible_v<T>`.
*
* @param other The vector to copy from.
*/
static_vector(const static_vector& other)
:static_vector(other.begin(), other.end())
{
}
/**
* @brief Constructs a vector by moving from the elements in
* `other`.
*
* Equivalent to
* `static_vector(std::make_move_iterator(other.begin()),
* std::make_move_iterator(other.end()))`.
*
* This function does not participate in overload resolution
* unless `std::is_move_constructible_v<T>`. This function is
* noexcept if and only if
* `std::is_nothrow_move_constructible_v<T>`.
*
* @param other The vector to move from.
*/
static_vector(static_vector&& other) noexcept(std::is_nothrow_move_constructible_v<T>)
:static_vector(std::make_move_iterator(other.begin()),
std::make_move_iterator(other.end()))
{
}
/**
* @}
*/
/**
* @name Assignment operators
* @{
*/
/**
* @brief Replaces the elements in the vector with `ilist`.
*
* Equivalent to `assign(ilist.begin(), ilist.end())`.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*
* @return `*this`
* @param ilist The list of elements. Can be empty.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
static_vector& operator=(std::initializer_list<T> ilist)
{
assign(ilist.begin(), ilist.end());
return *this;
}
/**
* @brief Replaces the elements in the vector with a copy of
* the elements in `other`.
*
* Equivalent to `assign(other.begin(), other.end())`.
*
* This function is defined as deleted unless
* `std::is_copy_constructible_v<T>`.
*
* @return `*this`
* @param other The vector to copy from.
*/
static_vector& operator=(const static_vector& other)
{
assign(other.begin(), other.end());
return *this;
}
/**
* @brief Replaces the elements in the vector with the
* elements in `other` moved.
*
* Equivalent to
* `assign(std::make_move_iterator(other.begin()),
* std::make_move_iterator(other.end()))`.
*
* Unless the move assignment operator of `std::vector`, this
* function actually moves the elements, therefore having
* linear time complexity.
*
* This function does not participate in overload resolution
* unless `std::is_move_constructible_v<T>`. This function is
* `noexcept` if and only if
* `std::is_nothrow_move_constructible_v<T>`.
*
* @return `*this`
* @param other The vector to move from.
*/
static_vector& operator=(static_vector&& other)
noexcept(std::is_nothrow_move_constructible_v<T>)
{
assign(std::make_move_iterator(other.begin()), std::make_move_iterator(other.end()));
return *this;
}
/**
* @}
*/
/**
* @brief Destroys the elements.
*
* Equivalent to `clear()`.
*/
~static_vector()
{
clear();
}
/**
* @name Iterators
* @{
*/
/**
* @brief Returns a non-constant iterator to the first
* element, or an unspecified value such that `begin() ==
* end()` if the vector is empty.
*/
[[nodiscard]] iterator begin() noexcept
{
return data();
}
/**
* @brief Returns a constant iterator to the first element, or
* an unspecified value such that `begin() == end()` if the
* vector is empty.
*/
[[nodiscard]] const_iterator begin() const noexcept
{
return data();
}
/**
* @brief Returns a non-constant iterator to one past the last
* element, or an unspecified value such that `begin() ==
* end()` is the vector is empty.
*/
[[nodiscard]] iterator end() noexcept
{
return data() + size();
}
/**
* @brief Returns a constant iterator to one past the last
* element, or an unspecified value such that `begin() ==
* end()` is the vector is empty.
*/
[[nodiscard]] const_iterator end() const noexcept
{
return data() + size();
}
/**
* @brief Returns `begin()`.
*/
[[nodiscard]] const_iterator cbegin() const noexcept
{
return begin();
}
/**
* @brief Returns `end()`.
*/
[[nodiscard]] const_iterator cend() const noexcept
{
return end();
}
/**
* @brief Returns `reverse_iterator(end())`.
*/
[[nodiscard]] reverse_iterator rbegin() noexcept
{
return reverse_iterator(end());
}
/**
* @brief Returns `const_reverse_iterator(end())`.
*/
[[nodiscard]] const_reverse_iterator rbegin() const noexcept
{
return const_reverse_iterator(end());
}
/**
* @brief Returns `reverse_iterator(begin())`.
*/
[[nodiscard]] reverse_iterator rend() noexcept
{
return reverse_iterator(begin());
}
/**
* @brief Returns `const_reverse_iterator(begin())`.
*/
[[nodiscard]] const_reverse_iterator rend() const noexcept
{
return const_reverse_iterator(begin());
}
/**
* @brief Returns `rbegin()`.
*/
[[nodiscard]] const_reverse_iterator crbegin() const noexcept
{
return rbegin();
}
/**
* @brief Returns `rend()`.
*/
[[nodiscard]] const_reverse_iterator crend() const noexcept
{
return rend();
}
/**
* @brief Returns the number of elements.
*/
[[nodiscard]] size_type size() const noexcept
{
return count;
}
/**
* @brief Returns the number of elements as a signed integer.
*
* Equivalent to `static_cast<difference_type>(size())`.
*/
[[nodiscard]] difference_type ssize() const noexcept
{
return static_cast<difference_type>(size());
}
/**
* @brief Returns the number of elements that can be inserted
* subject to the size limit.
*
* Equivalent to `max_size() - size()`.
*/
[[nodiscard]] size_type space() const noexcept
{
return max_size() - size();
}
/**
* @brief Returns the limit on the number of elements.
*
* @return `N`
*/
[[nodiscard]] size_type max_size() const noexcept
{
return N;
}
/**
* @brief Returns a `bool` value indicating whether the vector
* is empty.
*
* @return `size() == 0`
*/
[[nodiscard]] bool empty() const noexcept
{
return size() == 0;
}
/**
* @brief Returns a non-constant reference to the element with
* index `n`. The behavior is undefined if `n >= size()`.
*
* @return `begin()[n]`.
*/
reference operator[](size_type n)
{
assert(n < size());
return begin()[n];
}
/**
* @brief Returns a constant reference to the element with
* index `n`. The behavior is undefined if `n >= size()`.
*
* @return `begin()[n]`.
*/
const_reference operator[](size_type n) const
{
assert(n < size());
return begin()[n];
}
/**
* @brief If `n >= size()`, throws an exception of type
* `std::out_of_range`. Otherwise, returns `operator[](n)`.
*/
reference at(size_type n)
{
if (n >= size())
throw std::out_of_range{"static_vector<T, N>::at(n) out of range"};
return begin()[n];
}
/**
* @brief If `n >= size()`, throws an exception of type
* `std::out_of_range`. Otherwise, returns `operator[](n)`.
*/
const_reference at(size_type n) const
{
if (n >= size())
throw std::out_of_range{"static_vector<T, N>::at(n) out of range"};
return begin()[n];
}
/**
* @brief Returns a non-constant reference to the first
* element. The behavior is undefined if the vector is empty.
*
* @return `*begin()`
*/
reference front()
{
assert(!empty());
return *begin();
}
/**
* @brief Returns a constant reference to the first element.
* The behavior is undefined if the vector is empty.
*
* @return `*begin()`
*/
const_reference front() const
{
assert(!empty());
return *begin();
}
/**
* @brief Returns a non-constant reference to the last
* element. The behavior is undefined if the vector is empty.
*
* @return `*std::%prev(end())`
*/
reference back()
{
assert(!empty());
return *std::prev(end());
}
/**
* @brief Returns a constant reference to the last
* element. The behavior is undefined if the vector is empty.
*
* @return `*std::%prev(end())`
*/
const_reference back() const
{
assert(!empty());
return *std::prev(end());
}
/**
* @brief Returns a non-constant pointer to the first element.
* Returns an unspecified valid pointer if the vector is
* empty.
*/
[[nodiscard]] T* data() noexcept
{
return std::launder(reinterpret_cast<T*>(elems.data()));
}
/**
* @brief Returns a constant pointer to the first element.
* Returns an unspecified valid pointer if the vector is
* empty.
*/
[[nodiscard]] const T* data() const noexcept
{
return std::launder(reinterpret_cast<const T*>(elems.data()));
}
/**
* @}
*/
/**
* @name Insertion
* @{
*/
/**
* @brief Constructs an element with the arguments given
* before the element pointed to by `pos`, or at the end of
* the vector if `pos == end()`.
*
* Let `p` be an `iterator` such that `p == pos`. Equivalent
* to `emplace_back(std::forward<Args>(args)...);
* std::rotate(pos, std::prev(end()), end());`. `pos` points
* to the inserted element after the insertion. The behavior
* is undefined if `pos != end()` and `pos` doesn't point to
* an element in the vector.
*
* This function does not participate in overload resolution
* unless all of the following are `true`:
* `std::is_move_constructible_v<T>`,
* `std::is_move_assignable_v<T>`,
* `std::is_swappable_v<T>`, and
* `std::is_constructible_v<T, Args...>`.
*
* @return `p`.
* @param pos The position to insert the element.
* @param args The arguments used to construct the element.
*/
template <typename... Args, REQUIRES(std::is_constructible_v<T, Args...> &&
std::is_move_constructible_v<T> &&
std::is_move_assignable_v<T> &&
std::is_swappable_v<T>)>
iterator emplace(const_iterator pos, Args&&... args)
{
assert(begin() <= pos && pos <= end());
auto p = strip_const(pos);
emplace_back(std::forward<Args>(args)...);
std::rotate(p, std::prev(end()), end());
return p;
}
/**
* @brief Copies an element into the vector before the element
* pointed to by `pos`, or at the end of the vector if `pos ==
* end()`.
*
* Let `p` be an `iterator` such that `p == pos`. Equivalent
* to `emplace(pos, value)`. `pos` points to the inserted
* element after the insertion. The behavior is undefined if
* `pos != end()` and `pos` doesn't point to an element in the
* vector.
*
* This function does not participate in overload resolution
* unless all of the following are `true`:
* `std::is_copy_constructible_v<T>`,
* `std::is_move_constructible_v<T>`,
* `std::is_move_assignable_v<T>`, and
* `std::is_swappable_v<T>`.
*
* @return `p`.
* @param pos The position to insert the element.
* @param value The element to copy from.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U> &&
std::is_move_constructible_v<U> &&
std::is_move_assignable_v<U> &&
std::is_swappable_v<U>)>
iterator insert(const_iterator pos, const T& value)
{
return emplace(pos, value);
}
/**
* @brief Moves an element into the vector before the element
* pointed to by `pos`, or at the end of the vector if `pos ==
* end()`.
*
* Let `p` be an `iterator` such that `p == pos`. Equivalent
* to `emplace(pos, std::move(value))`. `pos` points to the
* inserted element after the insertion. The behavior is
* undefined if `pos != end()` and `pos` doesn't point to an
* element in the vector.
*
* This function does not participate in overload resolution
* unless all of the following are `true`:
* `std::is_move_constructible_v<T>`,
* `std::is_move_assignable_v<T>`, and
* `std::is_swappable_v<T>`.
*
* @return `p`.
* @param pos The position to insert the element.
* @param value The element to move from.
*/
template <typename..., typename U = T, REQUIRES(std::is_move_constructible_v<U> &&
std::is_move_assignable_v<U> &&
std::is_swappable_v<U>)>
iterator insert(const_iterator pos, T&& value)
{
return emplace(pos, std::move(value));
}
/**
* @brief Inserts `n` copies of the same element before the
* element pointed to by `pos`, or at the end of the vector if
* `pos == end()`.
*
* Let `p` be an `iterator` such that `p == pos`. Equivalent
* to `auto it = insert_back(n, value); std::rotate(p, it,
* end());`. If `n == 0`, `pos` points to the same position
* after the insertion; otherwise, `pos` points to the first
* inserted element after the insertion. The behavior is
* undefined if `pos != end()` and `pos` doesn't point to an
* element in the vector.
*
* This function does not participate in overload resolution
* unless all of the following are `true`:
* `std::is_copy_constructible_v<T>`,
* `std::is_move_constructible_v<T>`,
* `std::is_move_assignable_v<T>`, and
* `std::is_swappable_v<T>`.
*
* @return `p`.
* @param pos The position to insert the elements.
* @param n The number of elements to insert.
* @param value The value of the elements.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U> &&
std::is_move_constructible_v<U> &&
std::is_move_assignable_v<U> &&
std::is_swappable_v<U>)>
iterator insert(const_iterator pos, size_type n, const_reference value)
{
auto p = strip_const(pos);
auto it = insert_back(n, value);
std::rotate(p, it, end());
return p;
}
/**
* @brief Inserts a range of elements before the element
* pointed to by `pos`, or at the end of the vector if `pos ==
* end()`.
*
* Let `p` be an `iterator` such that `p == pos`. Equivalent
* to `auto it = insert_back(first, last); std::rotate(p, it,
* end());`. If `first == last`, `pos` points to the same
* position after the insertion; otherwise, `pos` points to
* the first inserted element after the insertion. The
* behavior is undefined if `pos != end()` and `pos` doesn't
* point to an element in the vector.
*
* This function does not participate in overload resolution
* unless `std::iterator_traits<It>::%iterator_category` is
* valid and denotes a type and all of the following are
* `true`: `std::is_constructible_v<T, typename
* std::iterator_traits<It>::%reference>`,
* `std::is_move_constructible_v<T>`,
* `std::is_move_assignable_v<T>`, and
* `std::is_swappable_v<T>`.
*
* @return `p`.
* @param pos The position to insert the elements.
* @param first `[first, last)` denotes the range of elements
* to insert.
* @param last See `first`.
*/
template <typename..., typename It, typename = detail::iter_category_t<It>,
REQUIRES(std::is_constructible_v<T, detail::iter_reference_t<It>> &&
std::is_move_constructible_v<T> &&
std::is_move_assignable_v<T> &&
std::is_swappable_v<T>)>
iterator insert(const_iterator pos, It first, It last)
{
assert(begin() <= pos && pos <= end());
auto p = strip_const(pos);
auto it = insert_back(first, last);
std::rotate(p, it, end());
return p;
}
/**
* @brief Inserts a list of elements before the element
* pointed to by `pos`, or at the end of the vector if `pos ==
* end()`.
*
* Equivalent to `insert(pos, ilist.begin(), ilist.end())`.
*
* This function does not participate in overload resolution
* unless all of the following are `true`:
* `std::is_copy_constructible_v<T>`,
* `std::is_move_constructible_v<T>`,
* `std::is_move_assignable_v<T>`, and
* `std::is_swappable_v<T>`.
*
* @return `p`, an iterator such that `p == pos`.
* @param pos The position to insert the elements.
* @param ilist The list of elements to insert.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U> &&
std::is_move_constructible_v<U> &&
std::is_move_assignable_v<U> &&
std::is_swappable_v<U>)>
iterator insert(const_iterator pos, std::initializer_list<T> ilist)
{
return insert(pos, ilist.begin(), ilist.end());
}
/**
* @brief Constructs an element with the given arguments at
* the end of the vector.
*
* If `max_size() - size() < 1`, throws an exception of type
* `std::length_error`. Otherwise, effectively calls `::%new
* (p) T(std::forward<Args>(args)...)` to construct the
* element, where `p` is a pointer of type `void*` that
* denotes the position in which the element is constructed.
*
* This function does not participate in overload resolution
* unless `std::is_constructible_v<T, Args...>`.
*
* @return A reference to the new element.
* @param args The arguments used to construct the element.
*/
template <typename... Args, REQUIRES(std::is_constructible_v<T, Args...>)>
reference emplace_back(Args&&... args)
{
ensure_space(1);
T* new_elem = ::new (static_cast<void*>(end())) T(std::forward<Args>(args)...);
++count;
return *new_elem;
}
/**
* @brief Copies an element to the end of the vector.
*
* Equivalent to `emplace_back(value)`.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*
* @param value The element to be copied from.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
void push_back(const T& value)
{
emplace_back(value);
}
/**
* @brief Moves an element to the end of the vector.
*
* Equivalent to `emplace_back(std::move(value))`.
*
* This function does not participate in overload resolution
* unless `std::is_move_constructible_v<T>`.
*
* @param value The element to be moved from.
*/
template <typename..., typename U = T, REQUIRES(std::is_move_constructible_v<U>)>
void push_back(T&& value)
{
emplace_back(std::move(value));
}
/**
* @brief Extended functionality. Inserts `n`
* value-initialized elements at the end of the vector.
*
* If `max_size() - size() < n`, throws an exception of type
* `std::length_error`. Otherwise, effectively calls
* `std::uninitialized_value_construct_n` to construct the
* elements.
*
* This function does not participate in overload resolution
* unless `std::is_default_constructible_v<T>`.
*
* @return An iterator that points to the first element
* inserted, or `end()` if `n == 0`.
* @param n The number of elements to insert. Can be zero.
*/
template <typename..., typename U = T, REQUIRES(std::is_default_constructible_v<U>)>
iterator insert_back(size_type n)
{
ensure_space(n);
return insert_back_unchecked(n);
}
/**
* @brief Extended functionality. Inserts `n` copies of
* `value` at the end of the vector.
*
* If `max_size() - size() < n`, throws an exception of type
* `std::length_error`. Otherwise, effectively calls
* `std::uninitialized_fill_n` to construct the elements.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*
* @return An iterator that points to the first element
* inserted, or `end()` if `n == 0`.
* @param n The number of elements to insert. Can be
* zero.
* @param value The element to copy from.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
iterator insert_back(size_type n, const_reference value)
{
ensure_space(n);
return insert_back_unchecked(n, value);
}
/**
* @brief Extended functionality. Inserts the range `[first,
* last)` at the end of the vector.
*
* If `std::iterator_traits<It>::%iterator_category` is
* convertible to `std::random_access_iterator_tag`, first
* checks if `max_size() - size() >= last - first`, throws an
* exception of type `std::length_error` if not, and
* effectively calls `std::uninitialized_copy` to construct
* the elements. Otherwise, equivalent to `for (; first !=
* last; ++first) emplace_back(*first);`.
*
* This function does not participate in overload resolution
* unless `std::iterator_traits<It>::%iterator_category` is
* valid and denotes a type and `std::is_constructible_v<T,
* detail::iter_reference_t<It>>`.
*
* @return An iterator that points to the first element
* inserted, or `end()` if `first == last`.
* @param first `[first, last)` denotes the range of elements
* to insert.
* @param last See `first`.
*/
template <typename It, typename..., typename Cat = detail::iter_category_t<It>,
REQUIRES(std::is_constructible_v<T, detail::iter_reference_t<It>>)>
iterator insert_back(It first, It last)
{
return insert_back_dispatch(first, last, Cat{});
}
/**
* @}
*/
/**
* @name Erasure
* @{
*/
/**
* @brief Removes the element pointed to by `pos`.
*
* Let `p` be an `iterator` such that `p == pos`. Equivalent
* to `std::move(std::next(p), end(), p); pop_back();`. The
* behavior is undefined if `pos` does not point to an element
* in the vector. (In particular, `pos` cannot be `end()`.)
*
* The function does not participate in overload resolution
* unless `std::is_move_assignable_v<T>`.
*
* @return An iterator to the element after the removed
* element, or `end()` if the last element was removed.
* @param pos The element to remove.
*/
template <typename..., typename U = T, REQUIRES(std::is_move_assignable_v<U>)>
iterator erase(const_iterator pos)
{
assert(begin() <= pos && pos < end());
auto p = strip_const(pos);
std::move(std::next(p), end(), p);
pop_back();
return p;
}
/**
* @brief Removes the range of elements `[first, last)`.
*
* Let `f` and `l` be `iterator`s such that `f == first` and
* `l == last`. Equivalent to `std::move(l, end(), f);
* pop_back(l - f);`. The behavior is undefined unless both
* `first` and `last` point to elements in the vector and
* `first <= last`.
*
* The function does not participate in overload resolution
* unless `std::is_move_assignable_v<T>`.
*
* @return If `first == last`, returns `f`. Otherwise,
* returns an iterator to the element after the removed
* elements, or `end()` if there is no such element.
* @param first `[first, last)` denotes the elements to
* remove.
* @param last See `first`.
*/
iterator erase(const_iterator first, const_iterator last)
{
assert(begin() <= first && first <= last && last <= end());
auto f = strip_const(first);
auto l = strip_const(last);
// std::move(i, j, k) requires that k is not in [i, j)
auto n = static_cast<size_type>(last - first);
if (n != 0) {
std::move(l, end(), f);
pop_back(n);
}
return f;
}
/**
* @brief Removes the last element.
*
* Equivalent to `pop_back(1)`. The behavior is undefined if
* `empty()`.
*/
void pop_back()
{
pop_back(1);
}
/**
* @brief Extended functionality. Removes the last `n`
* elements.
*
* Effectively calls `std::destroy` to destroy the elements.
* The behavior is undefined if `size() < n`.
*
* @param n The number of elements to remove. Can be zero.
*/
void pop_back(size_type n)
{
assert(n <= size());
std::destroy(end() - n, end());
count -= n;
}
/**
* @brief Removes all elements.
*
* Equivalent to `pop_back(size())`.
*/
void clear() noexcept
{
std::destroy(begin(), end());
count = 0;
}
/**
* @}
*/
/**
* @name Modifiers
* @{
*/
/**
* @brief Extended functionality. Replaces the contents of
* the vector with `n` value-initialized elements.
*
* Equivalent to `clear(); insert_back(n);`.
*
* This function does not participate in overload resolution
* unless `std::is_default_constructible_v<T>`.
*
* @param n The number of elements to replace the contents of
* the vector with.
*/
template <typename..., typename U = T, REQUIRES(std::is_default_constructible_v<U>)>
void assign(size_type n)
{
ensure_size(n);
clear();
insert_back_unchecked(n);
}
/**
* @brief Replaces the contents of the vector with `n` copies
* of `value`.
*
* Equivalent to `clear(); insert_back(n, value);`.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*
* @param n The number of elements to replace the contents
* of the vector with.
* @param value The value of the elements.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
void assign(size_type n, const_reference value)
{
ensure_size(n);
clear();
insert_back_unchecked(n, value);
}
/**
* @brief Replaces the contents of the vector with the
* elements in the range `[first, last)`.
*
* Equivalent to `clear(); insert_back(first, last);`.
*
* This function does not participate in overload resolution
* unless `std::iterator_traits<It>::%iterator_category` is
* valid and denotes a type and `std::is_constructible_v<T,
* std::iterator_traits<It>::%reference>`.
*
* @param first `[first, last)` denotes the range of elements
* to replace the vector with.
* @param last See `first`.
*/
template <typename It, typename..., typename Cat = detail::iter_category_t<It>,
REQUIRES(std::is_constructible_v<T, detail::iter_reference_t<It>>)>
void assign(It first, It last)
{
return assign_dispatch(first, last, Cat{});
}
/**
* @brief Replaces the contents of the vector with the list of
* elements `ilist`.
*
* Equivalent to `assign(ilist.begin(), ilist.end())`.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
void assign(std::initializer_list<T> ilist)
{
assign(ilist.begin(), ilist.end());
}
/**
* @brief Resizes the vector to `n` elements, where new
* elements are value-initialized.
*
* If `n < size()`, equivalent to `pop_back(size() - n)`;
* otherwise, equivalent to `insert_back(n - size())`.
*
* This function does not participate in overload resolution
* unless `std::is_default_constructible_v<T>`.
*/
template <typename..., typename U = T, REQUIRES(std::is_default_constructible_v<U>)>
void resize(size_type n)
{
if (n < size())
pop_back(size() - n);
else
insert_back(n - size());
}
/**
* @brief Resizes the vector to `n` elements, where new
* elements are copied from `value`.
*
* If `n < size()`, equivalent to `pop_back(size() - n)`;
* otherwise, equivalent to `insert_back(n - size(), value)`.
*
* This function does not participate in overload resolution
* unless `std::is_copy_constructible_v<T>`.
*/
template <typename..., typename U = T, REQUIRES(std::is_copy_constructible_v<U>)>
void resize(size_type n, const_reference value)
{
if (n < size())
pop_back(size() - n);
else
insert_back(n - size(), value);
}
/**
* @brief Swaps the vector with `other`.
*
* Let `common_size` be `std::min(size(), other.size())`. The
* first `common_size` elements are swapped as if by
* `std::swap_ranges`. Then, if the vectors differ in size,
* new elements are appended to the smaller vector by moving
* from the remaining elements in the bigger vector as if by
* `small.insert_back(std::make_move_iterator(big.begin() +
* common_size), std::make_move_iterator(big.end()));
* big.pop_back(big.size() - common_size)`, where `big` is the
* vector with more elements and `small` is the vector with
* fewer elements.
*
* This function does not participate in overload resolution
* unless `std::is_move_constructible_v<T> &&
* std::is_swappable_v<T>`. This function is `noexcept` if
* and only if `std::is_nothrow_move_constructible_v<T> &&
* std::is_nothrow_swappable_v<T>`.
*
* @param other The vector to swap with.
*/
template <typename..., typename U = T, REQUIRES(std::is_move_constructible_v<U> &&
std::is_swappable_v<U>)>
void swap(static_vector& other)
noexcept(std::is_nothrow_move_constructible_v<T> && std::is_nothrow_swappable_v<T>)
{
auto common_size = std::min(size(), other.size());
std::swap_ranges(begin(), begin() + common_size, other.begin());
if (size() > common_size) {
other.insert_back(std::make_move_iterator(begin() + common_size),
std::make_move_iterator(end()));
pop_back(size() - common_size);
} else {
insert_back(std::make_move_iterator(other.begin() + common_size),
std::make_move_iterator(other.end()));
other.pop_back(other.size() - common_size);
}
}
/**
* @}
*/
private:
iterator strip_const(const_iterator pos) noexcept
{
assert(begin() <= pos && pos <= end());
return const_cast<iterator>(pos);
}
void ensure_size(size_type n) const
{
if (max_size() < n)
throw std::length_error{"static_vector<T, N> not enough space"};
}
void ensure_space(size_type n) const
{
if (space() < n)
throw std::length_error{"static_vector<T, N> not enough space"};
}
iterator insert_back_unchecked(size_type n)
{
auto pos = end();
std::uninitialized_value_construct_n(pos, n);
count += n;
return pos;
}
iterator insert_back_unchecked(size_type n, const_reference value)
{
auto pos = end();
std::uninitialized_fill_n(pos, n, value);
count += n;
return pos;
}
template <typename It>
iterator insert_back_dispatch(It first, It last, std::random_access_iterator_tag)
{
auto n = static_cast<size_type>(last - first);
assert(n >= 0);
ensure_space(n);
return insert_back_dispatch_unchecked(first, last, n);
}
template <typename It>
iterator insert_back_dispatch(It first, It last, std::input_iterator_tag)
{
return insert_back_dispatch_unchecked(first, last);
}
template <typename It>
iterator insert_back_dispatch_unchecked(It first, It last, size_type n)
{
auto pos = end();
std::uninitialized_copy(first, last, pos);
count += n;
return pos;
}
template <typename It>
iterator insert_back_dispatch_unchecked(It first, It last)
{
auto pos = end();
for (; first != last; ++first)
emplace_back(*first);
return pos;
}
template <typename It>
void assign_dispatch(It first, It last, std::random_access_iterator_tag)
{
assert(first <= last);
auto n = static_cast<size_type>(last - first);
ensure_size(n);
clear();
insert_back_dispatch_unchecked(first, last, n);
}
template <typename It>
void assign_dispatch(It first, It last, std::input_iterator_tag)
{
clear();
insert_back_dispatch_unchecked(first, last);
}
std::array<std::aligned_storage_t<sizeof(T), alignof(T)>, N> elems;
std::size_t count{0}; // invariant: count <= N
}; // class static_vector
/**
* @cond DETAIL
*/
} // namespace detail
// actual static vector, with copy operations and move operations
// conditionally disabled
template <typename T, std::size_t N>
class static_vector :
public detail::static_vector<T, N>,
private detail::copy_base<std::is_copy_constructible_v<T>>,
private detail::move_base<std::is_move_constructible_v<T>>
{
using detail::static_vector<T, N>::static_vector;
};
/**
* @endcond
*/
/**
* @name Comparison operators
* @{
*/
/**
* @brief Checks whether two vectors are equal.
*
* Equivalent to `std::equal(lhs.begin(), lhs.end(), rhs.begin(),
* rhs.end())`. The behavior is undefined if this expression
* triggers undefined behavior.
*
* This function does not participate in overload resolution
* unless `decltype(a == b)` denotes a valid type and is
* contextually convertible to `bool`, where `a` and `b` are
* lvalues of type `const T`.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
*/
template <typename T, std::size_t N, typename...,
typename Result = decltype(std::declval<const T&>() == std::declval<const T&>()),
REQUIRES(detail::is_boolean_v<Result>)>
bool operator==(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs)
{
return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
/**
* @brief Checks whether two vectors are not equal.
*
* Equivalent to `!%ethereal::operator==(lhs, rhs)`. The behavior
* is undefined if this expression triggers undefined behavior.
*
* This function does not participate in overload resolution
* unless the aforementioned expression is valid.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
*/
template <typename T, std::size_t N>
auto operator!=(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs)
-> decltype(!ethereal::operator==(lhs, rhs)) // for SFINAE
{
// qualified call to disable ADL
return !ethereal::operator==(lhs, rhs);
}
/**
* @brief Checks whether the first vector lexicographically
* compares less than the second vector.
*
* Equivalent to `std::lexicographical_compare(lhs.begin(),
* lhs.end(), rhs.begin(), rhs.end())`. The behavior is undefined
* if this expression triggers undefined behavior.
*
* This function does not participate in overload resolution
* unless `decltype(a < b)` denotes a valid type and is
* contextually convertible to `bool`, where `a` and `b` are
* lvalues of type `const T`.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
*/
template <typename T, std::size_t N, typename...,
typename Result = decltype(std::declval<const T&>() < std::declval<const T&>()),
REQUIRES(detail::is_boolean_v<Result>)>
bool operator<(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
/**
* @brief Checks whether the first vector lexicographically
* compares greater than the second vector.
*
* Equivalent to `ethereal::operator<(rhs, lhs)`. The behavior is
* undefined if this expression triggers undefined behavior.
*
* This function does not participate in overload resolution
* unless the aforementioned expression is valid.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
*/
template <typename T, std::size_t N>
auto operator>(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs)
-> decltype(ethereal::operator<(rhs, lhs)) // for SFINAE
{
// qualified call to block ADL
return ethereal::operator<(rhs, lhs);
}
/**
* @brief Checks whether the first vector lexicographically
* compares less than or equal to the second vector.
*
* Equivalent to `!%ethereal::operator<(rhs, lhs)`. The behavior
* is undefined if this expression triggers undefined behavior.
*
* This function does not participate in overload resolution
* unless the aforementioned expression is valid.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
*/
template <typename T, std::size_t N>
auto operator<=(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs)
-> decltype(!ethereal::operator<(rhs, lhs))
{
return !ethereal::operator<(rhs, lhs);
}
/**
* @brief Checks whether the first vector lexicographically
* compares greater than or equal to the second vector.
*
* Equivalent to `!%ethereal::operator<(lhs, rhs)`. The behavior
* is undefined if this expression triggers undefined behavior.
*
* This function does not participate in overload resolution
* unless the aforementioned expression is valid.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
*/
template <typename T, std::size_t N>
auto operator>=(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs)
-> decltype(!ethereal::operator<(lhs, rhs))
{
return !ethereal::operator<(lhs, rhs);
}
/**
* @}
*/
/**
* @name Specialized algorithms
* @{
*/
/**
* @brief Swaps two vectors.
*
* Equivalent to `lhs.swap(rhs)`.
*
* This function does not participate in overload resolution
* unless `lhs.swap(rhs)` is valid. This function is `noexcept`
* if and only if `noexcept(lhs.swap(rhs))`.
*
* @param lhs The first vector.
* @param rhs The second vector.
*/
template <typename T, std::size_t N>
auto swap(static_vector<T, N>& lhs, static_vector<T, N>& rhs) noexcept(noexcept(lhs.swap(rhs)))
-> decltype(lhs.swap(rhs)) // for SFINAE
{
lhs.swap(rhs);
}
/**
* @brief Performs three-way lexicographical comparison on two
* vectors with a custom comparator.
*
* If `std::lexicographical_compare(lhs.begin(), lhs.end(),
* rhs.begin(), rhs.end(), pred)`, returns a negative value;
* otherwise, if `std::lexicographical_compare(rhs.begin(),
* rhs.end(), lhs.begin(), lhs.end(), pred)`, returns a positive
* value; otherwise, returns `0`. The behavior is undefined
* unless `pred` induces a strict weak ordering on the values.
*
* This function does not participate in overload resolution
* unless `decltype(pred(a, b))` denotes a valid type and is
* contextually convertible to `bool`, where `a` and `b` are
* lvalue expressions of type `const T`.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
* @param pred The comparator.
*/
template <typename T, std::size_t N, typename Pred, typename...,
typename Result = decltype(std::declval<Pred&>()(std::declval<const T&>(),
std::declval<const T&>())),
REQUIRES(detail::is_boolean_v<Result>)>
int compare(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs, Pred pred)
{
auto common_size = std::min(lhs.size(), rhs.size());
for (typename static_vector<T, N>::size_type i = 0; i < common_size; ++i) {
if (pred(lhs[i], rhs[i]))
return -1;
else if (pred(rhs[i], lhs[i]))
return 1;
}
return lhs.ssize() - rhs.ssize();
}
/**
* @brief Performs three-way lexicographical comparison on two
* vectors.
*
* Equivalent to `compare(lhs, rhs, std::less<>{})`. The behavior
* is undefined unless `std::less<>{}` induces a strict weak
* ordering on the values.
*
* This function does not participate in overload resolution
* unless `compare(lhs, rhs, std::less<>{})` is valid.
*
* @param lhs The left operand of the comparison.
* @param rhs The right operand of the comparison.
*/
template <typename T, std::size_t N>
auto compare(const static_vector<T, N>& lhs, const static_vector<T, N>& rhs)
-> decltype(ethereal::compare(lhs, rhs, std::less<>{})) // for SFINAE
{
// qualified call to block ADL
return ethereal::compare(lhs, rhs, std::less<>{});
}
/**
* @}
*/
} // namespace ethereal
#undef REQUIRES
#endif
</code></pre>
<p>There is some Doxygen stuff here, which reviewers can choose to review or not. As indicated by <code>[Documentation removed due to Code Review limitations.]</code>, the documentation is too long to fit in a Code Review question, so I have left it out. It can be found on <a href="https://pastebin.com/gJ0tR5rC" rel="nofollow noreferrer">pastebin</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:19:14.157",
"Id": "440986",
"Score": "1",
"body": "You might want to consider creating a repository at GitHub or GitLab and create separate documentation. If people like the implementation having user documentation might be helpful. Having your own repository might be helpful in a job search as well, you can add a link to it to your cover letter or resume."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T18:22:53.737",
"Id": "441008",
"Score": "0",
"body": "Why don't you want to consider Boost?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T23:08:31.067",
"Id": "441021",
"Score": "0",
"body": "@MichaelK Well, I didn't really think of that. Consider this a self-exercise then :)"
}
] |
[
{
"body": "<p>What I hate most.<br>\nIs looking for the variables that the class uses to hold the values. IT took my 10 minutes to find them:</p>\n\n<pre><code> std::array<std::aligned_storage_t<sizeof(T), alignof(T)>, N> elems;\n std::size_t count{0}; // invariant: count <= N\n}; // class static_vector\n\n/**\n * @cond DETAIL\n */\n\n} // namespace detail\n</code></pre>\n\n<p>They are like three quarters of the way down the file. This is the most important part of the class it should not be hard to find them. If you are not going to put them at the top at least mark them in a way that we can search for them!</p>\n\n<p>You know why I searched for them. Because the constructors don't initialize them so I was wondering are they self initialized. So yes they are but it was hard to find them because they are not mentioned in the constructors. This is why I dislike this way of initializing the members. I want to look at the constructor and see all them members correctly initialized not rely on code review to search through the code and check (a bit pedantic as turning on warnings would tell me but still I hate it).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T03:41:31.143",
"Id": "441250",
"Score": "0",
"body": "Sorry to have stolen 10 minutes of your precious time! :) I have always been putting them at the very end of the class because it seems to be common practice (e.g., [NL.16](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rl-order)), but now that I think of it, the original intent is to make the public interface more visible. Given that I have created documentation, this doesn't seem necessary anymore, so I may as well put them at the beginning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:29:20.783",
"Id": "441281",
"Score": "1",
"body": "I know this is frustrating and your reviews are generally a delight to read but that is really more a rant than a code review. Especially given the rather high quality of the code for review this is not appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T19:45:18.837",
"Id": "441430",
"Score": "0",
"body": "@miscco I ran out of time to do the review because I could not find the things I need to validate the code and thus do the review. But saying that this is where I disagree with Bjorn. Always put the private variables at the top (so you have context). There is usually not a lot of them. Then the public interface then the protected interface and finally the private interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T04:19:57.043",
"Id": "441485",
"Score": "0",
"body": "@miscco I just saw the discussion between you and Martin York. Well, I actually upvoted the answer, but thank you for calling my code \"high quality\" :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T04:33:52.307",
"Id": "441489",
"Score": "0",
"body": "@L.F. As marco said hi quality code so not really that much to comment on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:30:26.720",
"Id": "441547",
"Score": "0",
"body": "@MartinYork I actually tried to review the code and I have to say I feel you. The member should definitely be at the top of the class. However, note that the compiler generated special member functions have their advantages especially with respect to exception specifications"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T18:20:34.767",
"Id": "226866",
"ParentId": "226757",
"Score": "1"
}
},
{
"body": "<p>Two bugs my tests didn't catch:</p>\n\n<h1>Self assignment</h1>\n\n<p>This is a serious bug. The copy assignment of the class works by clearing <code>*this</code> first and then insert the values using iterators. This causes problems with self assignment — the iterators are invalidated after the clear. The following program is flagged by valgrind for access to uninitialized memory:</p>\n\n<pre><code>static_vector<std::string, 5> sv(3, std::string(20, 'x'));\nsv = sv;\nstd::cout << sv[0] << \" \" << sv[1] << \" \" << sv[2] << \"\\n\";\n</code></pre>\n\n<p>This bug is not easily testable. I included self assignment tests but valgrind didn't fire. The code above also works fine if I replace <code>20</code> with <code>10</code>!</p>\n\n<p>Possible fix: for copy assignment, explicitly test for self-assignment, like</p>\n\n<pre><code>if (this == &other)\n return;\n</code></pre>\n\n<p>For <code>assign(iterator, iterator)</code>, state in the documentation that it's undefined behavior if the iterators point into <code>*this</code>. Or, more generally, if the elements in <code>*this</code> are accessed by copy constructing from the result of dereferencing the iterator. (Also affect other functions.)</p>\n\n<h1><code>#include <array></code></h1>\n\n<p>It's missing. I discovered this bug by running the test on a Windows machine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:39:07.837",
"Id": "226915",
"ParentId": "226757",
"Score": "4"
}
},
{
"body": "<p>A more normal code review :-)</p>\n\n<p>OK. This code is good. So anything I have to say is going to have be extremely nit picky to even say anything. So only bother to read if you want to see me at my nit pickiest (I am bored).</p>\n\n<hr>\n\n<p>I have one question. I don't understand this:</p>\n\n<p>OK. I don't understand this.</p>\n\n<pre><code> template <typename..., typename U = T, REQUIRES(std::is_default_constructible_v<U>)>\n explicit static_vector(size_type n)\n {\n insert_back(n);\n }\n</code></pre>\n\n<p>What is happening with the <code>...</code> in this context?</p>\n\n<hr>\n\n<h2>Ahhhh documentation tools</h2>\n\n<pre><code>**\n * @file static_vector.hpp\n */\n</code></pre>\n\n<p>Nothing more to say on the subject.<br>\nI''l delete the comments before doing any more reviews.</p>\n\n<p>OK. one more thing to say:</p>\n\n<pre><code> /**\n * @brief Returns `reverse_iterator(begin())`.\n */\n [[nodiscard]] reverse_iterator rend() noexcept\n {\n return reverse_iterator(begin());\n }\n</code></pre>\n\n<p>7 lines to do what you could have done in 1.</p>\n\n<p>OK time to invest some time into finding a vim plugin to fold documentation comments so they are not visible. Still want to see normal comments but documentation comments are not really useful for a code review (only the documentation tool generator).</p>\n\n<p>OK. one more real thing to say. Please be consistent with your spacing between comments.</p>\n\n<pre><code> reference operator[](size_type n)\n {\n assert(n < size());\n return begin()[n];\n }\n // MIY added comment.\n // Sometimes you leave a space beteen the function function and comment\n // Sometimes you don't. If I find a comment folding plugin that will\n // mean that sometimes there is a space between functions and sometimes\n // they are smashed together.\n /**\n * @brief Returns a constant reference to the element with\n * index `n`. The behavior is undefined if `n >= size()`.\n *\n * @return `begin()[n]`.\n */\n const_reference operator[](size_type n) const\n {\n assert(n < size());\n return begin()[n];\n }\n</code></pre>\n\n<hr>\n\n<p>Not sure I like this without protection.</p>\n\n<pre><code>#define REQUIRES(...) std::enable_if_t<(__VA_ARGS__), int> = 0\n</code></pre>\n\n<p>Especially since you <code>#undef</code> it at the end. Personally I would add a check around it to make sure that no other system is using it.</p>\n\n<pre><code>#ifdef REQUIRES\n#error \"This code depends on the macro REQUIRES but it is defined in your code.\"\n#endif\n#define REQUIRES(...) std::enable_if_t<(__VA_ARGS__), int> = 0\n</code></pre>\n\n<hr>\n\n<p>Wimsical</p>\n\n<pre><code>// inspired by Merriam-Webster's word of the day on August 20, 2019\nnamespace ethereal {\n</code></pre>\n\n<hr>\n\n<pre><code> template <typename It>\n using iter_category_t = typename std::iterator_traits<It>::iterator_category;\n</code></pre>\n\n<p>Type names ending in <code>_t</code> are reserved by POSIX. Not sure I want to tread on their territory. Though i suppose that is only in the global namespace. </p>\n\n<hr>\n\n<p>Not sure I like this style personally (disabling properties by inheritance) but I have seen it around (boost) so its been used before.</p>\n\n<p>OK. I have now read further into the code. Nice usage as it will depend on the type <code>T</code> and its properties. OK. Cool like it.</p>\n\n<pre><code> // define the copy constructor and copy assignment as deleted\n template <bool Enabled>\n struct copy_base {};\n\n // Put at least one blank line here.\n\n template <>\n struct copy_base<false> {\n copy_base() = default;\n copy_base(const copy_base&) = delete;\n copy_base(copy_base&&) = default;\n copy_base& operator=(const copy_base&) = delete;\n copy_base& operator=(copy_base&&) = default;\n ~copy_base() = default;\n };\n</code></pre>\n\n<p>My one complaint here is that it is hard to make out the <code>default</code> from <code>deleted</code>. I would group them together so you can at a glance see what is deleted and what is defaulted. I suppose its a common pattern that people know but in that case why not grab one of the standard version (like boost).</p>\n\n<hr>\n\n<p>It's a nice touch to check <code>N</code> here.</p>\n\n<pre><code> class static_vector {\n static_assert(std::is_destructible_v<T>,\n \"static_vector<T, N> requires std::is_destructible_v<T>\");\n static_assert(N <= std::numeric_limits<std::ptrdiff_t>::max(),\n \"static_vector<T, N> requires \"\n \"N <= std::numeric_limits<std::ptrdiff_t>::max()\");\n</code></pre>\n\n<p>But the test <code>N <= std::numeric_limits<std::ptrdiff_t>::max()</code> is not accurate. I would suspect most systems have a limit on the size of the stack frame (OK its been over two decades since I wrote a compiler so that may not be true on modern hardware).</p>\n\n<p>In the old days the size of the stack frame (for the kids the chunk of memory reserved for local variables when a function is entered) was limited. Usually by hardware but sometimes also be compiler. This test is a bit meaningless as <code>std::numeric_limits<std::ptrdiff_t>::max()</code> is very large.</p>\n\n<p>Having a quick look at <code>GCC</code> I found this: <a href=\"https://gcc.gnu.org/onlinedocs/gcc-3.0.4/gcc/Stack-Checking.html\" rel=\"nofollow noreferrer\">https://gcc.gnu.org/onlinedocs/gcc-3.0.4/gcc/Stack-Checking.html</a></p>\n\n<blockquote>\n <p>STACK_CHECK_MAX_FRAME_SIZE<br>\n The maximum size of a stack frame, in bytes. GCC will generate probe instructions in non-leaf functions to ensure at least this many bytes of stack are available. If a stack frame is larger than this size, stack checking will not be reliable and GCC will issue a warning. The default is chosen so that GCC only generates one instruction on most systems. You should normally not change the default value of this macro. </p>\n</blockquote>\n\n<hr>\n\n<p>As mention before I have to find a check you have initialized all the members.</p>\n\n<pre><code> static_vector() noexcept = default;\n</code></pre>\n\n<p>That makes it hard to do a code review.<br>\nThink of the people you work with. Do you have a documented way to find members so you can check that they are all being correctly initialized.</p>\n\n<hr>\n\n<p>All of these function. I would have made one liners.</p>\n\n<pre><code> [[nodiscard]] iterator begin() noexcept\n {\n return data();\n }\n [[nodiscard]] const_iterator begin() const noexcept\n {\n return data();\n }\n // etc\n</code></pre>\n\n<hr>\n\n<p>What's this for?</p>\n\n<pre><code> [[nodiscard]] difference_type ssize() const noexcept\n {\n return static_cast<difference_type>(size());\n }\n</code></pre>\n\n<p>Why is it diffent from <code>size()</code>?</p>\n\n<hr>\n\n<p>Bad habit.<br>\nNot putting the braces around the throw.</p>\n\n<pre><code> reference at(size_type n)\n {\n if (n >= size())\n throw std::out_of_range{\"static_vector<T, N>::at(n) out of range\"};\n return begin()[n];\n }\n</code></pre>\n\n<hr>\n\n<p>Should this not return <code>pointer</code>?</p>\n\n<pre><code> [[nodiscard]] T* data() noexcept\n {\n return std::launder(reinterpret_cast<T*>(elems.data()));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T06:02:56.683",
"Id": "441506",
"Score": "0",
"body": "Wow, this is nice! The `typename ...` is used to prevent over smart users from manually specifying the template arguments. `ssize` is a useful feature that is standardized in c++20, so I decided to include it. (I used it in `compare`.) `data` should return `T*` not `pointer` because `pointer` has a different meaning (in the same way you don't want to return an `iterator` here, though `using iterator = T*;`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T11:18:31.013",
"Id": "441541",
"Score": "0",
"body": "As a side note, the `copy_base` idiom is what the standard library uses to forward traits to wrapper objects / containers. A really nice talk featuring this and even why there is use for `const T&&` is from Simon Brand https://www.youtube.com/watch?v=J4A2B9eexiw"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T05:42:33.693",
"Id": "226980",
"ParentId": "226757",
"Score": "2"
}
},
{
"body": "<p>Might I suggest taking a look at ETL(embedded template library) to get a comparison of your implementations? <a href=\"https://github.com/ETLCPP/etl/blob/master/include/etl/vector.h\" rel=\"nofollow noreferrer\">https://github.com/ETLCPP/etl/blob/master/include/etl/vector.h</a></p>\n\n<p>This is a whole library specifically designed to do what you are trying to accomplish. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-30T15:46:48.827",
"Id": "227182",
"ParentId": "226757",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "226980",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T18:40:33.770",
"Id": "226757",
"Score": "4",
"Tags": [
"c++",
"c++17",
"template-meta-programming",
"stl",
"doxygen"
],
"Title": "static_vector: a vector with stack storage"
}
|
226757
|
<h3>Description</h3>
<p>In a time where thin clients, web browsers, web services and micro services are prevalent, we tend to forget we still have to deal with thick and smart clients. Many applications in B2B still use the latter. It is common in such clients that the user can perform a set of actions on the client before synchronizing to the server. </p>
<p>One such scenario is a master-detail view where the user can <strong>edit</strong>, <strong>cancel</strong> and <strong>apply</strong> changes on the master. On edit, a detail view is activated where the user can <strong>accept</strong> or <strong>cancel</strong> the changes for that particular edit. Each time the user accepts changes, they are considered the latest state of the entity. On a next edit, when cancelling, the state gets reverted to the last accepted state. Only when the master view is applied, all changes are pushed to the server. When the master view gets cancelled, all changes from the details are also reverted back to initial state.</p>
<h3>API</h3>
<p>Microsoft had a solution for this: <a href="https://docs.microsoft.com/en-us/ef/ef6/fundamentals/disconnected-entities/self-tracking-entities/" rel="nofollow noreferrer">Self-tracking Entities</a>. But that API is no longer supported. Although other API's are available and/or being developed, I wanted to make an attempt at writing a low-level API as suggested by Microsoft:
<em>..or writing custom code using the low-level change tracking APIs.</em> I'm not sure I want to maintain or extend this API. I will probably first check whether the current version survives Code Review.</p>
<p>Current Features:</p>
<ul>
<li>accept/reject changes to a complex object</li>
<li>can traverse object trees and cyclic graphs (hierarchical change tracking)</li>
<li>context-free change tracking that works on POCO</li>
<li>tracking a detail entity while the master is also being tracked independantly (composite change tracking)</li>
<li>stacking change trackers on a single entity (multi-level change tracking)</li>
</ul>
<p>Currently Out-of-scope:</p>
<ul>
<li>tracking items in collections</li>
<li>allowing not to track navigation properties</li>
</ul>
<h3>Questions</h3>
<blockquote>
<ul>
<li>Does it make sense to make a custom API or should I use an existing one?</li>
<li>Is the API extensible, usable, maintainable?</li>
<li>Am I adhering to code conventions and best practices?</li>
</ul>
</blockquote>
<h3>Code</h3>
<p>The main object tracker for a consumer <code>ObjectEditor</code> allows for multi-level object tracker by implementing <code>IEditableObject</code>. <code>BeginEdit</code> starts an atomic update session. <code>EndEdit</code> accepts the current update, while <code>CancelEdit</code> reverts back to the last <code>EndEdit</code> or initial state. <code>RejectChanges</code> reverts back to initial state, regardless of number of edits that have been made, and <code>AcceptChanges</code> accepts all ongoing edits.</p>
<pre><code>public sealed class ObjectEditor : IRevertibleChangeTracking, IEditableObject
{
private readonly Stack<IRevertibleChangeTracking> trackers = new Stack<IRevertibleChangeTracking>();
public bool IsChanged { get; private set; }
public object Source { get; }
public ObjectEditor(object source) => Source = source ?? throw new ArgumentNullException(nameof(source));
public void AcceptChanges() => UntilEmpty(() => EndEdit());
public void RejectChanges() => UntilEmpty(() => CancelEdit());
public void BeginEdit() => trackers.Push(new ComplexObjectTracker(Source));
public void CancelEdit() => Pop(tracker => tracker.RejectChanges());
public void EndEdit() => Pop(tracker => tracker.AcceptChanges());
private void UntilEmpty(Action operation)
{
while (trackers.Any()) operation();
}
private void Pop(Action<IRevertibleChangeTracking> operation)
{
if (!trackers.Any()) return;
var tracker = trackers.Pop();
operation(tracker);
}
}
</code></pre>
<p>Internally, instances of <code>ComplexObjectTracker</code> are used to track entities, their properties and recursively track the entire object graph.</p>
<pre><code>public class ComplexObjectTracker : IRevertibleChangeTracking
{
public bool IsChanged { get; private set; }
public object Source { get; }
HashSet<object> Visited { get; }
List<IRevertibleChangeTracking> PropertyTrackers { get; }
public ComplexObjectTracker(object source, HashSet<object> visited = null)
{
Source = source ?? throw new ArgumentNullException(nameof(source));
Visited = visited ?? new HashSet<object>();
IsChanged = true;
Visited.Add(Source);
PropertyTrackers = (from p
in source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !p.GetIndexParameters().Any()
select p).Select(p => CreateChangeTracker(p)).ToList();
}
public void AcceptChanges() => Invoke(p => p.AcceptChanges());
public void RejectChanges() => Invoke(p => p.RejectChanges());
private void Invoke(Action<IRevertibleChangeTracking> operation)
{
PropertyTrackers.ForEach(operation);
IsChanged = false;
}
private IRevertibleChangeTracking CreateChangeTracker(PropertyInfo property)
{
if (property.PropertyType.IsValueType)
{
return new PropertyReferenceTracker(Source, property);
}
return new DeepPropertyTracker(Source, property, Visited);
}
}
</code></pre>
<p>As you can see, currently only two types of property tracking are implemented: <code>PropertyReferenceTracker</code> and <code>DeepPropertyTracker</code>. In future versions, additional trackers could be provided to track collections (shallow, deep, with ordering or not, etc).</p>
<pre><code>public class PropertyReferenceTracker : IRevertibleChangeTracking
{
public bool IsChanged { get; private set; }
public object DeclaringInstance { get; }
public object PropertyValue { get; }
public PropertyInfo Property { get; }
public PropertyReferenceTracker(object declaringInstance, PropertyInfo property)
{
DeclaringInstance = declaringInstance ?? throw new ArgumentNullException(nameof(declaringInstance));
Property = property ?? throw new ArgumentNullException(nameof(property));
PropertyValue = Property.GetValue(DeclaringInstance);
IsChanged = true;
}
public virtual void AcceptChanges() => IsChanged = false;
public virtual void RejectChanges()
{
if (Property.CanWrite)
{
Property.SetValue(DeclaringInstance, PropertyValue);
}
IsChanged = false;
}
}
public class DeepPropertyTracker : PropertyReferenceTracker
{
public IRevertibleChangeTracking deepTracker { get; }
public DeepPropertyTracker(object declaringInstance, PropertyInfo property, HashSet<object> visited)
: base(declaringInstance, property)
{
deepTracker = PropertyValue != null && !visited.Contains(PropertyValue) ? new ComplexObjectTracker(PropertyValue, visited) : null;
}
public override void AcceptChanges()
{
deepTracker?.AcceptChanges();
base.AcceptChanges();
}
public override void RejectChanges()
{
deepTracker?.RejectChanges();
base.RejectChanges();
}
}
</code></pre>
<h3>Usage Scenario</h3>
<p>I made a small demo using a trivial POCO <code>Employee</code> to show the current features. As you can see, there is a graph of a potential infinite object depth. This should show how object graphs are handled.</p>
<pre><code>class Employee
{
public DateTime BirthDate { get; set; }
public string FirstName { get; set; }
public string Name { get; set; }
public Employee Manager { get; set; }
}
</code></pre>
<p>And some unit tests to verify the behavior of change tracking.</p>
<pre><code>[TestClass]
public class Fixtures
{
private Employee employee;
[TestInitialize]
public void TestInit()
{
var manager = new Employee
{
BirthDate = new DateTime(1980, 1, 1),
FirstName = "John",
Name = "Doe"
};
employee = new Employee
{
BirthDate = new DateTime(2000, 1, 1),
FirstName = "Rembrandth",
Name = "Smith",
Manager = manager
};
}
[TestMethod]
public void EndEdit()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Name, "Smith");
employee.Name = "X";
editor.EndEdit();
Assert.AreEqual(employee.Name, "X");
}
[TestMethod]
public void CancelEdit()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Name, "Smith");
employee.Name = "X";
editor.CancelEdit();
Assert.AreEqual(employee.Name, "Smith");
}
[TestMethod]
public void EndHierarchicalEdit()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
employee.Manager.Name = "X";
editor.EndEdit();
Assert.AreEqual(employee.Manager.Name, "X");
}
[TestMethod]
public void EndHierarchicalEdit_OtherRef()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
employee.Manager = new Employee
{
BirthDate = new DateTime(1789, 1, 1),
FirstName = "Juan",
Name = "Carlos"
};
editor.EndEdit();
Assert.AreEqual(employee.Manager.Name, "Carlos");
}
[TestMethod]
public void CancelHierarchicalEdit_OtherRef()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
employee.Manager = new Employee
{
BirthDate = new DateTime(1789, 1, 1),
FirstName = "Juan",
Name = "Carlos"
};
editor.CancelEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
}
[TestMethod]
public void CancelHierarchicalEdit()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
employee.Manager.Name = "X";
editor.CancelEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
}
[TestMethod]
public void EndCompositeEdit()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
employee.Manager.Name = "X";
{
var compositeEditor = new ObjectEditor(employee.Manager);
compositeEditor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "X");
employee.Manager.Name = "Y";
compositeEditor.EndEdit();
Assert.AreEqual(employee.Manager.Name, "Y");
}
editor.EndEdit();
Assert.AreEqual(employee.Manager.Name, "Y");
}
[TestMethod]
public void CancelCompositeEdit()
{
var editor = new ObjectEditor(employee);
editor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
employee.Manager.Name = "X";
{
var compositeEditor = new ObjectEditor(employee.Manager);
compositeEditor.BeginEdit();
Assert.AreEqual(employee.Manager.Name, "X");
employee.Manager.Name = "Y";
compositeEditor.EndEdit();
Assert.AreEqual(employee.Manager.Name, "Y");
}
editor.CancelEdit();
Assert.AreEqual(employee.Manager.Name, "Doe");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T21:16:10.097",
"Id": "440942",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/97829/discussion-on-question-by-dfhwze-change-tracking-poco-entities)."
}
] |
[
{
"body": "<p>From where I'm standing it looks like this...</p>\n\n<p><strong>usability</strong></p>\n\n<ul>\n<li><p><code>BeginEdit</code> & <code>EndEdit</code> seem to be unsafe in use. What happens when I call either of them multiple times? Do they have to match? I mean, do I have to call <code>EndEdit</code> as many times as I called <code>BeginEdit</code>? Probably yes, but the API isn't clear about that. Or what would happen when I call <code>EndEdit</code> without <code>BeginEdit</code>? These scenarios should not be possible. What I think would be more intuitive and also reliable is this:</p>\n\n<ul>\n<li><p>let <code>BeginEdit</code> return a new interface</p>\n\n<pre><code>public interface IEditing : IDisposabe, IRevertibleChangeTracking {}\n</code></pre></li>\n<li><p>this can used with <code>using</code> or any other disposable session mechanism</p>\n\n<pre><code>using(var editing = objectEditor.BeginEdit()) // <-- IEditing\n{\n // make changes...\n}\n</code></pre></li>\n<li><p>throw an <code>InvalidOperationException</code> when <code>BeginEdit</code> is called multiple times for an object</p></li>\n<li><code>Dispose</code> would end the session and would also throw the same exception when there are any uncommited changes. This would be similar to an application warning you about unsaved changes when you are closing the editor. Of course the user should have other APIs to prevent that. The exception would be the last resort warning.</li>\n<li>let the user only have the original APIs from the <code>IRevertibleChangeTracking</code>. The pair <code>Begin/EndEdit</code> are too confusing.</li>\n</ul></li>\n<li>and there is also a question: what is going to happen when I try to edit an object with two editors (<code>UI</code>s) at the same time? Should this be possible or prohibited? How will conflicts be resolved?</li>\n<li>you are using a <code>Stack</code> for tracking changes internally. I guess this means that <code>BeginEdit</code> & <code>EndEdit</code> work like <code>QuickSave</code> and <code>Undo</code>. Again, I think it would be more intuitive if there were actually such methods as <code>TakeSnapshot</code> and <code>Undo</code>. This however would require the use to be able to see how many snapshots there are (as a counter or <code>ObjectEditor</code> could itself be <code>IEnumerable<OfSomething></code>) and when he tries to <code>Undo</code> more, then <code>InvalidOperationException</code> should be raised.</li>\n</ul>\n\n<p><strong>clean-code</strong> </p>\n\n<ul>\n<li><p>some of your members have access modifiers whereas others don't and there is no pattern ;-P </p></li>\n<li><p>I would call <code>ComplexObjectTracker</code> just <code>ObjectTracker</code>. No need to confuse the user that there is anything complex. Especially that there is no <code>ObjectTracker</code> yet so why is this one <em>complex</em>? </p></li>\n<li><p>I also think that all classes but the <code>ObjectEditor</code> should be <code>internal</code> and the user should see only the interfaces.</p></li>\n<li><p>there is the <code>PropertyReferenceTracker</code> but the derived class is named <code>DeepPropertyTracker</code> and not <em><code>DeepPropertyReferenceTracker</code></em>. I would remove the word <em><code>Reference</code></em> from the name. It's confusing. See here where a <em>Property<strong>Reference</strong>Tracker</em> is created for a value-type and a deep-tracker for a reference type:</p>\n\n<blockquote>\n<pre><code>private IRevertibleChangeTracking CreateChangeTracker(PropertyInfo property)\n{\n if (property.PropertyType.IsValueType)\n {\n return new PropertyReferenceTracker(Source, property);\n }\n\n return new DeepPropertyTracker(Source, property, Visited);\n }\n</code></pre>\n</blockquote></li>\n<li><p>Are you sure this should even be <code>public</code>? And the name...</p>\n\n<blockquote>\n<pre><code>public IRevertibleChangeTracking deepTracker { get; }\n</code></pre>\n</blockquote></li>\n</ul>\n\n<p><strong>misc</strong></p>\n\n<ul>\n<li>I don't think that setting <code>IsChanged = true;</code> for all properties, regardless whether they are actually changed or not is such a good idea. This would make it only more difficult to view the changes... that might actually not be there. It would also unnecessarily overwrite unmodified values. Having such helpers as <code>OldValue</code> and <code>NewValue</code> would also be very useful for rendering debug views or other summaries.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T06:13:28.040",
"Id": "440959",
"Score": "1",
"body": "I'll edit the answer when I find anything else..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T07:20:58.677",
"Id": "440961",
"Score": "0",
"body": "_what is going to happen when I try to edit an object with two editors (UIs) at the same time?_ last one wins, but this is not clear from my spec"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T07:22:39.053",
"Id": "440962",
"Score": "0",
"body": "_What happens when I call either of them multiple times? Do they have to match?_ it's possible to call them multiple times, it's like the matching parenthesis problem. You can nest edits (like a stack). It's also a sandbox, no exception when called if no matching end/begin pattern. perhaps throwing the exception as you suggest is a safer alternative"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T06:07:59.550",
"Id": "226764",
"ParentId": "226759",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226764",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T19:21:14.387",
"Id": "226759",
"Score": "6",
"Tags": [
"c#",
"recursion",
"graph",
"api",
"properties"
],
"Title": "Change tracking POCO entities"
}
|
226759
|
<p>I have taken a stab at implementing a HashMap in Java. To deal with collisions I implemented sort of a LinkedList using a dataNode. I am not very confident of my implementation hence looking for some feedback.</p>
<pre><code>import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class MyHashMap<K, V> implements SampleMap<K, V>{
private double loadFactor;
private int size;
private int capacity; // Number of elements in the HashMap
Set<K> hashSetKeys = new HashSet<>();
//
private dataNode[] hashTable;
// Constructor: Default values for instance variables
public MyHashMap() {
this(16, 0.75);
}
// Constructor: starts with an initialSize for the Map
public MyHashMap(int initialSize) {
this(initialSize, 0.75);
}
public MyHashMap(int initialSize, double loadFactor) {
hashTable = new dataNode[initialSize];
this.size = initialSize;
this.loadFactor = loadFactor;
}
// Removes all the mapping from this map
@Override
public void clear() {
if (size != 0) {
hashTable = new dataNode[size];
capacity = 0;
hashSetKeys.clear();
}
}
public int capacity() {
return capacity;
}
// Returns true if this map contains a mapping for the specified key.
@Override
public boolean containsKey(K key) {
return hashSetKeys.contains(key);
}
/*
* Returns the value to which the specified key is mapped, or null if this
* map contains no mapping for the key.
*/
@Override
public V get(K key) {
if (this.containsKey(key)) {
int tableIndex = (key.hashCode() & 0x7fffffff) % (size - 1);
return get(hashTable[tableIndex], key);
}
else {
// the hashtable does not contain the key
return null;
}
}
// Helper function for the get method to get the value of a specified key
private V get(dataNode node, K key) {
if (node == null) {
return null;
}
else {
if (node.getKey().equals(key)) {
return (V) node.getValue();
}
else {
return get(node.getNextNode(), key);
}
}
}
// Returns the number of key-value mappings in this map
@Override
public int size() {
return this.size;
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key,
* the old value is replaced.
*/
@Override
public void put(K key, V value) {
if (((double) capacity / size) >= loadFactor) {
copyAndIncreaseSize(size);
this.put(key, value);
}
else {
int tableIndex = (key.hashCode() & 0x7fffffff) % (size - 1);
if (!hashSetKeys.contains(key)) {
capacity += 1;
}
hashSetKeys.add(key);
if (hashTable[tableIndex] == null) {
hashTable[tableIndex] =
new dataNode<K, V>(key, value, key.hashCode());
}
else {
dataNode<K, V> tempNode = hashTable[tableIndex];
for (dataNode<K, V> node : tempNode) {
if (node.getKey().equals(key)) {
node.setValueData(value);
return;
}
}
hashTable[tableIndex] = new dataNode<K, V>(key, value,
key.hashCode(), hashTable[tableIndex]);
}
}
}
// Helper function to increase the size of the table
private void copyAndIncreaseSize(int currentSize) {
dataNode[] tempTable = hashTable; // temp table
hashTable = new dataNode[currentSize * 2]; // new hashTable
this.size = currentSize * 2; // Updating the size
// since the hashmap only allows unique keys hence iterating through
// the keyset
for (K key : this.keySet()) {
int currentIndex =
(key.hashCode() & 0x7fffffff) % (currentSize - 1);
dataNode<K, V> tempNode = tempTable[currentIndex];
// if there is no next node, it is only one node
if (tempNode != null) {
if (tempNode.getNextNode() == null) {
this.put(key, tempNode.getValue());
} else {
for (dataNode node : tempNode) {
if (node.getKey().equals(key)) {
this.put(key, tempNode.getValue());
}
}
}
}
}
}
/** Returns a Set view of the keys contained in this map. */
@Override
public Set<K> keySet() {
return hashSetKeys;
}
/**
* Removes the mapping for the specified key from this map if present.
*/
@Override
public V remove(K key) {
throw new UnsupportedOperationException();
}
/**
* Removes the entry for the specified key only if it is currently mapped to
* the specified value.
*/
@Override
public V remove(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<K> iterator() {
return new HashMapIterator(hashSetKeys);
}
private class HashMapIterator implements Iterator<K> {
K[] keyArray;
int keySetSize;
int counter = 0;
HashMapIterator(Set hashKeySet) {
keyArray = (K[]) hashKeySet.toArray();
keySetSize = hashKeySet.size();
}
@Override
public boolean hasNext() {
return keySetSize > 0;
}
@Override
public K next() {
counter += 1;
size -= 1;
return keyArray[counter];
}
}
}
</code></pre>
<p>dataNode.java</p>
<pre><code>import java.util.Iterator;
public class dataNode<K, V> implements Iterable<dataNode>{
private int hash;
private dataNode next;
private K keyData;
private V valueData;
// Constructor for nodes which will store the data
dataNode(K key, V value, int hash) {
this.keyData = key;
this.valueData = value;
this.hash = hash;
this.next = null;
}
dataNode(K key, V value, int hash, dataNode next) {
this.keyData = key;
this.valueData = value;
this.hash = hash;
this.next = next;
}
// Function to assign the next node
public void nextNode(dataNode next) {
this.next = next;
}
dataNode getNextNode() {
return this.next;
}
K getKey() {
return this.keyData;
}
V getValue() {
return this.valueData;
}
void setValueData(V valueData) {
this.valueData = valueData;
}
@Override
public Iterator<dataNode> iterator() {
return new dataNodeIterator(this);
}
private static class dataNodeIterator implements Iterator<dataNode> {
private dataNode current;
dataNodeIterator(dataNode node) {
current = node;
}
public boolean hasNext() {
return current.getNextNode() != null;
}
public dataNode next() {
dataNode nextNode = current.getNextNode();
current = nextNode;
return nextNode;
}
}
}
</code></pre>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T00:50:05.197",
"Id": "440951",
"Score": "2",
"body": "What is `SampleMap`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T12:51:54.523",
"Id": "440979",
"Score": "0",
"body": "It is an interface that I created that defines the abstract data type. Would you like me to post the code of that too?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T23:41:15.933",
"Id": "226762",
"Score": "1",
"Tags": [
"java",
"hash-map"
],
"Title": "Custom HashMap implementation in Java with Linear Probing"
}
|
226762
|
<p>I have been trying to solve <a href="https://www.hackerrank.com/challenges/contacts/problem" rel="nofollow noreferrer">this</a> HackerRank problem:</p>
<blockquote>
<p>We're going to make our own Contacts application! The application must perform two types of operations:</p>
<ul>
<li><p>add name, where is a string denoting a contact name. This must store as a new contact in the application.</p>
</li>
<li><p>find partial, where is a string denoting a partial name to search the application for. It must count the number of contacts starting with and print the count on a new line.</p>
</li>
</ul>
<p>Given sequential add and find operations, perform each operation in order.</p>
</blockquote>
<p>What I came up is this</p>
<pre><code>class TrieNode():
def __init__(self):
self.children = {}
self.word_count = 0
class Trie():
def __init__(self):
self.root = self.get_node()
def get_node(self):
return TrieNode()
def add(self, key):
crawl = self.root
for char in key:
if char not in crawl.children:
crawl.children[char] = self.get_node()
crawl = crawl.children[char]
crawl.word_count += 1
def get_prefix(self, key):
crawl = self.root
for char in key:
if char not in crawl.children:
return None
crawl = crawl.children[char]
return crawl
def find(self, key):
node = self.get_prefix(key)
return node.word_count if node else 0
</code></pre>
<p>The code above is a modification of <a href="https://www.geeksforgeeks.org/trie-insert-and-search/" rel="nofollow noreferrer">this</a> from GeeksForGeeks. The modifications that I have done are keeping a <code>word_count</code> for every trie node. This denotes how many words start with the prefix ending in that node's letter. The other modification is using a <code>hashmap</code> to keep children rather than <code>list</code>s.</p>
<p>On HackerRank, 9/11 test cases pass, and the other 2 timeout. I can't figure out where I can optimize this further.</p>
<p>I know of a radix tree that is an optimized version of a normal trie, but that saves on space, rather than time, so I haven't explored that option.</p>
<p>Can anyone help me figure out where I can optimize for time in my code?</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T08:59:41.717",
"Id": "440969",
"Score": "0",
"body": "You should always include the programming language tag to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T09:07:50.387",
"Id": "440970",
"Score": "1",
"body": "@dfhwze - Sorry, thanks for including that tag!"
}
] |
[
{
"body": "<p>I think the important thing to notice here is that you don't actually need a Trie. The <code>partial</code> queries are not just substrings of the names, they are prefixes. It should therefore be faster to just built a dictionary which directly counts how often each prefix occurs.</p>\n\n<p>Something as simple as this is sufficient (just tested it, it passes all testcases):</p>\n\n<pre><code>from collections import defaultdict\n\ndef contacts(queries):\n prefixes = defaultdict(int)\n for op, name in queries:\n if op == \"add\":\n # maybe not the best/nicest way to iterate over slices,\n # but probably the easiest\n for i in range(1, len(name) + 1):\n prefixes[name[:i]] += 1\n else:\n # gives 0 if name is not in prefixes, no need for `get`\n yield prefixes[name] \n</code></pre>\n\n<p>This is <span class=\"math-container\">\\$\\mathcal{O}(len(name))\\$</span> for each <code>add</code> and <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> for each <code>find</code>. And since the length of all names is less than 22, the <code>for</code> loop will be very fast. It does not even seem to matter that slicing the string might create additional copies.</p>\n\n<p>In contrast, your code is also <span class=\"math-container\">\\$\\mathcal{O}(len(name))\\$</span> for each <code>add</code>, but it is also <span class=\"math-container\">\\$\\mathcal{O}(len(name))\\$</span> for each <code>find</code>, as far as I can tell. You need to actually traverse the Trie to find the count. Apparently that, maybe together with the overhead of looking up class methods, is enough to reach the time limit for one of the larger testcases.</p>\n\n<p>Stylistically your code looks very good. The only thing to improve there is adding some <code>docstrings</code> to your methods which explain how to use them.</p>\n\n<p>If you were worried about Python 2 backward compatibility you should inherit from <code>object</code>, but nowadays that is probably less of a concern (especially with one-off code for a coding challenge).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:54:18.103",
"Id": "441594",
"Score": "1",
"body": "Why `defaultdict(int)` instead of `Counter`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:19:15.097",
"Id": "442184",
"Score": "1",
"body": "Thank you! I understand now. I have one follow up question though. Aren't tries' biggest use case finding prefixes? I'm asking because you said `not just substrings of the names, they are prefixes`, which makes me believe a `hashmap` is a better implementation for prefix finding rather than a `trie`. Or is it only true in this case because of max limit on the length of the input strings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:38:17.347",
"Id": "442185",
"Score": "1",
"body": "@SidharthSamant I think you might be right. In that case it is probably because the input size is fixed. With your trie you iterate through the nodes to get to the final node, and this iteration happens in Python. With the dictionary you lookup a value in a hashmap, which happens in C. And since only the counts are needed, there is no extra memory needed (if each value contained all words seen so far with that prefix, it would take a lot more space than a trie)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:41:14.743",
"Id": "442186",
"Score": "0",
"body": "@PeterTaylor Because I did not need any of the other features of `Counter` and therefore did not think of it. However, now that you mention it `counter.update(name[:i+1] for i in range(len(name)))` could be slightly more elegant than my `for` loop."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T08:25:45.653",
"Id": "226904",
"ParentId": "226768",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226904",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T08:58:01.380",
"Id": "226768",
"Score": "5",
"Tags": [
"python",
"performance",
"algorithm",
"time-limit-exceeded",
"trie"
],
"Title": "Count words with given prefix using Trie"
}
|
226768
|
<p>I have made a project at Github that uses computer vision to solve Sudokus. Since this is my first project I would really like to get some feedback on my code. Since it is not allowed to link my repository I took one class that I have created.</p>
<p>I am mostly looking for feedback on how I write my code, not necessarily on algorithms. Is there anything I can do to improve the readability, or to make it look nicer or more pythonic?</p>
<pre class="lang-py prettyprint-override"><code>class PreprocessNumber:
"""
A class used to process images from a Sudoku board.
Each box in the Sudoku board should be given an instance of this class. The class contains methods to
determine if one box contains a number or not. If the box contains a number this class provices methods to
extract and center the number in a new image with the dimension specified by the user.
Attributes
----------
NOT_BLACK_THRESHOLD : int (20)
a threshold used to classify if a pixel is considered non-black.
image : numpy array
the input image represented by a numpy array
extracted_feature : numpy array
a numpy array representing the extracted feature from the image
dimension : tuple
a tuple describing the dimension input image
__dct_groups : dictionary
a dictionary used to keep track of all groups of feature in the image as well as the group that each pixel
contains to.
Methods
-------
def crop_feature(self):
Crops the most centered feature in the image.
def is_number(self):
Validates if the instance of this class contains a number by using two conditions.
def get_centered_number(self, dimension):
Returns centered number.
def __create_groups_of_features(self):
Creates groups of features.
def __check_left_and_above_pixel_for_group(self, pixel_coord):
Returns the group value of adjacent pixels.
def __get_group_number_of_centered_feature(self):
Finds and returns the group number of the most centered feature.
def __extract_feature(self, feature_group_number):
Extracts all pixels corresponding to the given group number to self.extracted_feature.
def __validate_first_condition(self, temp=0):
Validates the first condition to determine if the instance of this class contains a number.
def __validate_second_condition(self):
Validates the second condition to determine if the instance of this class contains a number.
"""
def __init__(self, image):
"""
Parameters
----------
image : numpy array
the input image represented by a numpy array
"""
self.NOT_BLACK_THRESHOLD = 20
self.image = image
self.extracted_feature = np.zeros_like(self.image)
self.dimension = self.image.shape
self.__dct_groups = {}
def crop_feature(self):
"""Crops the most centered feature in the image.
This method takes the most centered cohesive group of non-black pixels and crop them to self.extracted_feature.
"""
self.__create_groups_of_features()
self.__extract_feature(self.__get_group_number_of_centered_feature())
def is_number(self):
"""Validates if the instance of this class contains a number by using two conditions.
Returns
-------
boolean
a boolean representing if self.extracted_feature contains a number or not. True if a number is present,
False otherwise.
"""
return self.__validate_first_condition() and self.__validate_second_condition()
def get_centered_number(self, dimension):
"""Returns centered number.
This method centers the number currently located in self.extracted_feature and then returns the centered number.
Parameters
----------
dimension : tuple
A tuple describing the dimension of the centered number to return
Returns
-------
numpy array
a numpy array representing the centered number having the dimension as specified by the parameter.
"""
# Initialize variables to find boundaries
left_bound = self.extracted_feature.shape[0]
right_bound = 0
upper_bound = self.extracted_feature.shape[1]
lower_bound = 0
# Find top left and bottom right corners of the number
for row in range(self.extracted_feature.shape[0]):
for col in range(self.extracted_feature.shape[1]):
if self.extracted_feature[row][col] > self.NOT_BLACK_THRESHOLD:
if row < upper_bound:
upper_bound = row
elif row > lower_bound:
lower_bound = row
if col < left_bound:
left_bound = col
elif col > right_bound:
right_bound = col
width = right_bound - left_bound + 1
height = lower_bound - upper_bound + 1
extracted_number = np.zeros((height, width))
# Extract the number
for row in range(height):
for col in range(width):
extracted_number[row][col] = self.extracted_feature[upper_bound + row][left_bound + col]
# Place the extracted number in a square
if height != width:
square_number = np.zeros((max((height, width)), max(height, width)))
if height > width:
# Add black columns to the left and right
diff = int((height-width)/2)
square_number[:, diff:diff + width] = extracted_number
else:
# Add black rows above and under
diff = int((width-height)/2)
square_number[diff:diff + height, :] = square_number
else:
square_number = extracted_number
centered_number = np.zeros(dimension)
# Assert that there is at least four black pixels closest to all edges.
if np.any(np.array(square_number.shape) > 20):
centered_number[4:24, 4:24] = resize(square_number, (20, 20), anti_aliasing=True)
else:
size = square_number.shape
diff_height = int((dimension[0] - size[0])/2)
diff_width = int((dimension[0] - size[1])/2)
centered_number[diff_height:size[0] + diff_height, diff_width:size[1] + diff_width] = square_number
return centered_number
def __create_groups_of_features(self):
"""Creates groups of features.
All different cohesive groups of non-black pixels will be treated as one feature. This method goes through all
pixels and labels all cohesive groups of non-black pixels. Each pixel will be a key corresponding to its group
in a dictionary. Black pixels will have its group number set to -1, indicating not a feature.
"""
new_group = 0
for row in range(self.dimension[0]):
for col in range(self.dimension[1]):
if self.image[row][col] > self.NOT_BLACK_THRESHOLD:
# Checks if the current pixel at (row, col) is adjacent to already assigned non-black pixels.
surrounding_group = self.__check_left_and_above_pixel_for_group(pixel_coord=[row, col])
if surrounding_group != -1:
self.__dct_groups[str(row) + ":" + str(col)] = surrounding_group
else:
self.__dct_groups[str(row) + ":" + str(col)] = new_group
new_group += 1
else:
self.__dct_groups[str(row) + ":" + str(col)] = -1
def __check_left_and_above_pixel_for_group(self, pixel_coord):
"""Returns the group value of adjacent pixels.
Given a coordinate of a pixel, this method checks if the adjacent pixels to the left and above have already
been assigned a group. If they have, this method returns the group number. If the pixel to the left and above
have been assigned different groups, all pixels associated with the group of the pixel above will be assigned
the group of the pixel to the left.
"""
group_pixel_left = -1
if pixel_coord[1] > 0:
# If there is an adjacent pixel to the left
group_pixel_left = self.__dct_groups[str(pixel_coord[0]) + ":" + str(pixel_coord[1]-1)]
if pixel_coord[0] > 0:
# If there is an adjacent pixel above
group_pixel_above = self.__dct_groups[str(pixel_coord[0] - 1) + ":" + str(pixel_coord[1])]
if group_pixel_left == -1:
return group_pixel_above
elif group_pixel_above == -1:
return group_pixel_left
else:
# No adjacent pixel above, return the group of the pixel to the left
return group_pixel_left
if group_pixel_left != group_pixel_above:
# Replacing pixels belonging to the group of the pixel above to the group of the pixel to the left
for item in self.__dct_groups:
if self.__dct_groups[item] == group_pixel_above:
self.__dct_groups[item] = group_pixel_left
return group_pixel_left
def __get_group_number_of_centered_feature(self):
"""Finds and returns the group number of the most centered feature.
This method uses an algorithm that starts to search from the middle and then expands its search in all
directions. When a non-black pixel is found, the corresponding group is returned.
"""
center_row = int(self.dimension[0] / 2)
center_col = int(self.dimension[1] / 2)
nr_search_loops = min(self.dimension[0] - center_row, self.dimension[1] - center_row) - 1
loop_directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
# Starts looking at the centered pixel
if self.image[center_row][center_col] > self.NOT_BLACK_THRESHOLD:
return self.__dct_groups[str(center_row) + ":" + str(center_col)]
else:
for loop_nr in range(1, nr_search_loops):
center_row -= 1
center_col -= 1
search_coord = [center_row, center_col]
for direction in loop_directions:
vertical = direction[0]
horizontal = direction[1]
for i in range(loop_nr * 2):
if self.image[search_coord[0]][search_coord[1]] > self.NOT_BLACK_THRESHOLD:
return self.__dct_groups[str(search_coord[0]) + ":" + str(search_coord[1])]
search_coord[0] += 1 * vertical
search_coord[1] += 1 * horizontal
# If no group was found, all pixels are black.
return -1
def __extract_feature(self, feature_group_number):
"""Extracts all pixels corresponding to the given group number to self.extracted_feature.
Parameters
----------
feature_group_number : int
An integer representing the group number of the feature to extract.
"""
for row in range(self.dimension[0]):
for col in range(self.dimension[1]):
if self.__dct_groups[str(row) + ":" + str(col)] == feature_group_number:
self.extracted_feature[row][col] = self.image[row][col]
def __validate_first_condition(self):
"""Validates the first condition to determine if the instance of this class contains a number.
Assume the image of the potential number is split into a 3x3-grid with 9 squares of equal size. The first
condition is that the middle square should contain at least five non-black pixels.
Returns
-------
boolean
a boolean representing if self.extracted_feature contains a number or not. True if a number is present,
False otherwise.
"""
non_black_dot_counter = 0
# x_box and y_box represents the coordinates of the upper left corner of the middle square
x_box = int(self.extracted_feature.shape[0] / 9) * 4
y_box = int(self.extracted_feature.shape[1] / 9) * 4
for row in range(x_box, x_box + int(self.extracted_feature.shape[0] / 9)*2):
for col in range(y_box, y_box + int(self.extracted_feature.shape[1] / 9) * 2):
if self.extracted_feature[row][col] > self.NOT_BLACK_THRESHOLD:
non_black_dot_counter += 1
if non_black_dot_counter >= 5:
return True
return False
def __validate_second_condition(self):
"""Validates the second condition to determine if the instance of this class contains a number.
The second condition is simply that the extracted feature should have at least 25 non-black pixels to be able
to be classified as a number.
Returns
-------
boolean
a boolean representing if self.extracted_feature contains a number or not. True if a number is present,
False otherwise.
"""
counter = 0
for row in self.extracted_feature:
for pixel in row:
if pixel > self.NOT_BLACK_THRESHOLD:
counter += 1
if counter >= 25:
return True
return False
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T13:09:00.293",
"Id": "440980",
"Score": "3",
"body": "Welcome to Code Review. Thanks for pasting the code here that you would like to be reviewed. That is most important, but you can also add a link to your github repo for those that want to see more context."
}
] |
[
{
"body": "<p>No issues (other than <em>lines too long</em>) found using an <a href=\"http://pep8online.com/\" rel=\"nofollow noreferrer\">online PEP 8 check</a> I can only find slight inconsistencies in white space. Note that <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">PEP 8: white space</a> allows both of these lines, but why introduce this inconsistency? </p>\n\n<blockquote>\n<pre><code>range(x_box, x_box + int(self.extracted_feature.shape[0] / 9)*2):\n\nrange(y_box, y_box + int(self.extracted_feature.shape[1] / 9) * 2):\n</code></pre>\n</blockquote>\n\n<p>You're also using a lot of magic (hard-coded, undocumented) numbers, to list a few:</p>\n\n<ul>\n<li><code>if counter >= 25:</code></li>\n<li><code>int(self.extracted_feature.shape[1] / 9) * 4</code></li>\n<li><code>centered_number[4:24, 4:24] =</code></li>\n</ul>\n\n<p>For maintainability, you might want to group these as constants, or use configurable options, with default values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T20:10:01.800",
"Id": "226793",
"ParentId": "226770",
"Score": "2"
}
},
{
"body": "<h2><code>__members</code></h2>\n\n<p>Adding a double underscore prefix (with at most one trailing underscore) to class/instance members has special meaning. It causes the interpreter to use <a href=\"https://docs.python.org/3/tutorial/classes.html#private-variables\" rel=\"nofollow noreferrer\">name-mangling</a> to avoid name clashes in subclasses.</p>\n\n<p>If <code>PreprocessNumber</code> is not subclassed, there is no need to invoke name mangling.</p>\n\n<p>→ Simply use a single leading underscore for private/protected members, not a double underscore.</p>\n\n<h2>Docstrings</h2>\n\n<p>Listing all the methods of a class in the docstring of the class is redundant. Executing <code>help(PreprocessNumber)</code> will generate help text from the class’s docstring <strong>and</strong> the docstrings of all public members in the class. If the class docstring includes information on the public members, it then appears twice in the output!</p>\n\n<p>Providing docstrings for non-public members of a class is usually not useful, as that documentation will not normally be emitted by the help system.</p>\n\n<p>Providing docstrings for name-mangled members is <em>hilarious</em>, as the members are not accessible unless one also knows the mangled name.</p>\n\n<p>→ Provide docstrings for public classes and methods only; comments are generally sufficient for private/protected members.</p>\n\n<h2>Class Constants</h2>\n\n<p>Instead of creating an extra member on each and every instance of a class, create constants directly on the class:</p>\n\n<pre><code>class PreprocessNumber:\n \"\"\"...\"\"\"\n\n NOT_BLACK_THRESHOLD = 20\n\n def __init__(self, image):\n ...\n</code></pre>\n\n<p>The class attribute can still be accessed using <code>self.NOT_BLACK_THRESHOLD</code> in member functions.</p>\n\n<p>Note: Assigning to <code>self.NOT_BLACK_THRESHOLD</code> will create a instance member with the new value; it will not change the class’s attribute value. Assigning to <code>PreprocessNumber.NOT_BLACK_THRESHOLD</code> will change the class attribute “constant” seen by all instances.</p>\n\n<h2>Integer Division</h2>\n\n<p>Python has an integer division operator (<code>//</code>), so instead of this:</p>\n\n<pre><code>center_row = int(self.dimension[0] / 2)\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>center_row = self.dimension[0] // 2\n</code></pre>\n\n<p>avoiding the conversions to floating point and then back to an integer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T03:49:41.110",
"Id": "226886",
"ParentId": "226770",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T09:39:13.597",
"Id": "226770",
"Score": "4",
"Tags": [
"python",
"sudoku"
],
"Title": "Solving Sudoku using computer vision, feedback on class"
}
|
226770
|
<p>The goal is to make a word generator. The program takes a word list (typically, it may be the full dictionary of a language, or a list of names), analyses it, and then invents word that sound alike the one in the list.<br>
There is multiple parts of the program, which is embedded in a Qt GUI. I used Qt Creator 4.9.2 (based on Qt 5.12.4, GCC 5.3.1, 64 bits).</p>
<p>It is all mostly in french (variable names and UI texts), sorry about that. I commented in English, I hope it's enough. </p>
<p>About how the program works :<br>
Analyzing the word means noting an occurrence for each succession of character present in this word. If a succession of characters appear in multiple words, multiple occurrences are noted and hence it is more probable to generate this succession.<br>
In the fonction.h, analysis is made by 'analyseWord' (but it only handles ASCII characters), or by another version 'QanalyseWord' using Qchar instead of char (hence any utf-8 character).<br>
Depending on the type of analysis made, word generation is made by 'generateur' or 'Qgenerateur'</p>
<p>For the program itself, the main.cpp is only what's needed to launch the mainwindow ("FenetrePrincipale")</p>
<pre class="lang-cpp prettyprint-override"><code>#include <QtWidgets>
#include "fenetreprincipale.h"
#include "fonctions.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
srand( static_cast<unsigned int>(time(NULL)));
/*Traduction of Qt texts to Fr*/
QString locale = QLocale::system().name().section('_', 0, 0);
QTranslator translator;
translator.load(QString("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&translator);
/*end*/
FenetrePrincipale fenetre;
fenetre.show();
return app.exec();
}
</code></pre>
<p>FenetrePrincipale handles all the interaction of the program. It has two tabs (one for analysis, one for generating words).
Its .ui file is :</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FenetrePrincipale</class>
<widget class="QMainWindow" name="FenetrePrincipale">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>702</width>
<height>539</height>
</rect>
</property>
<property name="font">
<font>
<pointsize>10</pointsize>
</font>
</property>
<property name="windowTitle">
<string>GeMots</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="1">
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="onglet_analyse">
<attribute name="title">
<string>Analyse d'une liste de mots</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_4">
<item row="6" column="0">
<widget class="QProgressBar" name="progr_Analyse">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>15</height>
</size>
</property>
<property name="value">
<number>0</number>
</property>
</widget>
</item>
<item row="3" column="0">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="4" column="0">
<widget class="QPushButton" name="bouton_analyser">
<property name="font">
<font>
<pointsize>12</pointsize>
</font>
</property>
<property name="text">
<string>Lancer l'analyse</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QFrame" name="frame_mode">
<property name="frameShape">
<enum>QFrame::Panel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="3" column="1" colspan="2">
<widget class="QRadioButton" name="radio_speciaux">
<property name="toolTip">
<string>C'est beau l'utf-8, mais c'est chiant à utiliser !</string>
</property>
<property name="text">
<string>Gère tout les caractères spéciaux</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="4" rowspan="4">
<widget class="Line" name="line_details">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="label_lcoh">
<property name="text">
<string>Longueur de cohérence :</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QSpinBox" name="spin_lcoh">
<property name="accelerated">
<bool>true</bool>
</property>
<property name="suffix">
<string> lettres</string>
</property>
<property name="minimum">
<number>2</number>
</property>
<property name="value">
<number>3</number>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QLabel" name="Qualite">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Qualité</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="3" column="5">
<widget class="QLabel" name="Bof">
<property name="toolTip">
<string>Pour ce que le programme fait (lire des suites de lettres. Noter le nombre d'occurence),
cette méthode est honteusement longue</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(223, 177, 19);</string>
</property>
<property name="text">
<string>Bof</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="5">
<widget class="QLabel" name="Parfait_2">
<property name="toolTip">
<string>C'est presque instantanné. Normal, y a vraiment pas besoin d'un supercalculateur pour faire ça</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(44, 161, 40);</string>
</property>
<property name="text">
<string>Parfait</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="2" column="3">
<widget class="QLabel" name="Bof_2">
<property name="toolTip">
<string>On génère pas des mots accentués. Et en plus, ça gère pas les tirets</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(223, 177, 19);</string>
</property>
<property name="text">
<string>Bof</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QLabel" name="Minable">
<property name="toolTip">
<string>J'voulais pas faire un truc pour les anglais, moi !</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(255, 0, 0);</string>
</property>
<property name="text">
<string>Minable</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="0" column="5">
<widget class="QLabel" name="Rapidite">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>Rapidité</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="3" column="3">
<widget class="QLabel" name="Parfait">
<property name="toolTip">
<string>Testez avec le Japonnais ! Promis, ça marche !</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(44, 161, 40);</string>
</property>
<property name="text">
<string>Parfait</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="2" column="5">
<widget class="QLabel" name="Minable_2">
<property name="toolTip">
<string>En même temps, c'est codé avec les pieds</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(255, 0, 0);</string>
</property>
<property name="text">
<string>Minable</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item row="1" column="1" colspan="2">
<widget class="QRadioButton" name="radio_ignore">
<property name="toolTip">
<string>Les lettres accentuées sont supprimée par l'analyse : on regarde le mot &quot;ttt&quot; au lieu de &quot;étêtât&quot;
Il vaut donc mieux que la liste de mots originale soit sans accents</string>
</property>
<property name="text">
<string>Ignore les accents</string>
</property>
</widget>
</item>
<item row="2" column="1" colspan="2">
<widget class="QRadioButton" name="radio_minable">
<property name="toolTip">
<string>Ces caractères spéciaux sont remplacé par leur valeur non-accentué :
ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûüÿÑñÇç
Mais ce traitement est long et nul ! Oui, mais je me suis fait chier à le coder, je vais pas le supprimer...</string>
</property>
<property name="text">
<string>Gère très mal les accents</string>
</property>
</widget>
</item>
<item row="4" column="5">
<widget class="QPushButton" name="bouton_details">
<property name="font">
<font>
<pointsize>8</pointsize>
</font>
</property>
<property name="text">
<string>(+ détails)</string>
</property>
<property name="flat">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label_mode">
<property name="text">
<string>Mode de traitement :</string>
</property>
</widget>
</item>
<item row="4" column="2" colspan="3">
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
<item row="5" column="0">
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="9" column="0">
<spacer name="verticalSpacer_5">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="0" column="0">
<widget class="QFrame" name="frame_choixListe">
<property name="frameShape">
<enum>QFrame::Panel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<layout class="QGridLayout" name="gridLayout_3">
<item row="1" column="0" colspan="2">
<widget class="QRadioButton" name="radio_langDef">
<property name="text">
<string>Utiliser la langue par défaut (////Nom liste défaut////)</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QRadioButton" name="radio_langPerso">
<property name="text">
<string>Choisir une liste de mot</string>
</property>
</widget>
</item>
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="label_choixLang">
<property name="text">
<string>Choix de la liste de mots à analyser :</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="bouton_selecFichier">
<property name="text">
<string>(Aucun)</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="onglet_generation">
<property name="enabled">
<bool>false</bool>
</property>
<attribute name="title">
<string>Génération de mots</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_5">
<item row="4" column="1">
<spacer name="verticalSpacer_6">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_tailleMots">
<property name="text">
<string>Taille max des mots</string>
</property>
</widget>
</item>
<item row="9" column="2">
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item row="10" column="2">
<widget class="QPushButton" name="bouton_trier">
<property name="text">
<string>Trier par taille</string>
</property>
</widget>
</item>
<item row="11" column="2">
<widget class="QPushButton" name="bouton_nettoyer">
<property name="text">
<string>Nettoyer</string>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QCheckBox" name="check_forcerTaille">
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
<property name="text">
<string>Forcer la taille des mots</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QSpinBox" name="spin_tailleMax">
<property name="suffix">
<string> lettres</string>
</property>
<property name="minimum">
<number>2</number>
</property>
<property name="singleStep">
<number>2</number>
</property>
<property name="value">
<number>20</number>
</property>
</widget>
</item>
<item row="0" column="3" rowspan="13">
<widget class="QTextEdit" name="text_mots"/>
</item>
<item row="1" column="1">
<widget class="QSpinBox" name="spin_nbMots">
<property name="minimum">
<number>1</number>
</property>
<property name="value">
<number>1</number>
</property>
</widget>
</item>
<item row="6" column="0" colspan="2">
<widget class="QCheckBox" name="check_troll">
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
<property name="text">
<string>Génération de mots parfaits</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_nbMots">
<property name="text">
<string>Nombre de mots</string>
</property>
</widget>
</item>
<item row="10" column="0" rowspan="2" colspan="2">
<widget class="QFrame" name="fram_resume">
<property name="frameShape">
<enum>QFrame::Box</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label_resume_analyse">
<property name="text">
<string>Type d'analyse : //type//</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_resume_lcoh">
<property name="text">
<string>Longueur de cohérence : //lcoh//</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="3" column="0" colspan="3">
<widget class="QPushButton" name="bouton_generer">
<property name="font">
<font>
<pointsize>12</pointsize>
</font>
</property>
<property name="text">
<string>Inventer des mots</string>
</property>
</widget>
</item>
<item row="8" column="1">
<spacer name="verticalSpacer_7">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="7" column="1">
<spacer name="verticalSpacer_8">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="9" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Analyse utilisée :</string>
</property>
<property name="alignment">
<set>Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft</set>
</property>
</widget>
</item>
<item row="9" column="1">
<spacer name="verticalSpacer_4">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>702</width>
<height>23</height>
</rect>
</property>
<widget class="QMenu" name="menuMenu">
<property name="title">
<string>Menu</string>
</property>
<widget class="QMenu" name="menuQuitter">
<property name="title">
<string>Quitter</string>
</property>
<widget class="QMenu" name="menuQuitter_2">
<property name="title">
<string>Quitter</string>
</property>
<addaction name="actionNe_pas_quitter"/>
<addaction name="actionNe_pas_quitter_2"/>
<addaction name="actionNe_pas_quitter_3"/>
<addaction name="actionQuitter_3"/>
<addaction name="actionNe_pas_quitter_4"/>
</widget>
<addaction name="menuQuitter_2"/>
</widget>
<addaction name="separator"/>
<addaction name="actionUtiliser_les_valeur_actuelles_par_defaut"/>
<addaction name="separator"/>
<addaction name="menuQuitter"/>
</widget>
<widget class="QMenu" name="menuA_propos">
<property name="title">
<string>A propos</string>
</property>
<addaction name="actionAide"/>
<addaction name="action_propos_de_ce_programme"/>
</widget>
<addaction name="menuMenu"/>
<addaction name="menuA_propos"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="actionQuitter_3">
<property name="text">
<string>Ha oui, quitter</string>
</property>
</action>
<action name="actionNe_pas_quitter">
<property name="text">
<string>Ne pas quitter</string>
</property>
</action>
<action name="actionNe_pas_quitter_2">
<property name="text">
<string>Ne pas quitter</string>
</property>
</action>
<action name="actionNe_pas_quitter_3">
<property name="text">
<string>Ne pas quitter</string>
</property>
</action>
<action name="actionNe_pas_quitter_4">
<property name="text">
<string>Ne pas quitter</string>
</property>
</action>
<action name="actionUtiliser_les_valeur_actuelles_par_defaut">
<property name="text">
<string>Changer les valeurs par défaut</string>
</property>
</action>
<action name="actionCharger_automatiquement_la_liste_de_mot_par_d_faut">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Charger la liste par défaut au lancement</string>
</property>
</action>
<action name="actionAnalyser_la_liste_par_d_faut_au_lancement">
<property name="checkable">
<bool>true</bool>
</property>
<property name="text">
<string>Analyser la liste par défaut au lancement</string>
</property>
</action>
<action name="actionAide">
<property name="text">
<string>Aide</string>
</property>
</action>
<action name="action_propos_de_ce_programme">
<property name="text">
<string>À propos de ce programme</string>
</property>
</action>
</widget>
<resources/>
<connections>
<connection>
<sender>radio_speciaux</sender>
<signal>toggled(bool)</signal>
<receiver>spin_lcoh</receiver>
<slot>setEnabled(bool)</slot>
<hints>
<hint type="sourcelabel">
<x>318</x>
<y>320</y>
</hint>
<hint type="destinationlabel">
<x>255</x>
<y>351</y>
</hint>
</hints>
</connection>
</connections>
</ui>
</code></pre>
<p>then, the .h file :</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef FENETREPRINCIPALE_H
#define FENETREPRINCIPALE_H
#include <QMainWindow>
#include <QProgressBar>
#include "fonctions.h"
#include "fenaide.h"
#include "infos.h"
namespace Ui {
class FenetrePrincipale; //=Main Window
}
class FenetrePrincipale : public QMainWindow
{
Q_OBJECT
public:
explicit FenetrePrincipale(QWidget *parent = 0);
~FenetrePrincipale();
enum type_Trait {aucun, ascii, asciiplus, utf_8};
type_Trait selectedTrait();
type_Trait stringToType(QString stringType);
public slots:
//Analyses a wordlist
void on_bouton_analyser_clicked();
//Generates a word based on previously analysed wordlist
void on_bouton_generer_clicked();
//Choose path to the wordlist
void on_bouton_selecFichier_clicked();
//Adds detail on the 3 possible analyses
void on_bouton_details_clicked();
//Removes all generated words
void on_bouton_nettoyer_clicked();
//Sort generated words by lenght
void on_bouton_trier_clicked();
//Menu icon 'Aide'
void on_actionAide_triggered();
//Menu icon 'About'
void on_action_propos_de_ce_programme_triggered();
//Change the default values of the Analyse tab to the current values.
void on_actionUtiliser_les_valeur_actuelles_par_defaut_triggered();
// Just a test function : unckecks the box 0.4 second after it has been clicked
void on_check_troll_clicked();
void unchecking();
//Message when quitting through menu
void quit_troll();
private slots:
//Indicates if the current parameters of the 'Analyse tab' have been modified since previous analisys
void check_analyse_changed();
//Checks if the current coherence lengh have been modified since previous analisys
void on_spin_lcoh_valueChanged(int value);
//Checks if the current analysis method have been modified since previous analisys
void traitement_modifie();
//Checks if the current wordlist have been modified since previous analisys
void liste_modifie();
private:
Ui::FenetrePrincipale *ui;
// QString nomListeMotsDefaut;
QString nomListeMotsDefaut="WordLists/Mots_FR_full.txt";
double probatab[27][27][27] = {{{0}}}; //result of the analysis of the wordlist (for 'ascii' and 'ascii+')
std::map<std::vector<QChar>, std::pair<int,double>> charmap; //result of the analysis (for 'utf-8')
//Parameter of the previous analysis:
QString nomListeMots; //name of the wordlist
type_Trait analyse = aucun; //indicates what analysis has previously been done. Acun = nothing
uint lcoh; //coherence lengh of previous analyse
//Indicates if a change has been made on the 'Analysis' tab
bool listeMots_changed=false;
bool traitement_changed=false;
bool lcoh_changed=false;
QString nomListeAnalysePrecedente;
FenAide *m_FenAide;
Infos *m_Infos;
};
#endif // FENETREPRINCIPALE_H
</code></pre>
<p>and the .cpp file </p>
<pre class="lang-cpp prettyprint-override"><code>#include <QFileDialog>
#include <QProgressBar>
#include <QTimer>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QMessageBox>
#include <QShortcut>
#include <thread>
#include "fenetreprincipale.h"
#include "ui_fenetreprincipale.h"
FenetrePrincipale::FenetrePrincipale(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::FenetrePrincipale)
{
ui->setupUi(this);
//Indication des tooltip longs
QString ListeMotsInstruction("La liste de mot doit être au format .txt, avec 1 seul mot par ligne\n"
"Si plusieurs mots par lignes, seul le premier est pris en compte");
ui->radio_langPerso->setToolTip(ListeMotsInstruction);
ui->bouton_selecFichier->setToolTip(ui->radio_langPerso->toolTip());
//Adaptation de la progressbar
ui->progr_Analyse->setAlignment(Qt::AlignCenter);
//Éléments de la statusbar
ui->statusbar->setFixedHeight(20);
ui->statusbar->showMessage("En attente de lancement...");
//Lecture du fichier des valeurs par défaut:
QFile file("WordLists/Parametres.xml");
if(file.open(QIODevice::ReadOnly)) {
QXmlStreamReader xmlReader(&file);
if(xmlReader.readNextStartElement()) {
if (xmlReader.name() == "valeursDef") {
while(xmlReader.readNextStartElement()) {
if (xmlReader.name() == "nomListe")
nomListeMotsDefaut = xmlReader.readElementText();
else if (xmlReader.name() == "modeTraitement") {
type_Trait wantedAnalyse = stringToType(xmlReader.readElementText());
if(wantedAnalyse==ascii)
ui->radio_ignore->setChecked(true);
else if(wantedAnalyse==asciiplus)
ui->radio_minable->setChecked(true);
else if(wantedAnalyse==utf_8)
ui->radio_speciaux->setChecked(true);
}
else if (xmlReader.name() == "lcoh")
ui->spin_lcoh->setValue(xmlReader.readElementText().toInt());
else if (xmlReader.name() == "nbMots")
ui->spin_nbMots->setValue(xmlReader.readElementText().toInt());
else if (xmlReader.name() == "tailleMax")
ui->spin_tailleMax->setValue(xmlReader.readElementText().toInt());
else
xmlReader.skipCurrentElement();
}
}
xmlReader.skipCurrentElement();
}
}
else{
ui->statusbar->showMessage("Problème lors de la lecture des valeurs par défaut");
}
//Indication de la liste par défaut
QFileInfo fi(nomListeMotsDefaut);
QString textLangDef = "Utiliser la langue par défaut ("+fi.fileName()+")";
ui->radio_langDef->setText(textLangDef);
//Efface tous les éléments affiché par le bouton "détail"
ui->Bof->setVisible(false);
ui->Bof_2->setVisible(false);
ui->Minable->setVisible(false);
ui->Minable_2->setVisible(false);
ui->Parfait->setVisible(false);
ui->Parfait_2->setVisible(false);
ui->Qualite->setVisible(false);
ui->Rapidite->setVisible(false);
ui->line_details->setVisible(false);
//Selectionne l'onglet de départ
ui->tabWidget->setCurrentIndex(0);
//Connexion signal/slot pour detection changement
QObject::connect(ui->radio_ignore, SIGNAL(clicked()), this, SLOT(traitement_modifie()));
QObject::connect(ui->radio_minable, SIGNAL(clicked()), this, SLOT(traitement_modifie()));
QObject::connect(ui->radio_speciaux, SIGNAL(clicked()), this, SLOT(traitement_modifie()));
QObject::connect(ui->radio_langDef, SIGNAL(clicked()), this, SLOT(liste_modifie()));
QObject::connect(ui->radio_langPerso, SIGNAL(clicked()), this, SLOT(liste_modifie()));
QObject::connect(ui->bouton_selecFichier, SIGNAL(clicked()), this, SLOT(liste_modifie()));
//Raccourci clavier
//new QShortcut(QKeySequence(Qt::Key_Return || Qt::Key_Enter), this, SLOT(on_bouton_generer_clicked()));
//Quitter via le menu
QObject::connect(ui->actionQuitter_3, SIGNAL(triggered()), this, SLOT(quit_troll()));
}
FenetrePrincipale::~FenetrePrincipale()
{
delete ui;
}
FenetrePrincipale::type_Trait FenetrePrincipale::selectedTrait() {
if(ui->radio_ignore->isChecked())
return ascii;
else if(ui->radio_minable->isChecked())
return asciiplus;
else if(ui->radio_speciaux->isChecked())
return utf_8;
else
return aucun;
}
FenetrePrincipale::type_Trait FenetrePrincipale::stringToType(QString stringType) {
if (stringType == "ascii")
return FenetrePrincipale::ascii;
else if (stringType == "asciiplus")
return FenetrePrincipale::asciiplus;
else if (stringType == "utf_8")
return FenetrePrincipale::utf_8;
else
return FenetrePrincipale::aucun;
}
void FenetrePrincipale::on_bouton_analyser_clicked() {
ui->centralwidget->setCursor(Qt::WaitCursor);
ui->onglet_analyse->setEnabled(false);
ui->progr_Analyse->setValue(0); //inutile.
ui->statusbar->setToolTip("");
int avRecup(5), avAnal(90), avProbatab(5); //doit sommer a 100. Avancement (%) de chaque étape
charmap.clear();
//Partie 1 : Récupération de la liste de mots
ui->statusbar->showMessage("Récupération de la liste de mots...");
//Choix liste mot (selon valeur radio)
if (ui->radio_langDef->isChecked()) {
nomListeMots = nomListeMotsDefaut;
}
else if (ui->radio_langPerso->isChecked()) {
QFileInfo fi(nomListeMots);
if (fi.fileName() != ui->bouton_selecFichier->text()) {
ui->statusbar->showMessage("Problème sur le nom de la liste de mot. Veuillez reselectionner un liste de mot");
ui->onglet_analyse->setEnabled(true);
ui->centralwidget->unsetCursor();
return;
}
} //vérification qu'on ne va pas refaire l'analyse par défaut
else { //Trololol inutile
ui->progr_Analyse->setValue(42);
ui->statusbar->showMessage("How did you do that ? En plus maintenant, t'as un pointeur de merde :p");
return; //Si aucun bouton coché : arrêter tout
}
//Importation liste mots
std::vector<std::string> mots;
std::vector<float> proba;
std::ifstream Liste_mots(nomListeMots.toStdString(), std::ios::in);
if(Liste_mots) {
extractWords(Liste_mots, mots, proba);
ui->progr_Analyse->setValue(avRecup);
}
else {
ui->statusbar->showMessage("Impossible de lire la liste de mots (voir ici pour plus de détails)");
ui->statusbar->setToolTip("La liste de mot suivante :\n"+nomListeMots+
"\nn'a pas pu être lue. Vérifiez qu'elle existe bien et est une liste de mots au format .txt, 1 mot par ligne");
ui->onglet_analyse->setEnabled(true);
ui->centralwidget->unsetCursor();
return;
}
ui->tabWidget->setTabIcon(0,QIcon()); //L'icone 'warning' nest retirée que si la première étape marche (pas de return dans les étape 2 et 3
//Partie 2 et 3 : Analyse liste mots / construction des proba
ui->statusbar->showMessage("Analyse de la liste de mots...");
int nb=0; //nombre de lettres traitées
//Partie 2 version A :
if(ui->radio_speciaux->isChecked()) { //Traitement moderne
lcoh = ui->spin_lcoh->value();
for(uint i=0; i<mots.size(); i++) {
QString qmot=QString::fromStdString(mots[i]);
QanalyzeWord(qmot,charmap, lcoh, nb);
if (i%500==0) { //Possibilité : 10000 (haché), 100000 (3 étapes)
ui->progr_Analyse->setValue(avRecup+i/(float)mots.size()*avAnal);
QCoreApplication::processEvents(); //permet l'actualisation du gui. Ralenti les calcul...
}
}
//Partie 3 vA : Création des proba de chaque enchaînement de lettre
ui->statusbar->showMessage("Liste de mots analysée. Analyse de l'analyse en cours...");
std::map<std::vector<QChar>, std::pair<int,double>>::iterator it = charmap.begin() , cePrDebut , cePrFin;
//cePrDebut et cePrFin sont des itérateur indiquant le début et la fin de l'enchaînement de lettre examiné actuellement
while(it!=charmap.end()) {
//pr = sous vecteur de it->first de [0] #FFBF00à [lcoh-2] : contient lcoh-1 éléments
//c'est l'enchainement de lettres précédente --> utilisé pour déterminer la proba de l'actuelle
std::vector<QChar> pr(&it->first[0], &it->first[lcoh-1]);
cePrDebut = it;
int nbtlsuiv = 0; //nb tot de lettre suivant l'enchainement 'pr[0]pr[1]...'
//1er parcours : compter occurence de chaque pr
// /!\ à l'odre des condition du while : il ne faut pas appeler it si it=end() --> vérification end en premier
while( (it!=charmap.end()) && (pr==std::vector<QChar>(&it->first[0], &it->first[lcoh-1])) ) {
//tant que l'enchainement des lettres précédentes (défini dans pr) ne change pas, on additionne le nombre d'occurence
nbtlsuiv += it->second.first; //it->second = la pair / .first -> le 'int'=nb d'occurence
it++; //passage au membre suivant
}
cePrFin = it;
//2e parcours : diviser enchainement/occurence total du pr + additionner (pour proba cumul)
//on repasse sur la partie déjà vue : de cePrDebut à cePrFin
for(std::map<std::vector<QChar>, std::pair<int,double>>::iterator repasse = cePrDebut; repasse!=cePrFin && repasse!=charmap.end(); ++repasse) {
repasse->second.second = (double)repasse->second.first / nbtlsuiv;
if (repasse != cePrDebut && repasse!=charmap.begin() )
repasse->second.second += prev(repasse)->second.second; //prev() = élément précédent
}
}
//Traitement terminé. Indication lié au traitement utf_8
analyse = utf_8;
ui->check_forcerTaille->setEnabled(false);
ui->check_forcerTaille->setToolTip("Un bug très (très) idiot empêche de forcer la taille des mots\n"
"avec la méthode gérant tous les type de caractères\n"
"Oui, désolé, j'ai eu la flemme de corriger ça");
ui->label_resume_analyse->setText("Type d'analyse : tous caractères spéciaux");
ui->label_resume_lcoh->setText("Longueur de cohérence : "+QString::number(lcoh));
}
//Patie 2 version B :
else { //Traitement à l'ancienne (radio Ignore et radio gère très mal
int lettertab[27][27][27] = {{{0}}}; //--> lettertab[2][1][3] = nombre d'occurence de "cab" ("3","1","2")
int nb=0; //nombre total de lettres traités
bool clearAccent = ui->radio_minable->isChecked(); //ascii (false) ou asciiplus (true)
for(unsigned int i=0; i<mots.size(); i++) {
nb += analyzeWord(mots[i], lettertab, clearAccent);
if (i%500==0) { //Possibilité : 10000 (haché), 100000 (3 étapes)
ui->progr_Analyse->setValue(avRecup+i/(float)mots.size()*avAnal);
QCoreApplication::processEvents(); //permet l'actualisation du gui. Ralenti les calculs...
}
}
//Partie 3 vB: Création des proba de chaque enchaînement de lettre
ui->statusbar->showMessage("Liste de mots analysée. Analyse de l'analyse en cours...");
for (uint k=0; k<27; k++) {
for (uint j=0;j<27;j++) {
int nbtlsuiv = 0; //nb tot de lettre suivant l'enchainement 'k-j'
for (uint i=0;i<27;i++) {
nbtlsuiv += lettertab[i][j][k];
}
for (uint i=0;i<27;i++) {
probatab[i][j][k] = (double)lettertab[i][j][k] / nbtlsuiv;
if(i!=0)
probatab[i][j][k] += probatab[i-1][j][k]; //Transformation en proba cumulative
}
}
}
//Traitement terminé. Indication lié au traitement ascii
if (clearAccent) {
ui->label_resume_analyse->setText("Type d'analyse : accents désaccentés");
analyse = asciiplus; }
else {
ui->label_resume_analyse->setText("Type d'analyse : sans accents");
analyse = ascii; }
//Autorise le "forcer_taille"
ui->check_forcerTaille->setEnabled(true);
ui->check_forcerTaille->setToolTip("");
lcoh=0; //pas de lcoh ici. lcoh=0 <=> traitement ascii
ui->label_resume_lcoh->setVisible(false); //cache la valeur lcoh
}
//Traitement terminé. Indications générales
ui->progr_Analyse->setValue(avRecup+avAnal+avProbatab-1);
ui->progr_Analyse->setToolTip("Non, la barre ne va pas à 100%. C'est frustrant, hein ?");
ui->onglet_generation->setEnabled(true);
ui->onglet_analyse->setEnabled(true);
ui->centralwidget->unsetCursor();
//Supprime les warning de changement
traitement_modifie();
on_spin_lcoh_valueChanged(lcoh);
QFile file(nomListeMots); QFileInfo fileinfo(file);
nomListeAnalysePrecedente=fileinfo.fileName(); //récupération du nom de la liste de mots
liste_modifie();
ui->statusbar->showMessage("Analyse terminée ! Prêt a inventer des mots !");
ui->tabWidget->setCurrentIndex(1);
}
void FenetrePrincipale::on_bouton_generer_clicked() {
ui->check_troll->setChecked(false);
if ((analyse==aucun)) {
ui->statusbar->showMessage("Vous devez analyser une liste de mots avant de générer des mots");
return; }
uint taille_max = ui->spin_tailleMax->value();
if(taille_max==0)
taille_max=100;
std::string mot;
for (int i=0; i<ui->spin_nbMots->value(); i++) {
if(analyse==utf_8)
mot = Qgenerateur(charmap,lcoh, ui->check_forcerTaille->isChecked(), taille_max);
if(analyse==ascii || analyse==asciiplus)
mot = generateur(probatab, ui->check_forcerTaille->isChecked(), taille_max);
ui->text_mots->append(QString::fromStdString(mot));
}
}
void FenetrePrincipale::on_bouton_selecFichier_clicked() {
nomListeMots = QFileDialog::getOpenFileName(this, "Selectionner une liste de mot .txt", "WordLists", "Fichier texte (*.txt)");
QFile file(nomListeMots);
QFileInfo fileinfo(file);
liste_modifie();
ui->bouton_selecFichier->setText(fileinfo.fileName());
if(ui->bouton_selecFichier->text()!="")
ui->radio_langPerso->setChecked(true);
else
ui->bouton_selecFichier->setText("(Aucun)");
}
void FenetrePrincipale::on_bouton_details_clicked() {
ui->Bof->setVisible(!ui->Bof->isVisible());
ui->Bof_2->setVisible(!ui->Bof_2->isVisible());
ui->Minable->setVisible(!ui->Minable->isVisible());
ui->Minable_2->setVisible(!ui->Minable_2->isVisible());
ui->Parfait->setVisible(!ui->Parfait->isVisible());
ui->Parfait_2->setVisible(!ui->Parfait_2->isVisible());
ui->Qualite->setVisible(!ui->Qualite->isVisible());
ui->Rapidite->setVisible(!ui->Rapidite->isVisible());
ui->line_details->setVisible(!ui->line_details->isVisible());
}
void FenetrePrincipale::on_bouton_nettoyer_clicked() {
ui->text_mots->clear();
}
void FenetrePrincipale::on_bouton_trier_clicked() {
QString text = ui->text_mots->toPlainText();
triParTaille(text);
ui->text_mots->setText(text);
}
void FenetrePrincipale::on_actionAide_triggered() {
m_FenAide = new FenAide();
m_FenAide->show();
}
void FenetrePrincipale::on_action_propos_de_ce_programme_triggered() {
m_Infos = new Infos();
m_Infos->show();
}
void FenetrePrincipale::on_actionUtiliser_les_valeur_actuelles_par_defaut_triggered() {
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Changer valeurs par defaut",
"Voulez vous changer les valeurs par défaut du programme ?\n"
"\nLes valeurs par défaut (càd celle au lancement du programme) seront remplacées par les valeurs actuelles\n"
"Sont concernés :\n"
" - La liste de mot\n"
" - La longueur de cohérence\n"
" - Le nombre de mot à générer\n"
" - La taille maximale des mots\n",
QMessageBox::Yes|QMessageBox::No);
//TODO : mieux que ça ! Heuresement qu'il n'y a que 5 paramètres...
if (reply == QMessageBox::Yes) {
//préparation pour écriture du chemin de la liste de mot
QFile file("WordLists/Parametres.xml");
if(file.open(QIODevice::WriteOnly)) {
QXmlStreamWriter xmlWriter(&file);
xmlWriter.writeStartElement("?xml version=\"1.0\" encoding=\"utf-8\"?");
xmlWriter.writeCharacters("\n");
xmlWriter.writeStartElement("valeursDef");
xmlWriter.writeCharacters("\n\t");
xmlWriter.writeStartElement("nomListe");
if(ui->radio_langPerso->isChecked())
xmlWriter.writeCharacters(nomListeMots);
else
xmlWriter.writeCharacters(nomListeMotsDefaut);
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\n");
xmlWriter.writeComment("Le chemin peut être donné en absolu ou en relatif");
xmlWriter.writeCharacters("\n\t");
xmlWriter.writeStartElement("modeTraitement");
if(ui->radio_ignore->isChecked())
xmlWriter.writeCharacters("ascii");
else if(ui->radio_minable->isChecked())
xmlWriter.writeCharacters("asciiplus");
else if(ui->radio_speciaux->isChecked())
xmlWriter.writeCharacters("utf_8");
else
xmlWriter.writeCharacters("aucun");
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\n");
xmlWriter.writeComment("Les valeurs possible du mode de traitement sont : aucun, ascii, asciiplus et utf_8");
xmlWriter.writeCharacters("\n\t");
xmlWriter.writeStartElement("lcoh");
xmlWriter.writeCharacters(QString::number(ui->spin_lcoh->value()));
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\n\t");
xmlWriter.writeStartElement("nbMots");
xmlWriter.writeCharacters(QString::number(ui->spin_nbMots->value()));
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\n\t");
xmlWriter.writeStartElement("tailleMax");
xmlWriter.writeCharacters(QString::number(ui->spin_tailleMax->value()));
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\n");
xmlWriter.writeEndElement();
xmlWriter.writeCharacters("\n");
}
else{
ui->statusbar->showMessage("Problème lors de l'écriture des valeurs par défaut");
}
}
}
void FenetrePrincipale::on_check_troll_clicked() {
QTimer::singleShot(80, this, SLOT(unchecking()));
}
void FenetrePrincipale::unchecking() {
std::this_thread::sleep_for(std::chrono::milliseconds(400));
ui->check_troll->setChecked(false);
}
void FenetrePrincipale::quit_troll() {
QMessageBox::information(this, "Vraiment ?",
"Sinon, y avait plus simple pour quitter hein...\n"
"Pourquoi y a toujours un bouton du menu pour quitter ?\n"
"Qui l'utilse ?...");
this->close();
}
void FenetrePrincipale::check_analyse_changed() {
bool changed = listeMots_changed || traitement_changed || lcoh_changed;
if (changed && analyse!=aucun) {
QIcon p(":/icones/icons/warning.png");
ui->tabWidget->setTabIcon(0,p);
ui->statusbar->showMessage("Attention, vous devez refaire l'analyse pour que les changements soient pris en compte");
}
else {
ui->tabWidget->setTabIcon(0,QIcon());
ui->statusbar->showMessage("");
}
}
void FenetrePrincipale::on_spin_lcoh_valueChanged(int value) {
if( (analyse==type_Trait::utf_8) & ((uint)value!=lcoh) ) {
ui->spin_lcoh->setStyleSheet("background-color: #FFBF00");
lcoh_changed = true; }
else {
ui->spin_lcoh->setStyleSheet("");
lcoh_changed = false; }
check_analyse_changed();
}
void FenetrePrincipale::traitement_modifie() {
if(analyse!=aucun) {
if(selectedTrait()!=analyse) {
traitement_changed=true;
if(ui->radio_ignore->isChecked()) {
ui->radio_ignore->setStyleSheet("background-color: #FFBF00");
ui->radio_minable->setStyleSheet("");
ui->radio_speciaux->setStyleSheet(""); }
else if(ui->radio_minable->isChecked()) {
ui->radio_ignore->setStyleSheet("");
ui->radio_minable->setStyleSheet("background-color: #FFBF00");
ui->radio_speciaux->setStyleSheet(""); }
else if(ui->radio_speciaux->isChecked()) {
ui->radio_ignore->setStyleSheet("");
ui->radio_minable->setStyleSheet("");
ui->radio_speciaux->setStyleSheet("background-color: #FFBF00"); }
}
else {
traitement_changed=false;
ui->radio_ignore->setStyleSheet("");
ui->radio_minable->setStyleSheet("");
ui->radio_speciaux->setStyleSheet("");
}
}
check_analyse_changed();
}
void FenetrePrincipale::liste_modifie() {
if(analyse!=aucun) {
bool usedLangDef = (nomListeMots==nomListeMotsDefaut);
if(ui->radio_langPerso->isChecked() && usedLangDef) {
ui->radio_langDef->setStyleSheet("");
ui->radio_langPerso->setStyleSheet("background-color: #FFBF00");
listeMots_changed=true; }
else if (ui->radio_langDef->isChecked() && usedLangDef) {
ui->radio_langDef->setStyleSheet("");
ui->radio_langPerso->setStyleSheet("");
listeMots_changed=false; }
else if(ui->radio_langDef->isChecked() && !usedLangDef) {
ui->radio_langDef->setStyleSheet("background-color: #FFBF00");
ui->radio_langPerso->setStyleSheet("");
listeMots_changed=true; }
else if(ui->bouton_selecFichier->text()!=nomListeAnalysePrecedente&& !usedLangDef) {
ui->radio_langDef->setStyleSheet("");
ui->radio_langPerso->setStyleSheet("background-color: #FFBF00");
listeMots_changed=true; }
else if(ui->radio_langPerso->isChecked() && !usedLangDef ) {
ui->radio_langDef->setStyleSheet("");
ui->radio_langPerso->setStyleSheet("");
listeMots_changed=false; }
else {
ui->radio_langDef->setStyleSheet("");
ui->radio_langPerso->setStyleSheet("");
listeMots_changed=false; }
}
check_analyse_changed();
}
</code></pre>
<p>Addition: Default value are stored in an xml file and loaded in FenetrePrincipale constructor. This file path is "wordlist/Parametres.xml" (from executable folder).</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<valeursDef>
<nomListe>wordlist/wordlist.txt</nomListe>
<!--Le chemin peut être donné en absolu ou en relatif-->
<modeTraitement>utf_8</modeTraitement>
<!--Les valeurs possible du mode de traitement sont : aucun, ascii, asciiplus et utf_8-->
<lcoh>3</lcoh>
<nbMots>1</nbMots>
<tailleMax>20</tailleMax>
</valeursDef>
</code></pre>
<p>The word analysis/generation in itself is contained in the fonction.h/.cpp files :
fonction.h</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef FONCTIONS
#define FONCTIONS
#include <map>
#include <vector>
#include <fstream>
#include <QString>
//Get the words listed in the wordlist (text file)
void extractWords(std::ifstream &liste, std::vector<std::string> &mots, std::vector<float> &proba);
//Remove accentuated letters (for 'analyze word')
std::string retireAccent(std::string &message);
//analyse one word and completes lettertab (of "fenetreprincipale"). ClearAccent=true handles accentuated letter by replacing them by their unaccentuated version
int analyzeWord(std::string &lemot, int lettertab[27][27][27], bool ClearAccent=false);
//analyse on word and completes the charmap (of "fenetreprincipale")
void QanalyzeWord(const QString &lemot, std::map<std::vector<QChar>, std::pair<int,double>> &charmap, uint lcoh, int &nb);
//Generates a word based on the table 'probatab'
std::string generateur(double probatab[27][27][27], bool forcedSize=false, uint maxsize=100);
//Generates a word based on the character map (charmap)
std::string Qgenerateur(std::map<std::vector<QChar>, std::pair<int,double>> &charmap, uint lcoh=3, bool forcedSize=false, uint maxsize=100);
//triParTaille : sort word displayed by size
void triParTaille(QString &liste_mots);
void Qechanger(QStringList &liste, int a, int b);
void Qquicksort(QStringList &liste, int debutR, int fin);
#endif // FONCTIONS
</code></pre>
<p>fonction.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include <vector>
#include <sstream>
#include <iostream>
#include "fonctions.h"
#include "fenetreprincipale.h"
//Fonction commencant par Q = fonction pour le traitement gérant tout les type de
//caratère et la longueur de cohérence (Q pour le Q de QString, le moyen le plus
//simple de gérer l'utf-8 (j'aime pas les wchar_t. C'est nul et pas pratique)
using namespace std;
void extractWords(ifstream &liste, vector<string> &mots, vector<float> &proba) {
int nb_lignes = 0; //number of lines on the wordlist
string line; //last read line
for (; getline(liste,line); nb_lignes++) {}; //Get number of lines
liste.clear();
liste.seekg(0, ios::beg); //going back to beginning of the file
getline(liste, line);
nb_lignes--; //Ignore first line
//TODO : manage comments on the file, e.g. lines beginning by //
mots.resize(nb_lignes);
proba.resize(nb_lignes);
for (int i=0; i<nb_lignes; i++) {
getline(liste, line);
string sproba;
stringstream ss;
ss << line;
ss >> mots[i] >> sproba; // get 1st word = actual word and 2nd word = occurence probability
if(sproba!="")
proba[i]=stof(sproba); //conversion to float
else //if no word probability is indicated, set it at 0
proba[i]=0;
}
liste.close();
return;
}
string retireAccent(string &message)
{
string accent("ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûüÿÑñÇç");
string sansAccent("AAAAAAaaaaaaOOOOOOooooooEEEEeeeeIIIIiiiiUUUUuuuuyNnCc");
int i=0,j=0,k=0,taille;
taille=message.size();
for (i=0;i<=taille;i++) {
for(j=0;j<=104;j=j+2) {
if((message[i]==accent[j])&&(message[i+1]==accent[j+1])) {
message[i]=sansAccent[j/2];
for(k=i+1;k<taille;k++) {
message[k]=message[k+1];
}
message=message.substr(0,taille-1);
taille=message.size();
}
}
}
return message;
}
int analyzeWord(string &lemot, int lettertab[27][27][27], bool ClearAccent) {
int pr1=0; //previous letter, default is nothing (0)
int pr2=0; //second-to-last letter, default is nothing (0)
int curr; //lettre actuelle
int nb=0; //nombre total de lettre traitées
for(unsigned int i=0; i<lemot.size(); i++) {
if(ClearAccent==true)
lemot=retireAccent(lemot);
curr=lemot.at(i)-96; // returns ascii code for the letter
if(curr>0 && curr <27) { //ignoring accentuated letter
lettertab[curr][pr1][pr2]++;
pr2=pr1;
pr1=curr; //current letter is now previous letter
nb++;
}
}
lettertab[0][pr1][pr2]++; //indicates the word finishes by "...."pr2""pr1"
return nb;
}
void QanalyzeWord(const QString &lemot, map<vector<QChar>, pair<int,double>> &charmap, uint lcoh, int &nb) {
vector<QChar> suiteLettres(lcoh,'\0'); //vecteur de longueur lcoh, initialisé à \0
for(int i=0; i<lemot.size(); i++) {
suiteLettres[lcoh-1]=lemot.at(i); //lcoh = suiteLettres.size()
charmap[suiteLettres].first++;
nb++;
for(uint j=0; j<lcoh-1; j++) {
suiteLettres[j]=suiteLettres[j+1];
}
}
//Indication de dernier charactère=vide
suiteLettres[lcoh-1]='\0';
charmap[suiteLettres].first++;
return;
}
string generateur (double probatab[27][27][27], bool forcedSize, uint maxsize) {
string monmot ="";
int pr1=0; //lettre précédente
int pr2=0; //avant-dernière lettre
int pot; //lettre potentielle
do {
pot=0;
double r = (double)rand() / RAND_MAX;
while (r > probatab[pot][pr1][pr2] && pot<26) {
pot++;
}
if (pot!=0){ //si pot=0 (eg. fin du mot) MAIS forcedSize, alors on ignore ce caractère
monmot += (char)(pot+96);
pr2=pr1;
pr1=pot;
}
} while ((pot!=0 || forcedSize) && monmot.size()<=maxsize); //!\ size=taille en octet=nb carac en ascii seulement
return monmot;
}
string Qgenerateur(std::map<std::vector<QChar>, pair<int,double>> &charmap, uint lcoh, bool forcedSize, uint maxsize) {
QString monmot="";
vector<QChar> cePr(lcoh-1,'\0');
vector<QChar> cePrMin, cePrMax; //debut et fin des élément de la map ayant ce Pr
cePrMin.reserve(lcoh); cePrMax.reserve(lcoh);
map<vector<QChar>, pair<int,double>>::iterator it, itLow, itHigh;
//itLow : itérateur vers le premier éléments de la map ayant ce Pr
//itHigh: itérateur vers l'élément suivant le dernier éléments de la map ayant ce Pr
do {
cePrMin=cePr; cePrMin.push_back(QChar::Null);
cePrMax=cePr; cePrMax.push_back(QChar::LastValidCodePoint);
itLow = charmap.lower_bound(cePrMin);
itHigh = charmap.upper_bound(cePrMax);
it = itLow;
double r = double(rand())/ RAND_MAX; // 0 < r < 1
while (r > it->second.second && it != itHigh) { //places iterator to the 1st caracter having a probability less than r
it++;
}
monmot += QString(it->first.back()); //append this caracter to the word
for(uint i=0; i<cePr.size()-1; i++) {
cePr[i] = cePr[i+1];
}
cePr[cePr.size()-1] = it->first.back();
} while ( (it->first.back()!='\0') && uint(monmot.size()) <= maxsize);
//TODO : implémenter le forced size
return monmot.toStdString();
}
void triParTaille(QString &liste_mots) {
QStringList splitted(liste_mots.split('\n'));
Qquicksort(splitted, 0, splitted.size()-1);
liste_mots = splitted.join("\n");
}
void Qechanger(QStringList &liste, int a, int b) {
//Fonction utilisée par le tri quicksort
QString temp = liste.at(a);
liste.replace(a, liste.at(b));
liste.replace(b,temp);
}
void Qquicksort(QStringList &liste, int debut, int fin) {
int gauche=debut-1;
int droite=fin+1;
const int pivot = liste.at(debut).size();
if(debut>=fin)
return;
while(1) {
do {droite--; } while(liste.at(droite).size() > pivot);
do gauche++; while(liste.at(gauche).size() < pivot);
if(gauche < droite)
Qechanger(liste, gauche, droite);
else break;
}
Qquicksort(liste, debut, droite);
Qquicksort(liste, droite+1, fin);
}
</code></pre>
<p>Now only remain an 'help' window and a 'about' window. I don't show the .ui here due to number of caraters limitation :
fenaide.h</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef FENAIDE_H
#define FENAIDE_H
#include <QDialog>
namespace Ui {
class FenAide; //=Help window
}
class FenAide : public QDialog
{
Q_OBJECT
public:
explicit FenAide(QWidget *parent = 0);
~FenAide();
public slots:
void on_bouton_moreInfo_clicked();
private:
Ui::FenAide *ui;
};
#endif // FENAIDE_H
</code></pre>
<p>fenaide.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "fenaide.h"
#include "ui_fenaide.h"
FenAide::FenAide(QWidget *parent) :
QDialog(parent),
ui(new Ui::FenAide)
{
ui->setupUi(this);
ui->text_details->setVisible(false);
this->adjustSize();
#ifdef __linux__
this->setFixedSize(this->width(),this->height());
#elif _WIN32
//Taille de fenetre fixe. Windows seulement
setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
#else
#endif
}
FenAide::~FenAide()
{
delete ui;
}
void FenAide::on_bouton_moreInfo_clicked() {
ui->text_details->setVisible(!ui->text_details->isVisible());
this->adjustSize();
}
</code></pre>
<p>infos.h</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef INFOS_H
#define INFOS_H
#include <QDialog>
namespace Ui {
class Infos;
}
class Infos : public QDialog
{
Q_OBJECT
public:
explicit Infos(QWidget *parent = 0);
~Infos();
private:
Ui::Infos *ui;
};
#endif // INFOS_H
</code></pre>
<p>infos.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "infos.h"
#include "ui_infos.h"
Infos::Infos(QWidget *parent) :
QDialog(parent),
ui(new Ui::Infos)
{
ui->setupUi(this);
// Make window fixed size
#ifdef __linux__
this->setFixedSize(this->width(),this->height());
#elif _WIN32
setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
#else
#endif
}
Infos::~Infos()
{
delete ui;
}
</code></pre>
<p>The .pro file if ever it is usefull</p>
<pre class="lang-cpp prettyprint-override"><code>TEMPLATE = app
CONFIG += qt
CONFIG += c++11
QT += widgets
SOURCES += main.cpp \
fonctions.cpp \
fenaide.cpp \
fenetreprincipale.cpp \
infos.cpp
HEADERS += \
fonctions.h \
fenaide.h \
fenetreprincipale.h \
infos.h
DISTFILES +=
FORMS += \
fenaide.ui \
fenetreprincipale.ui \
infos.ui
</code></pre>
<p>And finaly, the wordlist. It can be any .txt file like :</p>
<pre><code>//First line is ignored
This
is
a
wordlist
platypus
</code></pre>
<p>Edit:
In addition here are screenshots of the application.<br>
On the analyze tab, default behaviour is pre-selected (trhough the xml file), so user just has to click 'launch alaysis' ('lancer l'analyse'). User can select another wordlist using the button (on the top) ; and chooses between analysis type (ascii only characters, ascii + few accentuated letters, or utf-8)
<a href="https://i.stack.imgur.com/JLt1j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JLt1j.png" alt="Analyze tab"></a>
On the generate word tab, user chooses how many words he wants to create, and sets up a limit to a maximum number of characters.
<a href="https://i.stack.imgur.com/5a6C6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5a6C6.png" alt="Word generation tab"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T11:48:15.047",
"Id": "440976",
"Score": "1",
"body": "Can you provide a screenshot of the app?"
}
] |
[
{
"body": "<p>That is quite a lot of code, so I won't do a full review, just give some remarks about obvious things.</p>\n\n<h1>Try to avoid as much platform-specific code as possible</h1>\n\n<p>I see this piece of code:</p>\n\n<pre><code>#ifdef __linux__\n this->setFixedSize(this->width(),this->height());\n#elif _WIN32\n //Taille de fenetre fixe. Windows seulement\n setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);\n#else\n\n#endif\n</code></pre>\n\n<p>Is it really that important to have the <code>MSWindowsFixedSizeDialogHint</code> flag set? Also, you don't actually fix the size of the window in this case. The Qt documentation also advises against using this flag, since it apparently doesn't behave nice in multi-monitor setups.</p>\n\n<p>Even better would be to set a size constraint on the layout, as mentioned in <a href=\"https://doc.qt.io/qt-5/qwidget.html#setFixedSize\" rel=\"nofollow noreferrer\">the documentation for setFixedSize()</a>.</p>\n\n<h1>Accents change the sound of a character</h1>\n\n<pre><code>string accent(\"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûüÿÑñÇç\");\nstring sansAccent(\"AAAAAAaaaaaaOOOOOOooooooEEEEeeeeIIIIiiiiUUUUuuuuyNnCc\");\n</code></pre>\n\n<p>There it looks like you are just mapping every character to one which looks similar but without accents. However, in many languages, accents have a big impact on the sound, for example in German, \"ä\" sounds more like \"eh\" than \"a\". Even in French, \"ç\" sounds like \"s\" while where it is used, a \"c\" would have sounded like a \"k\".</p>\n\n<h1>Mixing languages in source code</h1>\n\n<p>You already apologized for using French variable and function names in the code. And from experience, I know many French developers prefer using French names in source code, so it's a culture thing that's probably hard to change. However, it has two drawbacks. First, it makes it harder to collaborate with non-French speaking persons on the same code. Second, since you are using C++ which uses English names for keywords, and the Qt library with is using English names as well, you are getting a horrible mix of languages in your code. For example:</p>\n\n<pre><code>else if(ui->radio_speciaux->isChecked())\n</code></pre>\n\n<p>But it even happens in variable and function names you completely declared yourself, like:</p>\n\n<pre><code>void FenetrePrincipale::on_bouton_generer_clicked() {\n</code></pre>\n\n<h1>Use a consistent code style</h1>\n\n<p>I see both <code>if (foo)</code> and <code>if(foo)</code> in your code, sometimes there are spaces surrounding operators, sometimes not. Keeping a consistent code style makes it easier to navigate the code and to spot errors. The exact code style you use is a matter of taste, but it's best to use something that is in common use.</p>\n\n<h1>Avoid using <code>new</code> and <code>delete</code></h1>\n\n<p>I see the following in the implementation of <code>class Fenaide</code>'s constructor and destructor:</p>\n\n<pre><code>FenAide::FenAide(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::FenAide)\n\n...\n\nFenAide::~FenAide()\n{\n delete ui;\n}\n</code></pre>\n\n<p>If you are always allocating memory for a variable in the constructor, and always freeing it in the destructor, you might just as well have made <code>ui</code> a regular member variable, but I guess in this case the full declaration of <code>Ui::FenAide</code> might be hidden. In that case, use a <code>std::unique_ptr<></code> to hold the pointer, so it gets cleaned up automatically, even when something <code>throw</code>s in the constructor:</p>\n\n<pre><code>class FenAide : public QDialog\n{\n ...\n\nprivate:\n std::unique_ptr<Ui::FenAide> ui;\n};\n</code></pre>\n\n<p>With the above, you can get rid of the destructor of <code>FenAide</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T13:07:52.183",
"Id": "441136",
"Score": "0",
"body": "`Ui::FenAide` is the class that's generated by `uic` - you can't change that namespace, AFAIK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T15:41:02.227",
"Id": "441165",
"Score": "0",
"body": "@TobySpeight Ah, well if that's because of the tools used then you can't do anything about it. Personally I avoid all these weird XML-to-C compilers. It's quite possible to write a Qt5 UI in pure C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:12:40.640",
"Id": "441172",
"Score": "0",
"body": "Concerning the flag, on windows (7) with setFixedSize you get a resize cursor on the side of the window even if it has no effect (because size is fixed) ; so I found this workaround to delete this cursor. Regarding new, delete and Ui:: namespace: all this code is part of the default template of Qt creator, so I did not change it. Where could I find resources for using Qt with more modern style?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T20:35:05.380",
"Id": "441233",
"Score": "0",
"body": "About `new` and `delete`: if it's autogenerated code, then I guess there's not much you can or should do about it. It will still work. Still, it would be nice if Qt would use `unique_ptr<>` and that it automatically fixes the cursor issue when you set a fixed size..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T15:45:07.803",
"Id": "441593",
"Score": "0",
"body": "The solution with `unique_ptr` you proposed work (apparently, I did test test it extensivly, nor would I know how to do that)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T15:57:54.153",
"Id": "442261",
"Score": "0",
"body": "Being born and raised in the USA, I understand what you said about variables and comments in French, but I have issues with it. Keep in mind that before English became the `Lingua Franca` or common language French as the common language for much of the world (at least the nobility in Europe). I also know that some of the best CS education programs are or have been in France."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T21:27:00.800",
"Id": "226796",
"ParentId": "226773",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T10:01:16.983",
"Id": "226773",
"Score": "3",
"Tags": [
"c++",
"qt"
],
"Title": "Generating word sounding similar to the ones given in a wordlist"
}
|
226773
|
<p>This is a <a href="https://codereview.stackexchange.com/questions/226423/bank-atm-app-mockup-implementing-domain-driven-design-ddd">follow-up on bank ATM mockup app</a> in .NET Core framework and Entity Framework Core. I have 2 user interfaces: Console and Web.</p>
<p>Previously I have UOW and repository layer but I have removed them as it is considered overkill by many. Now that I have removed repository layer, just wondering where should I have my <code>FindByCardNoPin</code> method like below? In application layer? Is my exception handling codes considered as good practice? Is this considered as domain-driven design or clean architecture or something else?</p>
<p><strong>Domain Model layer</strong></p>
<pre><code>public class BankAccount
{
public int Id { get; set; }
public string AccountName { get; set; }
public string CardNumber { get; set; }
public string CardPin { get; set; }
public decimal Balance { get; set; }
public decimal CheckBalance()
{
return Balance;
}
public void Deposit(int amount)
{
// Domain logic
Balance += amount;
}
public void Withdraw(int amount)
{
// Domain logic
if (amount > Balance)
{
throw new Exception("Withdraw amount exceed account balance.");
}
Balance -= amount;
}
}
public class Transaction
{
public int Id { get; set; }
public int BankAccountId { get; set; }
public DateTime TransactionDateTime { get; set; }
public TransactionType TransactionType { get; set; }
public decimal Amount { get; set; }
}
public enum TransactionType
{
Deposit, Withdraw
}
</code></pre>
<p><strong>Persistence layer</strong></p>
<pre><code> public class AppDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("[connstring]");
}
public DbSet<BankAccount> BankAccounts { get; set; }
public DbSet<Transaction> Transactions { get; set; }
}
public class DatabaseUtility
{
public void TestDBConn()
{
var db = new AppDbContext();
try
{
db.Database.CanConnect();
}
catch
{
throw new Exception("System error. Please contact the bank. ");
}
}
}
public class RepositoryBankAccount
{
private readonly AppDbContext context;
public RepositoryBankAccount()
{
context = new AppDbContext();
}
public BankAccount FindByCardNoPin(string cardNo, string cardPin)
{
var validUser = (from u in context.BankAccounts
where u.CardNumber.Equals(cardNo)
&& u.CardPin.Equals(cardPin)
select u).SingleOrDefault();
return validUser;
}
}
</code></pre>
<p><strong>Application layer</strong></p>
<pre><code>public class AccountService
{
public decimal CheckBalanceAmount(int bankAccountId)
{
BankAccount bankAccount;
using (var ctx = new AppDbContext())
{
bankAccount = ctx.BankAccounts.Find(bankAccountId);
}
if (bankAccount == null)
{
throw new Exception("Error");
}
return bankAccount.CheckBalance();
}
public void DepositAmount(BankAccount bankAccount, int amount)
{
using (var ctx = new AppDbContext())
{
using (var trans = ctx.Database.BeginTransaction())
{
try
{
bankAccount.Deposit(amount);
ctx.BankAccounts.Update(bankAccount);
var transaction = new Transaction()
{
BankAccountId = bankAccount.Id,
Amount = amount,
TransactionDateTime = DateTime.Now,
TransactionType = TransactionType.Deposit
};
ctx.Transactions.Add(transaction);
trans.Commit();
ctx.SaveChanges();
}
catch
{
trans.Rollback();
}
}
}
}
public void WithdrawAmount(BankAccount bankAccount, int amount)
{
using (var ctx = new AppDbContext())
{
using (var trans = ctx.Database.BeginTransaction())
{
try
{
bankAccount.Withdraw(amount);
ctx.BankAccounts.Update(bankAccount);
var transaction = new Transaction()
{
BankAccountId = bankAccount.Id,
Amount = amount,
TransactionDateTime = DateTime.Now,
TransactionType = TransactionType.Withdraw
};
ctx.Transactions.Add(transaction);
trans.Commit();
ctx.SaveChanges();
}
catch
{
trans.Rollback();
throw;
}
}
}
}
}
</code></pre>
<p><strong>User Interface Layer</strong> - Console (Note: For brevity, I just show one of the function: Withdraw)</p>
<pre><code>amount = GetAmount();
try
{
accountService.WithdrawAmount(bankAccount, amount);
Console.WriteLine($"Withdrew RM {amount} successfully. Please collect your RM {amount} cash. ");
}
catch (Exception ex)
{
// // todo: write ex.stacktrace into text file for programmer to do troubleshooting.
Console.WriteLine(ex.Message);
}
</code></pre>
<p><strong>User Interface Layer</strong> - Web</p>
<pre><code>public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
var repoBankAccount = new RepositoryBankAccount();
var validUser = repoBankAccount.FindByCardNoPin(Login.CardNumber, Login.CardPin);
if (validUser == null)
{
ViewData["Error"] = "Invalid card number or card pin.";
return Page();
}
// Create user session.
HttpContext.Session.SetInt32("userId", validUser.Id);
return RedirectToPage("/Secure/Dashboard");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T10:23:48.863",
"Id": "440973",
"Score": "4",
"body": "Is this the previous version of the app? https://codereview.stackexchange.com/questions/215086/bank-atm-in-c-console-project or this: https://codereview.stackexchange.com/questions/226423/bank-atm-app-mockup-implementing-domain-driven-design-ddd?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T13:47:46.340",
"Id": "440984",
"Score": "0",
"body": "The second one. That's the latest version before this version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:02:02.020",
"Id": "440985",
"Score": "3",
"body": "First Please move the paragraph and the code block at the bottom of the question to the top, it might clarify the question for some people. It might be better to put the FindByCardNoPin where you think it belongs and ask if it is in the correct place, asking where to put it is off-topic. Please provide a link to the previous question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T01:09:45.800",
"Id": "441031",
"Score": "1",
"body": "@pacmaninbw okay. I have moved it up and added my FindByCardNoPin method which I have currently."
}
] |
[
{
"body": "<h3>Domain Model layer</h3>\n\n<p>Your domain classes serve 3 conflicting purposes:</p>\n\n<ul>\n<li>Data Transfer Object</li>\n<li>ORM Object (Data Record for EF, some call this a DAO, others wouldn't)</li>\n<li>Business Entity</li>\n</ul>\n\n<p>For bigger projects, you would like to have 3 different layers exposing equivalent classes. The main problem for your API is that next to having business operations defined that guard the state of the entities, you're also exposing all state through public getters and setters. Let's take a look at <code>BankAccount</code>:</p>\n\n<blockquote>\n<pre><code>public int Id { get; set; }\npublic string AccountName { get; set; }\npublic string CardNumber { get; set; }\npublic string CardPin { get; set; }\npublic decimal Balance { get; set; }\n</code></pre>\n</blockquote>\n\n<p>Method <code>Withdraw</code> has a business rule defined, albeit hard-coded:</p>\n\n<blockquote>\n<pre><code>if (amount > Balance)\n{\n throw new Exception(\"Withdraw amount exceed account balance.\");\n}\n</code></pre>\n</blockquote>\n\n<p>But it could easily by cirmcumvented by calling the setter on <code>Balance</code></p>\n\n<pre><code>someBankAccount.Balance = -1000;\n</code></pre>\n\n<p>To solve this, you should have a different entity for the persistence layer than in the domain layer and use a mapper between layers.</p>\n\n<p>I would also advise to use use throw hard-coded validation messages, but use some pattern for it (get from DB, from resource files, ..). I would make a custom exception to indicate business errors.</p>\n\n<pre><code>throw new BusinessException(ResourceManager.GetString(Resources.WithDrawExceeded));\n</code></pre>\n\n<h3>Persistence Layer</h3>\n\n<p>I am not convinced of the concept to put all entity queryables in a single class <code>AppDbContext</code>. I would let each specific <code>Repository</code> have its own scope of what to manage.</p>\n\n<p>Class <code>DatabaseUtility</code> is a weird one, what would you use it for? Also, since it has no instance state, it should be made <em>static</em>. It's probably a convenience used only internally by the API, so make it <code>internal</code>. Method <code>TestDBConn</code> screems to return a <code>Boolean</code>. If you do decide to throw an error, I would throw some kind of <code>TechnicalException</code> to distinguish technical from business errors. Technical errors could be converted differently to end users, using a generic error message \"Something went wrong, please try again later\".</p>\n\n<p><code>RepositoryBankAccount</code> is usually called <code>BankAccountRepository</code>. Method <code>FindByCardNoPin</code> sits at the right location here. An endpoint should call <code>repository.FindByCardNoPin</code> rather than <code>service.FindByCardNoPin</code>. Only when additional business logic is required, the service should provide this method. But even then, the repository should also provide it as input for the service.</p>\n\n<p>Returning <code>SingleOrDefault</code> is ok if your model explicitly guards against multiple matches. But even then, if not found you'll get a generic .NET exception. Invest in your LINQ-style methods that take a friendly message on not found, too many found, etc.</p>\n\n<h3>Application Layer</h3>\n\n<p>This layer is pretty well implemented. It handles transactions, calls to repositories and business checks.</p>\n\n<p>Method <code>CheckBalanceAmount</code> throws a really lame exception. Clean this up a bit.</p>\n\n<pre><code>if (bankAccount == null)\n{\n throw new Exception(\"Error\");\n}\n</code></pre>\n\n<p>Method <code>DepositAmount</code> has different behavior than <code>WithdrawAmount</code> concerning transaction rollback. The former performs <code>trans.Rollback();</code> while the latter also rethrows the exception <code>throw;</code>. The latter is better practice. You should try to invest in a solution that handles transactions as an <a href=\"https://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"nofollow noreferrer\">aspect</a> instead, this to avoid boiler-plate code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T00:12:51.677",
"Id": "441465",
"Score": "0",
"body": "Thanks a lot for all the code review and comments :) For the exception, I guess I have to create another class library with both TechnicalException and BusinessException right? By the way, there is a issue I encounter. When I try to enter withdraw amount more than the account balance, it did throw the exception. But the second time, I enter the withdraw amount, the session became null. But if I throw my BusinessException in the Application layer, it has no issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T01:09:21.407",
"Id": "441473",
"Score": "0",
"body": "and for 'For bigger projects, you would like to have 3 different layers exposing equivalent classes', do you have any links with example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T04:25:32.147",
"Id": "441486",
"Score": "1",
"body": "Here's a small summary: http://bloomlab.blogspot.com/2014/05/data-transfer-object-business-object.html. You can also lookup each type of object individually at wikipedia to see what they are meant for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:42:44.310",
"Id": "441609",
"Score": "1",
"body": "regarding: _I would let each specific Repository have its own scope of what to manage._ - this only works with CRUD (which is in real-world rarely the case) as soon as you need a cross-repository query you're screwed :-P I always build a single repo for _everything_. The crud-repository pattern is a like virus distroying applications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T16:48:34.577",
"Id": "441611",
"Score": "0",
"body": "What do you think of creating two more derived `Transaction` types for `Deposit` and `Withdraw` where each of them would check the amount aginst being postiv or negative? Currently OP is using an `enum` for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:06:10.610",
"Id": "441614",
"Score": "0",
"body": "@t3chb0t I would make a repository by aggregated root. Perhaps BankAccount and Transaction can both be entities within the same aggregate root BankAccount. So a definition for 'own scope' could be debated :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T17:08:34.783",
"Id": "441616",
"Score": "0",
"body": "@t3chb0t The enum vs derived class dilemma is a common design decision. I'd opt for derived classes, only if each derived class has sufficient specific state/operations. In this case, I can see both designs being OK."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:10:00.800",
"Id": "226912",
"ParentId": "226774",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226912",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T10:22:13.047",
"Id": "226774",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"entity-framework-core"
],
"Title": "Bank ATM Mockup App"
}
|
226774
|
<p><a href="https://practice.geeksforgeeks.org/problems/immediate-smaller-element/0/?track=sp-arrays-and-searching&batchId=152" rel="nofollow noreferrer">Immediate Smaller Element</a> The code is working fine <a href="https://ide.geeksforgeeks.org/J4DblHKLOK" rel="nofollow noreferrer">Code is here.</a> For each element in the array, check whether the right adjacent element (on the next immediate position) of the array is smaller. If the next element is smaller, print that element. If not, then print -1. The only problem is I'm getting "Time Limit Exceeded" when I submit my answer <a href="https://practice.geeksforgeeks.org/problems/immediate-smaller-element/0/?track=sp-arrays-and-searching&batchId=152" rel="nofollow noreferrer">here</a>.
It shows </p>
<blockquote>
<p>Your program took more time than expected.Time Limit Exceeded<br>
Expected Time Limit < 3.496sec<br>
Hint: Please optimize your code and
submit again.</p>
</blockquote>
<p>How do I optimize my code to pass the time limit exceeded problem?</p>
<hr>
<blockquote>
<p><strong>Problem Statement</strong>: Given an integer array of size N. For each element
in the array, check whether the right adjacent element (on the next
immediate position) of the array is smaller. If next element is
smaller, print that element. If not, then print -1.</p>
<p><strong>Input</strong>: The first line of input contains an integer T denoting the
number of test cases. T testcases follow. Each testcase contains 2
lines of input: The first line contains an integer N, where N is the
size of array. The second line contains N integers(elements of the
array) sperated with spaces.</p>
<p><strong>Output</strong>: For each test case, print the next immediate smaller elements
for each element in the array.</p>
<p><strong>Constraints</strong>:<br>
1 ≤ T ≤ 200<br>
1 ≤ N ≤ 10E7<br>
1 ≤ arr[i] ≤ 1000<br>
Expected Time Limit < 3.496sec </p>
<p><strong>Example</strong>: </p>
<p><strong>Input</strong>:<br>
2<br>
5<br>
4 2 1 5 3<br>
6<br>
5 6 2 3 1 7</p>
<p><strong>Output</strong>:<br>
2 1 -1 3 -1<br>
-1 2 -1 1 -1 -1 </p>
<p><strong>Explanation</strong>:<br>
Testcase 1: Array elements are 4, 2, 1, 5, 3. Next to 4
is 2 which is smaller, so we print 2. Next of 2 is 1 which is smaller,
so we print 1. Next of 1 is 5 which is greater, so we print -1. Next
of 5 is 3 which is smaller so we print 3. Note that for last element,
output is always going to be -1 because there is no element on right.</p>
</blockquote>
<hr>
<p>Here is my code</p>
<pre><code>class Program
{
static void Main(string[] args)
{
int testCases = int.Parse(Console.ReadLine().Trim());
while (testCases-- > 0)
{
int arrSize = int.Parse(Console.ReadLine().Trim());
string[] arr = Console.ReadLine().Trim().Split(' ');
for (int i = 0; i < arrSize - 1; i++)
{
if (int.Parse(arr[i]) > int.Parse(arr[i + 1]))
{
Console.Write(arr[i + 1] + " ");
}
else
Console.Write("-1" + " ");
}
Console.Write("-1");
Console.WriteLine();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:40:08.603",
"Id": "440988",
"Score": "1",
"body": "In cases like this you might want to profile the code to see where you are spending the most time. In some languages that might require you to break the solution up into multiple functions."
}
] |
[
{
"body": "<h3>Things to improve</h3>\n\n<ul>\n<li>You are looping over the input twice; (1) when splitting the raw input string <code>Console.ReadLine().Trim().Split(' ')</code> (2) when going over the splitted items <code>for (int i = 0; i < arrSize - 1; i++)</code>. Try finding a way to go over the raw input in a single pass.</li>\n<li>You are parsing most items twice, once as <code>arr[i+1]</code> and once as <code>arr[i]</code> in the next cycle. Try avoiding redundant parsing.</li>\n<li>Writing to the console is time expensive. <code>Console.Write(\"-1\" + \" \");</code> Try to find a way to build the string and write the result to the console once.</li>\n</ul>\n\n<p><sup>I just tested a solution taking into account the above and I got Execution Time: <code>1.21</code>. So it's definately possible to go < <code>3.496</code></sup> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T22:41:55.067",
"Id": "441020",
"Score": "1",
"body": "Lazy parsing seems like the next step to investigate. A lot of time is wasted splitting strings up, copying substrings around, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T07:13:54.293",
"Id": "441690",
"Score": "0",
"body": "Thanks a lot for your reply. It solved my problem. But,\n1.[Link](https://ide.geeksforgeeks.org/xtwfFLXT7T) How may I optimize code further?\n2.\"You are looping over the input twice..Try finding a way to go over the raw input in a single pass.\" - I could not figure out this. May you tell me how to do that?\n3.\"I just tested a solution taking into account the above and I got Execution Time: 1.21\"- May you share your code with me?\nThanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T07:25:04.557",
"Id": "441692",
"Score": "0",
"body": "I suggest you ask a follow-up question with your updated code :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T13:06:27.900",
"Id": "226777",
"ParentId": "226775",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "226777",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T12:05:47.443",
"Id": "226775",
"Score": "6",
"Tags": [
"c#",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Immediate Smaller Element Time Limit Exceeded"
}
|
226775
|
<p>I have this long line of code:</p>
<pre class="lang-py prettyprint-override"><code>enc = encoder.predict(np.array([data[stock][4*i:4*(i+30)] for i in range(lens[stock]+days-30)]))
</code></pre>
<p>The problem is, the number of characters (97) exceed 79, which is not allowed by PEP 8. To follow the PEP 8 guideline I can</p>
<pre class="lang-py prettyprint-override"><code>temp = [data[stock][4*i:4*(i+30)] for i in range(lens[stock]+days-30)]
enc = encoder.predict(np.array(temp))
</code></pre>
<p>But this creates a new variable that is stored in memory, rather then just a temporary storage in the first case. I'm assuming this takes slightly more time as well. The question is, is it worth compromising on speed to follow the guidelines/improve readability?</p>
<p>(PS: If there is a way to break down that one line of code into multiple lines, I would like to know)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:50:59.097",
"Id": "440990",
"Score": "1",
"body": "You also use 4 magical numbers which should be replaced anyway with 4 properly named constants (making the statement even longer). Also, `temp` would be a terrible variable name, I am sure you could find a more meaningful name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T23:17:06.453",
"Id": "441024",
"Score": "0",
"body": "My `ipython` `timeit` test of a simpler version of making an array from a list comprehension actually runs a bit faster with the `temp` variable. The interpreter has to run the list comprehension before it is passed to `np.array` regardless. Assigning that list object a name does not cost extra time; there's no difference in memory usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:17:57.683",
"Id": "441041",
"Score": "2",
"body": "So that we can give you proper advice, please describe what calculation is being performed, and make that the title of the question. See [ask]. Also include the code for the `predict` function, since that could be part of your problem."
}
] |
[
{
"body": "<p>A reasonable question to ask, maybe not for a single instance but if you end up with extremely performance-sensitive code. <a href=\"https://black.now.sh/?version=stable&state=_Td6WFoAAATm1rRGAgAhARYAAAB0L-Wj4ACeAIBdAD2IimZxl1N_WlgA5-PRwqIocXeLYTyQR6agwuTzex71SU3kwayO6z1sOQpf5xYC_zy_BAEPWDQq9-VBhNCbawwbwgzVY-ub_WvCOL7Y51f1_HUcsxUfS0NyIVb5077-A4hRXx1pNzk63cruo-5psTm9bdRM0Lmgj93i3jDfHla0AFwQIlU9VqI6AAGcAZ8BAACQsHBwscRn-wIAAAAABFla\" rel=\"nofollow noreferrer\">Black formats the code like this</a>:</p>\n\n<pre><code>enc = encoder.predict(\n np.array(\n [\n data[stock][4 * i : 4 * (i + 30)]\n for i in range(lens[stock] + days - 30)\n ]\n )\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T19:24:40.753",
"Id": "441012",
"Score": "4",
"body": "\"if you end up with extremely performance-sensitive code.\" Then write it in C with Python bindings, or just stand alone C++."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T17:04:47.577",
"Id": "226785",
"ParentId": "226776",
"Score": "4"
}
},
{
"body": "<p>This is not a bad question. Fundamentally, your line of thought is a perfect example of <a href=\"https://en.wikipedia.org/wiki/Program_optimization#When_to_optimize\" rel=\"nofollow noreferrer\">premature optimization</a>. Optimization on its own is not a bad thing, but</p>\n\n<ol>\n<li>you should know that this line of code is the line of code that slows the program down;</li>\n<li>since the line is so complex, you should know which part of this line is the slowest;</li>\n<li>you should be somewhat confident that making this single-line pile of code is worth the performance gain given the significant drop in legibility and maintainability.</li>\n</ol>\n\n<p>It's very important to profile - to measure the performance of your code, and to find bottlenecks. Without this, we as programmers are entirely blind to the actual performance characteristics of our code. Your usual priorities should be strongly biased toward making it legible and correct well before making it fast, and when you do make it fast, you need to already know where the speedups are needed to a fairly good degree of accuracy.</p>\n\n<p>In short, the code that you showed is unmaintainable. It needs to be spread over many more lines than it is now, and if you think it's worth profiling - great! Measure the before and after!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T01:48:42.300",
"Id": "226805",
"ParentId": "226776",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226785",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T12:47:01.937",
"Id": "226776",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy"
],
"Title": "Is it worth to compromise on speed to follow PEP 8 guidelines?"
}
|
226776
|
<h1>Abstract</h1>
<p>I am a beginner of Rust language. As my practice I want to create simple train reservation system. </p>
<p>I know little about the "best practice" in Rust, so I want some advises in my code. In terms of the function there are much luck to improve, but I want advises about how to write codes "in Rust".</p>
<h1>Code structure</h1>
<pre class="lang-bsh prettyprint-override"><code>reservation
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── lib.rs
│ ├── main.rs
│ └── reserve_request
│ └── mod.rs
└── target
</code></pre>
<h1>My codes</h1>
<p>lib.rs</p>
<pre class="lang-rust prettyprint-override"><code>pub mod reserve_request;
</code></pre>
<p>reserve_request/mod.rs</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
#[derive(PartialEq, Eq, Hash)]
pub struct Stations<'a> {
pub start: &'a str,
pub destination: &'a str,
}
pub struct Request<'a> {
pub start: &'a str,
pub destination: &'a str,
pub time: &'a str,
pub time_kind: &'a str,
}
impl<'a> Request<'a> {
pub fn reserve(&self, timetable: HashMap<Stations, &[&str]>) -> bool {
let st = Stations {
start: self.start,
destination: self.destination,
};
let times = timetable.get(&st);
let default: &[&str] = &[];
let result = match times {
Some(r) => r,
None => default,
};
for t in result {
if *t == self.time {
return true;
}
}
false
}
pub fn is_valid(&self) -> bool {
if self.start == "" {
println!("You need to determine start point");
return false;
} else if self.destination == "" {
println!("You need to determine destination");
return false;
} else if self.start == self.destination {
println!("Invalid. The start point and destication is same");
} else if self.time == "" && self.time_kind != "" {
println!("Invalid time specification");
return false;
}
true
}
}
</code></pre>
<p>main.rs</p>
<pre class="lang-rust prettyprint-override"><code>use reserve::reserve_request;
use std::collections::HashMap;
fn main() {
//TODO: save time table in the json file
let time: &[&str] = &["12:00", "14:00", "18:00", "19:00"];
let mut stations = HashMap::new();
stations.insert(
reserve_request::Stations {
start: "Tokyo",
destination: "Kyoto",
},
time,
);
let request = reserve_request::Request {
start: "Tokyo",
destination: "Kyoto",
time: "18:00",
time_kind: "start",
};
if request.is_valid() && request.reserve(stations) {
println!("Succeed in reserving that train");
} else {
println!("Failed to reserved that train");
}
}
</code></pre>
<h1>What I want to know especially</h1>
<ul>
<li><p>In main.rs, to make a value of the <code>HashMap</code> (type <code>&[&str]</code>), I define <code>time</code> variable and insert into HashMap. I feel it is redundant but I do not know how to deal with.</p></li>
<li><p>Similar to above, in mod.rs, I make <code>default</code> variable for using in match clause only.</p></li>
</ul>
|
[] |
[
{
"body": "<pre><code>let time: &[&str] = &[\"12:00\", \"14:00\", \"18:00\", \"19:00\"];\nlet mut stations = HashMap::new();\nstations.insert(\n reserve_request::Stations {\n start: \"Tokyo\",\n destination: \"Kyoto\",\n },\n time,\n);\n</code></pre>\n\n<p>Ok, I assume you tried putting the value assigned to <code>time</code> directly in the expression, but were unable to resolve the resulting error message. The problem is that expression has the type <code>[&str; 4]</code>, an array. But you want a slice: <code>&[&str]</code> instead. There a few ways to resolve this:</p>\n\n<p>Firstly, you can specify the type of the HashMap:</p>\n\n<pre><code>let mut stations: HashMap<reserve_request::Stations, &[&str]> = HashMap::new();\nstations.insert(\n reserve_request::Stations {\n start: \"Tokyo\",\n destination: \"Kyoto\",\n },\n &[\"12:00\", \"14:00\", \"18:00\", \"19:00\"]\n);\n</code></pre>\n\n<p>This way, Rust will infer what type you actually wanted at convert the reference to an array into a slice.</p>\n\n<p>Alternatively, you can manually request a slice by called <code>.as_ref()</code> on the array:</p>\n\n<pre><code>let mut stations = HashMap::new();\nstations.insert(\n reserve_request::Stations {\n start: \"Tokyo\",\n destination: \"Kyoto\",\n },\n [\"12:00\", \"14:00\", \"18:00\", \"19:00\"].as_ref()\n);\n</code></pre>\n\n<p>However, a better approach would be to not use arrays at all. Rust arrays are really just not that useful, and you almost always should prefer to use a Vec. Furthermore, if you implement loading from JSON as your comment suggests, then you'll certainly get a Vec and not a slice. </p>\n\n<pre><code>let mut stations = HashMap::new();\nstations.insert(\n reserve_request::Stations {\n start: \"Tokyo\",\n destination: \"Kyoto\",\n },\n vec![\"12:00\", \"14:00\", \"18:00\", \"19:00\"]\n);\n</code></pre>\n\n<p>Moving on the second part where you had an issue:</p>\n\n<pre><code> let times = timetable.get(&st);\n let default: &[&str] = &[];\n</code></pre>\n\n<p>Firstly, we have the same problem as before with a (in this case empty) array. It can be solved in the same way as above.</p>\n\n<pre><code> let result = match times {\n Some(r) => r,\n None => default,\n };\n</code></pre>\n\n<p><code>Option</code> has a method, <code>unwrap_or</code> which does the same thing:</p>\n\n<pre><code> let result = timetable.get(&st).unwrap_or([].as_slice());\n</code></pre>\n\n<p>However, a better approach would be use an <code>if let</code> statement.</p>\n\n<pre><code> if let Some(times) = timetable.get(&st) {\n for t in times {\n if *t == self.time {\n return true;\n }\n }\n }\n</code></pre>\n\n<p>This way the loop over times only runs if it was present and you don't need to create and iterate over an empty slice.</p>\n\n<p>However, if you use Vec instead of slices as I suggest, the inner loop can be written as a call to the contains function:</p>\n\n<pre><code> if times.contains(&self.time) {\n return true;\n }\n</code></pre>\n\n<p>Or you can replace the whole function with:</p>\n\n<pre><code> timetable\n .get(&Stations {\n start: self.start,\n destination: self.destination\n })\n .map_or(false, |times| times.contains(&self.time))\n</code></pre>\n\n<p>map_or returns false if the time table was not found, otherwise it calls the closure which checks if times contains the appropriate time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-15T02:17:34.260",
"Id": "445215",
"Score": "0",
"body": "Thanks. I'll study the error processing (?) more."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T16:22:04.437",
"Id": "227277",
"ParentId": "226779",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227277",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:16:38.997",
"Id": "226779",
"Score": "1",
"Tags": [
"beginner",
"rust"
],
"Title": "Train reservation system in Rust as my practice"
}
|
226779
|
<p>In the last days I've written a number guessing game that I've posted <a href="https://codereview.stackexchange.com/questions/226491/number-guessing-game-in-java">on this site</a>.</p>
<p>I have now written a lottery simulation in which I tried to acknowledge the criticisms of the project mentioned above. I also tried to add error handling. If the user enters invalid numbers or complete bullshit, the program will not crash any longer.</p>
<p><a href="https://lottery-simulation.dexter1997.repl.run/" rel="nofollow noreferrer">You can test the program here.</a> Dont wonder: The online interpreter needs a little time before it start the program.</p>
<p>Have I sufficiently implemented the criticism of the last Code Review? Are there new things that should be better?</p>
<p>Thank you for answers!</p>
<p><strong>Main.java</strong></p>
<pre><code>import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
LotteryGame game = new LotteryGame(6, 1, 49);
System.out.println(game.getExplanationString());
boolean run = true;
while (run) {
game.play();
System.out.print("Continue (Y / N): ");
System.out.flush();
run = scanner.nextLine().equalsIgnoreCase("Y");
System.out.println();
}
}
}
</code></pre>
<p><strong>LotteryGame.java</strong></p>
<pre><code>import java.util.Scanner;
public class LotteryGame {
private Scanner scanner = new Scanner(System.in);
private final int drawSize;
private final int drawLowerLimit;
private final int drawUpperLimit;
public LotteryGame(int drawSize, int drawLowerLimit, int drawUpperLimit) {
this.drawSize = drawSize;
this.drawLowerLimit = drawLowerLimit;
this.drawUpperLimit = drawUpperLimit;
}
public void play() {
// generate new random draw
Draw draw = Draw.generateRandomDraw(drawSize, drawLowerLimit, drawUpperLimit);
// let the user guess
Draw userDraw = guess();
// compare the draws and print result
int rightNumbers = draw.compare(userDraw);
System.out.println("Your guess: " + userDraw.getStringRepresentation());
System.out.println("Draw: " + draw.getStringRepresentation());
System.out.println("You guessed " + rightNumbers + " right!");
System.out.println();
}
public Draw guess() {
int numbers[] = new int[drawSize];
while (true) {
try {
for (int i = 0; i < drawSize; i++) {
numbers[i] = HelpfulFunctions.saveIntInput("Number " + (i+1) + ": ");
}
System.out.println();
return new Draw(numbers);
} catch (IllegalArgumentException e) {
System.out.println("The numbers have to be unique\n");
}
}
}
public String getExplanationString() {
StringBuilder sb = new StringBuilder();
sb.append("You have to guess the numbers of a lottery draw.\n");
sb.append("A draw consists of 6 different numbers.\n");
sb.append("Each number is in a range between 1 and 49.\n");
sb.append("The more numbers you guess right, the luckier you can be!\n");
return sb.toString();
}
}
</code></pre>
<p><strong>Draw.java</strong></p>
<pre><code>import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class Draw {
public int[] numbers;
public Draw(int[] numbers) throws IllegalArgumentException {
// check if all numbers are unique
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (i == j) continue;
if (numbers[i] == numbers[j]) {
throw new IllegalArgumentException("All numbers have to be unique.");
}
}
}
this.numbers = numbers;
}
public static Draw generateRandomDraw(int numberOfEntries, int lowerLimit, int upperLimit) {
// generate list that contains possible values
List<Integer> possibleValues = new ArrayList<>();
for (int i = lowerLimit; i <= upperLimit; i++) {
possibleValues.add(i);
}
// fill draw with randomly picked values
int[] numbers = new int[numberOfEntries];
Random random = new Random();
for (int i = 0; i < numberOfEntries; i++) {
int randomIndex = random.nextInt(possibleValues.size());
Integer pickedValue = possibleValues.get(randomIndex);
possibleValues.remove(pickedValue);
numbers[i] = pickedValue;
}
Arrays.sort(numbers);
return new Draw(numbers);
}
// returns count of equal numbers
public int compare(Draw draw) throws IllegalArgumentException {
if (draw.numbers.length != numbers.length) {
throw new IllegalArgumentException("The draws dont have the same length.");
}
int count = 0;
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers.length; j++) {
if (numbers[i] == draw.numbers[j]) {
count++;
}
}
}
return count;
}
public String getStringRepresentation() {
StringBuilder sb = new StringBuilder();
sb.append("[" + numbers[0]);
for (int i = 1; i < numbers.length; i++) {
sb.append(", " + numbers[i]);
}
sb.append("]");
return sb.toString();
}
}
</code></pre>
<p><strong>HelpfulFunctions.java</strong></p>
<pre><code>import java.util.Scanner;
public class HelpfulFunctions {
private static Scanner scanner = new Scanner(System.in);
public static int saveIntInput(String message) {
while (true) {
try {
System.out.print(message);
System.out.flush();
return Integer.valueOf(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Not a valid number.");
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some suggestion, I have seen you used a method called to <code>getStringRepresentation()</code> in the <code>Draw</code> class to print a representation of the object: for all classes you can use the common method <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString--\" rel=\"nofollow noreferrer\">toString</a>, overriding it for every class with the <code>@Override</code> annotation. You can then use in your code <code>System.out.println(\"Your guess: \" + draw)</code> instead of <code>System.out.println(\"Your guess: \" + draw.getStringRepresentation())</code> obtaining the same result. It seems me from your code that you have multiple Scanner instances referring to stdin inside your classes; it should be better encapsulate the scanner in one place and call it from every class that use it, see <a href=\"https://stackoverflow.com/questions/19766566/java-multiple-scanners\">this</a> for details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T14:21:49.533",
"Id": "441151",
"Score": "0",
"body": "I've heard that toString() is only meant for technical sort of output and that this method should not be used for displaying user output"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:15:06.843",
"Id": "441173",
"Score": "0",
"body": "It is used for representation as a 'String' for every object internal state and it has been included in the `Object` class and consequently in all classes including those created by a user, so it is already present in your classes .From the link to Java documentation \"Returns a string representation of the object and it is recommended that all subclasses override this method\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:49:04.750",
"Id": "441199",
"Score": "0",
"body": "Hmmm, okay I guess you're right - I will account that in a later version!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T13:51:37.023",
"Id": "226842",
"ParentId": "226780",
"Score": "1"
}
},
{
"body": "<p>I'll put my comments inline. In order:</p>\n\n<p><strong>Main:</strong></p>\n\n<pre><code>import java.util.Scanner;\n\npublic class Main {\n</code></pre>\n\n<p>I saw this came up in your previous question, too, but <code>Main</code> is not a good name. As someone seeing your code for the first time, I have no idea what <code>Main</code> is - I know from the name that it's the <em>entrypoint</em> to your logic, but I have no idea <em>what</em> logic it's the entrypoint for. For classes with a <code>main()</code> method that starts up some other class' logic, I like the <code>_Runner</code> naming scheme. E.g. <code>LotteryGameRunner</code>. What does it do? It runs the lottery game. I already know what type of logic to expect (a <code>main()</code> method) and what system the logic belongs to.</p>\n\n<pre><code> private static Scanner scanner = new Scanner(System.in);\n\n public static void main(String[] args) {\n LotteryGame game = new LotteryGame(6, 1, 49);\n</code></pre>\n\n<p>Magic numbers: I don't know what <code>6</code>, <code>1</code>, and <code>49</code> mean. I see them defined in another class, but it's a pain to have to look there every time I need to double check whether it's 6 draw size and 1 lower limit, or 1 draw size and 6 lower limit. Use variables just like you do in the other class, so when you need to change them later you can be sure you're changing the one you think you're changing, without needing to count its index in the parameters to be sure.</p>\n\n<p>Whether it's necessary to pull out parameters into temporary variables varies, but in this case there are two strong arguments for it: 1. these are <code>int</code>'s, so we have <strong>no</strong> information about their meaning as we would if they were named objects, 2. these are really <strong>configuring</strong> your program - they're not calculated, you're just providing them in the code. Configuration, as much as possible, should be pulled out of logic, so that when you need to change the configuration, you're not touching a line of logic.</p>\n\n<pre><code> System.out.println(game.getExplanationString());\n boolean run = true;\n while (run) {\n game.play();\n System.out.print(\"Continue (Y / N): \");\n System.out.flush();\n run = scanner.nextLine().equalsIgnoreCase(\"Y\");\n System.out.println();\n }\n } \n}\n</code></pre>\n\n<p>The above looks good. Nice!</p>\n\n<p><strong>LotteryGame:</strong></p>\n\n<pre><code>import java.util.Scanner;\n\npublic class LotteryGame {\n private Scanner scanner = new Scanner(System.in);\n\n private final int drawSize;\n private final int drawLowerLimit;\n private final int drawUpperLimit;\n</code></pre>\n\n<p>These are nicely named.</p>\n\n<pre><code> public LotteryGame(int drawSize, int drawLowerLimit, int drawUpperLimit) {\n this.drawSize = drawSize;\n this.drawLowerLimit = drawLowerLimit;\n this.drawUpperLimit = drawUpperLimit;\n }\n</code></pre>\n\n<p>And this is a good way to do the constructor.</p>\n\n<pre><code> public void play() {\n // generate new random draw\n Draw draw = Draw.generateRandomDraw(drawSize, drawLowerLimit, drawUpperLimit);\n\n // let the user guess\n Draw userDraw = guess();\n\n // compare the draws and print result\n int rightNumbers = draw.compare(userDraw);\n System.out.println(\"Your guess: \" + userDraw.getStringRepresentation());\n</code></pre>\n\n<p>See comment on <code>getStringRepresentation()</code> below.</p>\n\n<pre><code> System.out.println(\"Draw: \" + draw.getStringRepresentation());\n System.out.println(\"You guessed \" + rightNumbers + \" right!\");\n System.out.println();\n }\n\n public Draw guess() {\n int numbers[] = new int[drawSize];\n while (true) {\n try {\n for (int i = 0; i < drawSize; i++) {\n numbers[i] = HelpfulFunctions.saveIntInput(\"Number \" + (i+1) + \": \");\n }\n System.out.println();\n return new Draw(numbers);\n } catch (IllegalArgumentException e) {\n System.out.println(\"The numbers have to be unique\\n\");\n }\n</code></pre>\n\n<p>Try-catch blocks should generally not be used for normal logic. A good rule of thumb is that, if the same method keeps running after the try-catch block is executed, it shouldn't be a try-catch block (there are a lot of caveats to this; one very common pattern that rightfully breaks this rule is failing slowly - running a processing loop over a collection that processes every item, catching every exception and waiting until the end to throw them all). In this case, you're using the try-catch to enable a loop in the logic itself. Instead, just check whether all the numbers the user has given you were unique:</p>\n\n<pre><code> while (true) {\n for (int i = 0; i < drawSize; i++) {\n numbers[i] = HelpfulFunctions.saveIntInput(\"Number \" + (i+1) + \": \");\n }\n System.out.println();\n\n // a set inserts only unique items, leaving out duplicates\n if (new HashSet<Integer>(Arrays.asList(numbers)).size() == numbers.length) {\n return new Draw(numbers);\n } else {\n System.out.println(\"The numbers have to be unique\\n\");\n }\n }\n }\n\n public String getExplanationString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"You have to guess the numbers of a lottery draw.\\n\");\n sb.append(\"A draw consists of 6 different numbers.\\n\");\n sb.append(\"Each number is in a range between 1 and 49.\\n\");\n sb.append(\"The more numbers you guess right, the luckier you can be!\\n\");\n return sb.toString();\n }\n}\n</code></pre>\n\n<p>1 and 49?! If that's set in stone, then they shouldn't be input parameters above. If it's not set in stone, those same variables should be used here - you'll probably need to pull them out into <code>public final static</code> constants.</p>\n\n<p>Also, is there ever a case when you're not immediately printing the result of this method? If there is not, then it would be simpler to rename it to <code>public void printExplanationString()</code> and have it <code>System.out.println()</code> each of its currently appended lines.</p>\n\n<p><strong>Draw:</strong></p>\n\n<pre><code>import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Random;\n\npublic class Draw {\n public int[] numbers;\n\n public Draw(int[] numbers) throws IllegalArgumentException {\n // check if all numbers are unique\n for (int i = 0; i < numbers.length; i++) {\n for (int j = 0; j < numbers.length; j++) {\n if (i == j) continue;\n if (numbers[i] == numbers[j]) {\n throw new IllegalArgumentException(\"All numbers have to be unique.\");\n }\n }\n }\n</code></pre>\n\n<p>Use the same uniqueness checking as above - it'll be much shorter, and it's actually more efficient than a nested loop :)</p>\n\n<pre><code> this.numbers = numbers;\n }\n\n public static Draw generateRandomDraw(int numberOfEntries, int lowerLimit, int upperLimit) {\n // generate list that contains possible values\n List<Integer> possibleValues = new ArrayList<>();\n for (int i = lowerLimit; i <= upperLimit; i++) {\n possibleValues.add(i);\n }\n\n // fill draw with randomly picked values\n int[] numbers = new int[numberOfEntries];\n Random random = new Random();\n for (int i = 0; i < numberOfEntries; i++) {\n int randomIndex = random.nextInt(possibleValues.size());\n Integer pickedValue = possibleValues.get(randomIndex);\n possibleValues.remove(pickedValue);\n numbers[i] = pickedValue;\n }\n</code></pre>\n\n<p>Rather than generate your own random <code>int</code>s between <code>lowerLimit</code> and <code>upperLimit</code>, you can let <code>Random</code> do it for you. Check out <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#ints-int-int-\" rel=\"nofollow noreferrer\">Random.ints()</a></p>\n\n<pre><code> Arrays.sort(numbers);\n\n return new Draw(numbers);\n }\n\n // returns count of equal numbers\n public int compare(Draw draw) throws IllegalArgumentException {\n if (draw.numbers.length != numbers.length) {\n throw new IllegalArgumentException(\"The draws dont have the same length.\");\n }\n\n int count = 0;\n for (int i = 0; i < numbers.length; i++) {\n for (int j = 0; j < numbers.length; j++) {\n if (numbers[i] == draw.numbers[j]) {\n count++;\n }\n }\n }\n</code></pre>\n\n<p>Careful! What's the maximum value returned by <code>compare()</code>? It should probably be <code>numbers.length</code>. Is it?</p>\n\n<pre><code> return count;\n }\n\n public String getStringRepresentation() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\" + numbers[0]);\n for (int i = 1; i < numbers.length; i++) {\n sb.append(\", \" + numbers[i]);\n }\n sb.append(\"]\");\n return sb.toString();\n }\n}\n</code></pre>\n\n<p>As another answer has mentioned: this method is doing what <code>toString()</code> is supposed to do. Just name it <code>toString</code> and add an <code>@Override</code> tag, and you'll be good to go.</p>\n\n<p><strong>HelpfulFunctions:</strong></p>\n\n<p>This name is not the best. Classes like these are nifty for beginning programmers who tinker with similar things a bunch. However, they're still not as good as just bundling related logic into helpful library classes named for what they do (InputSaving.java, anyone?). Furthermore, <strong>this</strong> class only has one method. Until you know you need this method in another place, just leave it as part of a class for this system. <code>LotteryGame</code> is probably a good spot.</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class HelpfulFunctions {\n private static Scanner scanner = new Scanner(System.in);\n\n public static int saveIntInput(String message) {\n while (true) {\n try {\n System.out.print(message);\n System.out.flush();\n</code></pre>\n\n<p>The method is called <code>saveIntInput</code>, but it's not saving anything (it's just returning an attempt to parse a <code>String</code> to an <code>int</code>), and worse, it <strong>is</strong> doing things other than that: it's printing messages. Another good rule of thumb is that, except for temporary debugging <code>println()</code>'s, methods should only call <code>System.out.println()</code> if they're communicating directly with the user. Couple this with the fact that communication with the user should be at the highest possible level, wrapping logic that doesn't know anything about the user at all, and it's clear that we shouldn't be printing here.</p>\n\n<p>As usual, there's an exception (kind of) to the above. <strong>Logging</strong> - methods throughout a system might log messages to make a record of what has happened. However, this is generally done via a <code>Logger</code> from a logging framework, not using System.out().</p>\n\n<pre><code> return Integer.valueOf(scanner.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Not a valid number.\");\n }\n }\n }\n}\n</code></pre>\n\n<p><strong>Overall:</strong>\nYour code style is good, and overall naming and conventions are clean. There are a couple spots where small changes could be cleaner, but your code is in general nice to read.</p>\n\n<p>You've obviously incorporated feedback from your last review, and that's great. A lot of my suggestions here are less \"you did something wrong\" and more \"here's a better way you might not know about\". Nice job!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T01:34:46.737",
"Id": "226881",
"ParentId": "226780",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226881",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:51:40.743",
"Id": "226780",
"Score": "2",
"Tags": [
"java",
"beginner",
"game"
],
"Title": "Lottery Game in Java"
}
|
226780
|
<h2>Challenge</h2>
<p>Link on geeksforgeeks: <a href="https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1" rel="nofollow noreferrer">Binary Tree to DLL</a></p>
<blockquote>
<p>Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL)
In-Place. The left and right pointers in nodes are to be used as
previous and next pointers respectively in converted DLL. The order of
nodes in DLL must be same as Inorder of the given Binary Tree. The
first node of Inorder traversal (left most node in BT) must be head
node of the DLL.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/WjqXb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WjqXb.png" alt="Visualisation"></a></p>
<blockquote>
<p>Your Task:</p>
<p>You don't have to take input. Complete the function <code>bToDLL()</code> that
takes node and head as parameter. The driver code prints the DLL both
ways.</p>
</blockquote>
<p>The following code is given. Class <code>Node</code> may not be changed. Method <code>bToDLL</code> must be implemented, but its signature may not be changed.</p>
<pre><code>class Node
{
Node left, right;
int data;
Node(int d)
{
data = d;
left = right = null;
}
}
// This function should convert a given Binary tree to Doubly Linked List
class GfG
{
Node head;
Node bToDLL(Node root)
{
// TODO .. convert tree and store the result as head
}
}
</code></pre>
<hr>
<h2>Solution</h2>
<p>As pointed out in the comments, a solution is required to be in-place. This is what I came up with. Any type of feedback is invited.</p>
<pre><code>class GfG
{
Node head;
Node bToDLL(Node root)
{
head = first(reduce(root));
return head;
}
void append(final Node source, final Node node) {
source.right = node;
node.left = source;
}
Node reduce(final Node node) {
if (node == null) return node;
Node prev = reduce(node.left);
Node next = reduce(node.right);
if (prev != null) append(last(prev), node);
if (next != null) append(node, first(next));
return node;
}
Node first(Node node) {
while (node.left != null) node = node.left;
return node;
}
Node last(Node node) {
while (node.right != null) node = node.right;
return node;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T16:02:25.530",
"Id": "440994",
"Score": "2",
"body": "It looks to me like you're creating a new tree, but the challenge says `In-Place`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T16:20:59.600",
"Id": "440995",
"Score": "0",
"body": "@tinstaafl If I take a look at the 'spoiler', they are doing the same. https://www.geeksforgeeks.org/in-place-convert-a-given-binary-tree-to-doubly-linked-list/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T16:42:18.530",
"Id": "440997",
"Score": "0",
"body": "\"The problem here is simpler as we don’t need to create circular DLL, but a simple DLL.\" That's in the spoiler. Do you want to write code that fits the spec of the original description or that fits the provided spoiler? There appear to be differences between the two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T16:45:31.617",
"Id": "440998",
"Score": "1",
"body": "@Mast In case of discrepancy, the original spec. Whether the algorithm is circular or not doesn't matter, as long I don't change the class definitions and the outcome matches. I do notice now that the picture states 'In-Place' and I'm not adhering to that requirement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T18:29:17.890",
"Id": "441009",
"Score": "0",
"body": "Because of recursion it still doesn't qualify as in-place. What they want to see is a variation on a Morris traversal theme."
}
] |
[
{
"body": "<p>Algorithm: because of the recursion, it still doesn't qualify as in-place. Consider a variation on a Morris traversal theme.</p>\n\n<hr>\n\n<p>The calls to <code>first()</code> and <code>last()</code> are detrimental to the performance. Meanwhile, the callee already computed them. Consider returning a (fake) node pointing the beginning and the end of the flattened subtree, along the lines</p>\n\n<pre><code> left = flatten(root.left);\n right = flatten(root.right);\n\n left.right.next = root;\n root.left = left.right;\n\n right.left.left = root;\n root.right = right.left;\n\n return Node(left.left, right.right);\n</code></pre>\n\n<p>There is only <span class=\"math-container\">\\$O(h)\\$</span> <code>Nodes</code> to exist at any given moment, so the space complexity is not compromised.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T18:50:26.870",
"Id": "441011",
"Score": "2",
"body": "My initial solution used circular linked list to avoid that _first_ and _last_ overhead, but this would work as well. I did not know about the Morris traversal theme, I learn every day."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T18:47:41.903",
"Id": "226788",
"ParentId": "226781",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226788",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T14:56:35.330",
"Id": "226781",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"linked-list",
"tree",
"converting"
],
"Title": "Convert a Binary Tree to Doubly Linked List"
}
|
226781
|
<p>I have found that there is a distinct lack of an RPN calculator available to me, so I decided to make my own. I am still adding new functions to it, but as of now, I would like to refactor my code.</p>
<h1>Main of JavaRPN</h1>
<p>Because this is a small problem, and I haven't made a GUI for it, I only use one class.</p>
<pre class="lang-java prettyprint-override"><code>package owl;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Stack<Double> stack = new Stack<Double>();
System.out.println("JavaRPN: Input numbers and operands separated by newline or space");
DecimalFormat df = new DecimalFormat("#,###.#########");
while (true) {
String input = reader.readLine();
String[] inputs = input.split(" ");
for (int i = 0; i < inputs.length; i++) {
if (isNumber(inputs[i])) {
stack.push(Double.parseDouble(inputs[i]));
continue;
}
if (inputs[i].equals("e") || inputs[i].equals("p") || inputs[i].equals("c")) {
commands(inputs[i], stack, df);
} else if (inputs[i].equals("sq") || inputs[i].equals("sin") || inputs[i].equals("cos")
|| inputs[i].equals("tan") || inputs[i].equals("asin") || inputs[i].equals("acos")
|| inputs[i].equals("atan")) {
function(inputs[i], stack);
} else if (inputs[i].equals("+") || inputs[i].equals("-") || inputs[i].equals("*")
|| inputs[i].equals("/") || inputs[i].equals("^")) {
operator(stack, inputs[i]);
} else {
System.out.println("ERROR: Invalid input");
}
}
}
} catch (
Exception e) {
e.printStackTrace();
}
}
private static void commands(String input, Stack<Double> stack, DecimalFormat df) {
switch (input) {
case "e":
System.exit(0);
;
break;
case "p":
if (stack.size() > 0) {
System.out.println(df.format(stack.peek()));
break;
} else {
System.out.println("ERROR: All Stacks Empty");
break;
}
case "c":
stack.clear();
break;
}
}
private static void function(String string, Stack<Double> stack) {
if (stack.size() > 0) {
double num = stack.pop();
switch (string) {
case "sq":
stack.push(num * num);
break;
case "sin":
stack.push(Math.sin(Math.toRadians(num)));
break;
case "cos":
stack.push(Math.cos(Math.toRadians(num)));
break;
case "tan":
stack.push(Math.tan(Math.toRadians(num)));
break;
case "asin":
stack.push(Math.asin(Math.toRadians(num)));
break;
case "acos":
stack.push(Math.acos(Math.toRadians(num)));
break;
case "atan":
stack.push(Math.atan(Math.toRadians(num)));
break;
}
}
}
private static void operator(Stack<Double> stack, String input) {
if (stack.size() > 1) {
double num2 = stack.pop();
double num1 = stack.pop();
switch (input) {
case "+":
stack.push(num1 + num2);
break;
case "-":
stack.push(num1 - num2);
break;
case "*":
stack.push(num1 * num2);
break;
case "/":
stack.push(num1 / num2);
break;
case "^":
stack.push(Math.pow(num1, num2));
break;
}
} else {
System.out.println("ERROR: Can't operate on an empty stack");
}
}
private static boolean isNumber(String input) {
try {
Double.parseDouble(input);
return true;
} catch (Exception e) {
return false;
}
}
}
</code></pre>
<p>Anyone familiar with RPN calculators and the UNIX system is probably familiar with the built in dc calculator. The calculator parses input very similar to that old program, but has support for decimals unlike the old one (or at least I couldn't find a way to use decimals in it).</p>
<p>I am aware theat I am clearly being redundant on the line where the code checks the input before executing a method, which checks for the same exact method. I attempted to refactor that before, but I couldn't figure out for the life of my how to do it more efficiently without breaking my current code.</p>
<p>I frequently update this project on my github: <a href="https://github.com/ViceroyFaust/JavaRPN/tree/Refactoring" rel="nofollow noreferrer">https://github.com/ViceroyFaust/JavaRPN/tree/Refactoring</a>
^^^
I have made updates, please tell me whether I've improved or made the problem worse ^_^</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T17:34:54.347",
"Id": "441003",
"Score": "0",
"body": "Just a suggestion: instead of doing `inputs[i].equals(...)` a bunch of times, try `Arrays.asList(\"e\", \"p\", \"c\").contains(inputs[i])`. It basically just initialises a new list, then checks if it contains the string using the `contains` method, which is only available in lists (hence why we have to use `asList` instead of `String[]`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T17:39:16.783",
"Id": "441004",
"Score": "0",
"body": "@GezaKerecsenyi That makes things much simpler. But, does it theoretically hinder or increase the effiency of the program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T17:40:04.757",
"Id": "441005",
"Score": "0",
"body": "Also, line 49 is just an unnecessary semicolon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T17:41:37.980",
"Id": "441006",
"Score": "0",
"body": "Regarding your comment, no, it shouldn't. While I've not tested it (and I'm also a beginner to Java), they both stop as soon as they detect something. The only thing that could possibly be slower is initialising the array, but I'm fairly certain it's negligible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T18:00:38.253",
"Id": "441007",
"Score": "0",
"body": "@GezaKerecsenyi That'll be slower than necessary as `contains` will need to do a linear lookup of the list. A set or map, as my answer shows, would be much more performant. Whether or not that performance difference is important though is another story."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T11:40:25.993",
"Id": "441128",
"Score": "2",
"body": "In fact, for a very small number of elements, linear lookup can be faster than the overhead of a hash calculation and a set lookup. But whichever is faster is of no concern as long as we are looking at sub-millisecond optimizations in relation to direct user input. And at the OP: please don't concern yourself with speed (yet). Learn how to write well-structured and maintainable software which is fun to work with first. (You have come to the right place for that ;-))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:00:04.733",
"Id": "441350",
"Score": "0",
"body": "@mtj Alright, I will keep that in mind. I am just a little overwhelmed with so many new functions and concepts introduced to me. But, there is no way to learn these things without experience, so I have to try!"
}
] |
[
{
"body": "<p>In those lines doing equality checks, you write <code>inputs[i]</code> <em>repeatedly</em>. This has two main problems:</p>\n\n<ul>\n<li>It's likely bulkier than necessary</li>\n<li>If you ever need to change from <code>inputs[i]</code> to something else, you're needing to change it roughly 17 places! That's not ideal.</li>\n</ul>\n\n<p>You can fix at least the second problem by just creating an intermediate variable:</p>\n\n<pre><code>for (int i = 0; i < inputs.length; i++) {\n String curInput = inputs[i]; // Create an intermediate\n\n if (isNumber(curInput)) { // Then use it everywhere\n stack.push(Double.parseDouble(curInput));\n continue;\n }\n if (curInput.equals(\"e\") || curInput.equals(\"p\") || curInput.equals(\"c\")) {\n . . . \n</code></pre>\n\n<p>Now, if you need to change what defines the current input, you only need to make the change in one place instead of 10+ places. This doesn't really help bulk though as <code>curInput</code> is only one character shorter. It can certainly help sometimes though.</p>\n\n<p>The main problem with that whole bit though is you're writing <code>.equals(. . .)</code> all over the place. Whenever you need to check one variable against several inputs, consider using a <code>Set</code> (like a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html\" rel=\"nofollow noreferrer\"><code>HashSet</code></a>):</p>\n\n<pre><code>// Create a set containing the input to check against.\n// The \"asList\" part is just a shortcut so you don't need to call \"add\" a whole bunch of times\nSet<String> functionInputs = new HashSet<>(Arrays.asList(\"sq\", \"sin\", \"cos\", \"tan\", \"asin\", \"acos\", \"atan\"));\n\n. . .\n\n} else if (functionInputs.contains(curInput)) { // Now it's much shorter and cleaner\n function(inputs[i], stack);\n</code></pre>\n\n<p>Then the same can be done for the other types of checks. Create a set holding all the different types to check against, then use <code>contains</code> to check if the input is in that set.</p>\n\n<p>For an explanation of the <code>asList</code> shortcut I'm using, see <a href=\"https://stackoverflow.com/questions/2041778/how-to-initialize-hashset-values-by-construction\">here</a>.</p>\n\n<hr>\n\n<pre><code>} catch (\n\nException e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>I don't like a couple things here:</p>\n\n<ul>\n<li>You're using odd formatting. I don't see why this should be split over a few lines.</li>\n<li><p>You should <em>not</em> be blindly catching <code>Exception</code>. You're printing the stack trace when an error has occurred, so you aren't silencing helpful errors, but you are potentially catching errors you shouldn't be. It seems like your intent there is to catch a <code>NumberFormatException</code> thrown by <code>parseDouble</code>. If that's the case, catch that specifically:</p>\n\n<pre><code>} catch (NumberFormatException e) {\n e.printStackTrace();\n}\n</code></pre></li>\n</ul>\n\n<p>I'd still restructure this though. It would probably be a better idea to pre-check and pre-process the input before running through it in the main loop. I'd pre-parse all the inputs in a separate function. That way, you can entirely remove the <code>try</code> from the loop in <code>main</code> and make the code cleaner. <code>main</code> is huge and is doing a lot. I would try to move a lot of that functionality out into separate, smaller functions. That will make each piece of code much clearer.</p>\n\n<hr>\n\n<p>Back onto the topic of duplication, look at this code and think about if it has unnecessary duplication:</p>\n\n<pre><code>double num = stack.pop();\nswitch (string) {\ncase \"sq\":\n stack.push(num * num);\n break;\ncase \"sin\":\n stack.push(Math.sin(Math.toRadians(num)));\n break;\ncase \"cos\":\n stack.push(Math.cos(Math.toRadians(num)));\n break;\ncase \"tan\":\n stack.push(Math.tan(Math.toRadians(num)));\n break;\ncase \"asin\":\n stack.push(Math.asin(Math.toRadians(num)));\n break;\ncase \"acos\":\n stack.push(Math.acos(Math.toRadians(num)));\n break;\ncase \"atan\":\n stack.push(Math.atan(Math.toRadians(num)));\n break;\n}\n</code></pre>\n\n<p>How many times do you call <code>toRadians</code> in that code? What if you add more functions to deal with? Convert the number, then check against that:</p>\n\n<pre><code>double num = stack.pop();\ndouble rads = Math.toRadians(num); // Store radians here\nswitch (string) {\ncase \"sq\":\n stack.push(num * num);\n break;\ncase \"sin\":\n stack.push(Math.sin(rads));\n break;\ncase \"cos\":\n stack.push(Math.cos(rads));\n break;\ncase \"tan\":\n stack.push(Math.tan(rads));\n break;\ncase \"asin\":\n stack.push(Math.asin(rads));\n break;\ncase \"acos\":\n stack.push(Math.acos(rads));\n break;\ncase \"atan\":\n stack.push(Math.atan(rads));\n break;\n}\n</code></pre>\n\n<p>Note how you have <code>stack.push</code> over and over as well. You could get rid of that duplication by calling it after the <code>switch</code>:</p>\n\n<pre><code>double num = stack.pop();\ndouble rads = Math.toRadians(num); // Store radians here\n\nDouble answer = null; // \nswitch (string) {\ncase \"sq\":\n answer = num * num;\n break;\ncase \"sin\":\n answer = Math.sin(rads);\n break;\ncase \"cos\":\n answer = Math.cos(rads);\n break;\ncase \"tan\":\n answer = Math.tan(rads);\n break;\ncase \"asin\":\n answer = Math.asin(rads);\n break;\ncase \"acos\":\n answer = Math.acos(rads);\n break;\ncase \"atan\":\n answer = Math.atan(rads);\n break;\n}\n\nif (answer) {\n stack.push(answer);\n}\n</code></pre>\n\n<p>Now if you ever change how the stack you're using works, you don't need to make multiple changes. This still isn't great though. Now I have <code>answer =</code> duplicated. You could make use of some semi-advanced functional techniques and store the functions in a <code>Map</code>, and dispatch on it:</p>\n\n<pre><code>import java.util.function.DoubleUnaryOperator;\nimport java.util.Map;\nimport java.util.HashMap;\n\nMap<String, DoubleUnaryOperator> nameToFunc = new HashMap<>();\nnameToFunc.put(\"sin\", Math::sin);\nnameToFunc.put(\"cos\", Math::cos);\nnameToFunc.put(\"tan\", Math::tan);\n. . . // And the rest of the mappings\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>private static void function(String string, Stack<Double> stack) {\n if (stack.size() > 0) {\n double num = stack.pop();\n DoubleUnaryOperator f = nameToFunc.get(string); // Get the func\n Double answer = f.applyAsDouble(Math.toRadians(num)); // Will be null if it's a bad string\n\n if (answer != null) {\n stack.push(answer);\n }\n }\n}\n</code></pre>\n\n<p>For simplicity, I ignored the <code>\"sq\"</code> case though. Since it uses non-radian input, it's a special case.</p>\n\n<p>The advantage of using this is, because it uses the same strings as the Set suggestion I made at the top, you can change the definition of <code>functionInputs</code> to be based on <code>nameToFunc</code>:</p>\n\n<pre><code>Set<String> functionInputs = nameToFunc.keySet();\n</code></pre>\n\n<p>Now, if you add more function names to handle, you only need to update <code>nameToFunc</code> and they'll both be updated. You could also just avoid <code>functionInputs</code> altogether and just use <code>nameToFunc</code>. You could change your checks to:</p>\n\n<pre><code>} else if (nameToFunc.get(curInput)) { // \"get\" returns null (falsey) on a bad lookup\n function(inputs[i], stack);\n</code></pre>\n\n<hr>\n\n<p>You write:</p>\n\n<pre><code>if (isNumber(curInput)) {\n stack.push(Double.parseDouble(curInput));\n continue;\n}\n</code></pre>\n\n<p>There's one performance-related issue with this: your <code>isNumber</code> already calls <code>parseDouble</code>. You could avoid this by changing <code>isNumber</code>:</p>\n\n<pre><code>private static Double maybeParse(String input) {\n try {\n return Double.parseDouble(input);\n\n } catch (NumberFormatException e) { // Only catch what you intend on catching! \n return null; // Return null on failure\n }\n}\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>Double maybeN = maybeParse(curInput);\nif (maybeN != null) {\n stack.push(maybeN);\n continue;\n}\n</code></pre>\n\n<p>Instead of returning a <code>null</code> on a bad parse, you could also make use of <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html\" rel=\"nofollow noreferrer\"><code>Optional</code></a> here. What I'm showing in <code>maybeParse</code> is basically the Optional pattern, minus the use of the standard wrapper class. As long as you document that <code>null</code> may be returned, this should be fine. <code>Optional</code> is nice though in that it's self-documenting. </p>\n\n<p>The use of <code>Double</code> will cause a little overhead due to the boxing/unboxing of the <code>double</code>. I expect the cost to be less than it is to parse the string twice though. </p>\n\n<hr>\n\n<p>Hopefully this gives you some good ideas. Good luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:17:32.180",
"Id": "441065",
"Score": "0",
"body": "Instead of defining the functions as DoubleUnaryOperators I would define them as Consumer<Stack<Double>>. This way the function would be responsible for knowing how many parameters it takes and the '+', '-', '*', etc functions could be defined in the same structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T11:07:46.013",
"Id": "441114",
"Score": "0",
"body": "@TorbenPutkonen That's a good point. I'll see if I have time to add something after work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:34:50.783",
"Id": "441360",
"Score": "0",
"body": "I can't actually return a null as a double, what do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T15:22:20.350",
"Id": "441365",
"Score": "0",
"body": "@ViceroyFaust If you're referring to my `maybeParse`, note that the return type is `Double`, not `double`. The first is an object that may contain `null`, the latter is a primitive that can't contain `null`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T18:30:30.530",
"Id": "441411",
"Score": "0",
"body": "@RolandIllig I'm going to rewrite that part. I realize now that I was wrong. I was thinking that `if`s could accept arbitrary types. Been writing too much Python lately. Thanks."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T17:58:35.520",
"Id": "226787",
"ParentId": "226782",
"Score": "5"
}
},
{
"body": "<p>Putting all code into one class makes the program very complicated. Refactor the code into classes where each class performs one task. This is called <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a></p>\n\n<p>The core of the <code>RpnEgine</code> is the following function. I've used Deque as it performs better than the synchronized Stack.</p>\n\n<pre><code>public void process(String ... input) {\n for (String s: input) {\n final Consumer<Deque<Double>> func = FUNCTIONS.get(s);\n if (func != null) {\n func.accept(stack);\n } else {\n stack.push(Double.valueOf(s));\n }\n }\n}\n</code></pre>\n\n<p>The mathematical operations and commands can then be defined as lambdas or standalone classes. These are a bit ugly, as the operator order is reversed hen read from the stack. You'll notice this code repeats the pushing and popping a lot, so it might be a good idea to refactor them to a common class that check stack size, pops the operands, delegates them to a <code>BiFunction</code> and pushes the result.</p>\n\n<p>It also introduces great flexibility, as implementing a function that calculates the sum of whatever is in the stack becomes trivial.</p>\n\n<pre><code>static {\n FUNCTIONS.put(\"+\", (d) -> d.push(d.pop() + d.pop()));\n FUNCTIONS.put(\"-\", (d) -> d.push((- d.pop()) + d.pop()));\n FUNCTIONS.put(\"/\", (d) -> d.push(1.0 / (d.pop() / d.pop())));\n FUNCTIONS.put(\"sum\", new Sum());\n}\n</code></pre>\n\n<p>Do not put the input parsing to the same class. Create a class named <code>RpnCli</code> that reads input and passes it to the <code>RpnEngine</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T13:43:20.833",
"Id": "441340",
"Score": "1",
"body": "What does the Deque do which Stack doesn't? Also, I am not sure how to use BiFunction, so I am kind of confused what is happening in that static {...} method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:47:16.870",
"Id": "441362",
"Score": "1",
"body": "And I am just in general confused where did you get Consumer, FUNCTIONs and all that from..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T18:19:20.877",
"Id": "441404",
"Score": "0",
"body": "The static block initializes a HashMap<String, Consumer<Deque<Double>>> using lambda expressions and one plain old Java object. If you're just learning Java, lambdas are probably not the first things on the curriculum."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:43:10.693",
"Id": "226826",
"ParentId": "226782",
"Score": "4"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>import java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.util.Map;\nimport java.util.Stack;\nimport java.util.function.DoubleBinaryOperator;\nimport java.util.function.DoubleUnaryOperator;\n\nimport static java.util.Map.entry;\n\npublic class Rpn {\n private static final Map<String, DoubleUnaryOperator> FUNCTIONS = Map.ofEntries(\n entry("sin", Math::sin),\n entry("cos", Math::cos),\n entry("tan", Math::tan)\n );\n\n private static final Map<String, DoubleBinaryOperator> OPERATORS = Map.ofEntries(\n entry("+", (n1, n2) -> n1 + n2),\n entry("-", (n1, n2) -> n1 - n2),\n entry("*", (n1, n2) -> n1 * n2),\n entry("/", (n1, n2) -> n1 / n2),\n entry("^", Math::pow)\n );\n\n public static void main(String[] args) throws Exception {\n System.out.println("Rpn: Reverse Polish Notation Calculator");\n\n final var reader = new BufferedReader(new InputStreamReader(System.in));\n final var stack = new Stack<Double>();\n var valid = true;\n String line;\n\n while (valid && ((line = reader.readLine()) != null)) {\n for (final var token : line.split("\\\\s+")) {\n valid =\n applyNumber(token, stack) ||\n applyFunction(token, stack) ||\n applyOperator(token, stack);\n }\n }\n\n reader.close();\n }\n\n private static boolean applyFunction(final String token, final Stack<Double> stack) {\n if (!stack.isEmpty()) {\n final var f = FUNCTIONS.get(token);\n\n if (f != null) {\n stack.push(f.applyAsDouble(Math.toRadians(stack.pop())));\n\n return true;\n }\n }\n\n return false;\n }\n\n private static boolean applyOperator(final String token, final Stack<Double> stack) {\n if (stack.size() > 1) {\n final var op = OPERATORS.get(token);\n\n if (op != null) {\n final var num2 = stack.pop();\n final var num1 = stack.pop();\n stack.push(op.applyAsDouble(num1, num2));\n\n return true;\n }\n }\n\n return false;\n }\n\n private static boolean applyNumber(final String token, final Stack<Double> stack) {\n try {\n stack.push(Double.parseDouble(token));\n return true;\n }\n catch (final Exception e) {\n return false;\n }\n }\n}\n</code></pre>\n<p>The "commands" are removed for brevity, but the following concepts generally apply:</p>\n<ul>\n<li>Map the tokens to functions, operators, and commands (not shown).</li>\n<li>Group logical code snippets together (i.e., don't split variable declarations with a <code>println</code>).</li>\n<li>Change method signatures to make them as similar as possible: same arguments, same argument order, and same return types.</li>\n<li>Avoid <code>while(true)</code> by declaring the termination conditions directly.</li>\n<li>Be sure to close any opened streams, preferably using try-with-resources (not shown).</li>\n<li>Consider revising the regular expression to be a little more permissive (e.g., perhaps <code>\\\\s+</code> to allow splitting across multiple spaces)?</li>\n<li>Validate the data by adding <code>null</code> checks where the API calls can return <code>null</code>.</li>\n<li>Declare variables as <code>final</code> wherever possible.</li>\n<li>Make use of immutable data structures when feasible (e.g., <code>FUNCTIONS</code> and <code>OPERATORS</code>).</li>\n<li>Consider using <code>var</code> when the type of variable is obvious.</li>\n<li>Try to name variable using standard nomenclature (e.g., parsing text often is understood to involve "tokens"/"lexemes" rather than "strings" or "names" or "inputs").</li>\n</ul>\n<p>Lastly, use a modern IDE for development that will produce warnings that show code improvements. For example, IntelliJ will show that <code>stack.size() != 0</code> is equivalent to <code>!stack.isEmpty()</code>, as well as <code>if</code> statements that can be a <code>switch</code>, and many more simplifications.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-12-02T20:01:20.623",
"Id": "270629",
"ParentId": "226782",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "226787",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T16:03:27.047",
"Id": "226782",
"Score": "8",
"Tags": [
"java",
"beginner",
"calculator",
"math-expression-eval"
],
"Title": "JavaRPN calculator"
}
|
226782
|
<p><strong>Part 2: Error Handling</strong> (and anything else that can be improved)</p>
<p><em>(<a href="https://codereview.stackexchange.com/questions/226466/work-order-spatial-query-part-1">Part 1</a> focused on general cleanup.)</em></p>
<hr>
<p>I received this comment in an <a href="https://stackoverflow.com/questions/57617494/jython-parse-json-object-to-get-value-object-has-array">unrelated post</a> (thanks @Milton):</p>
<blockquote>
<p>...Since it is obvious you are using a GIS endpoint, I would note that
<strong>a lot can go wrong with your script</strong> if the GIS were to go down, move
url, request gets lost, etc. I discourage url links to GIS data...</p>
</blockquote>
<p>I think this concern is legitimate. If this script produces an error, then the user will not be able to save their work orders in the work order management system (<a href="https://www.ibm.com/products/maximo" rel="nofollow noreferrer">Maximo</a>). This would render the entire system unusable until the problem is fixed.</p>
<p>To address this concern, I've put a generic <code>try, except</code> error handler in the main part of the script. <strong>Is this good enough, or should it be improved?</strong></p>
<hr>
<p><strong>The Script:</strong></p>
<pre><code>#What the script does:
# 1. Takes the X&Y coordinates of a work order in Maximo
# 2. Generates a URL from the coordinates
# 3. Executes the URL via a separate script/library (LIB_HTTPCLIENT)
# 4. Performs a spatial query in an ESRI REST feature service (a separate GIS system)
# 5. JSON text is returned to Maximo with the attributes of the zone that the work
# order intersected
# 6. The zone number is parsed from the JSON text via a separate script/library
# (LIB_PARSE_JSON)
# 7. Inserts the zone number into the work order record
#
#Notes about libraries:
# - Unfortunately, I'm unable to add external Python libraries (like urllib or
# urlparse) to my Maximo/Jython implementation.
# - Furthermore, some libraries (exampple: JSON) that are normally included in Python
# and Jython have been excluded from my Maximo implementation. I don't have control
# over this.
# - Instead, if there is functionality missing from my Jython implementation, I need
# to use Java classes to fill in the gap:
# https://www.ibm.com/support/knowledgecenter/ja/SSEUEX_2.0.2/com.ibm.javaeuc.doc/com/ibm/json/java/package-summary.html
#
#Notes about creating the URL:
# - Previous code reviewers have strongly suggested "...splitting the URL creation
# into different variables and adding a looping function that adds query parameters
# to the URL."
# - I've tried doing this, but I found that it made the url parts harder for me to
# manage, not easier. Maybe I'm nuts, but I've tried it, and figured it was overly
# complicated, so I think we can skip this idea for now. Thanks all the same.
from psdi.mbo import MboConstants
from java.util import HashMap
field_to_update = "ZONE"
def get_coords():
"""
Get the y and x coordinates(UTM projection) from the WOSERVICEADDRESS table
via the SERVICEADDRESS system relationship.
The datatype of the LatitdeY and LongitudeX fields is decimal.
"""
laty = mbo.getDouble("SERVICEADDRESS.LatitudeY")
longx = mbo.getDouble("SERVICEADDRESS.LongitudeX")
return laty, longx
def is_latlong_valid(laty, longx):
#Verify if the numbers are legitimate UTM coordinates
return (4000000 <= laty <= 5000000 and
600000 <= longx <= 700000)
def make_url(laty, longx):
"""
Assemble the URL (including the longx and the laty).
Note: The coordinates are flipped in the url.
Consider replacing the field wildcard(*) with the specific field name (zone)
"""
url="http://example.com/arcgis/rest/services/Something/Zones/MapServer/15/query?geometry={0}%2C{1}&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&outFields=*&returnGeometry=false&f=pjson".format(str(longx),str(laty))
return url
def fetch_zone(url):
# Get the JSON text from the feature service (the JSON text contains the zone value).
ctx = HashMap()
ctx.put("url", url)
service.invokeScript("LIB_HTTPCLIENT", ctx)
json_text = str(ctx.get("response"))
# Parse the zone value from the JSON text
ctx = HashMap()
ctx.put("json_text", json_text)
service.invokeScript("LIB_PARSE_JSON", ctx)
parsed_val = str(ctx.get("parsed_val"))
return parsed_val
#Is this sort of generic error checking acceptable (try/except)?
try:
laty, longx = get_coords()
if not is_latlong_valid(laty, longx):
service.log('Invalid coordinates')
else:
url = make_url(laty, longx)
zone = fetch_zone(url)
#Insert the zone value into the zone field in the work order
mbo.setValue(field_to_update, zone, MboConstants.NOACCESSCHECK)
except:
"""
If the script fails, then set the field vaule to null.
Reason: If the work order coordinates have changed (thereby triggering this script),
then setting the zone's field value to null is better than leaving it as the wrong
zone number (if the coordinates of the work order changed, that means
that the zone number likely changed too).
Furthermore, if there is an error in the script, then an error message will pop up
and prevent users from creating/saving work orders.
We don't want that! (error messages would render the system unusable until fixed)
So, I figure, I'll set the field value to null if there is an error.
"""
mbo.setValue(field_to_update, "", MboConstants.NOACCESSCHECK) #Should I
# set the field value to "" or to None?
service.log("An exception occurred")
</code></pre>
<p><strong>LIB_HTTPCLIENT:</strong></p>
<pre><code>from psdi.iface.router import HTTPHandler
from java.util import HashMap
from java.lang import String
handler = HTTPHandler()
map = HashMap()
map.put("URL", url)
map.put("HTTPMETHOD", "GET")
responseBytes = handler.invoke(map, None)
response = String(responseBytes, "utf-8")
</code></pre>
<p><strong>LIB_PARSE_JSON:</strong></p>
<pre><code>#Is there a way to NOT hardcode the field name (ZONE)?
from com.ibm.json.java import JSONObject
obj = JSONObject.parse(json_text)
#The "features" element of the JSON object has an array. Get the first feature in the
#array by specifying [0].
parsed_val = obj.get("features")[0].get("attributes").get("ZONE")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T12:04:29.417",
"Id": "441133",
"Score": "1",
"body": "If you use the Contact link at the bottom of the page, staff could delete/edit the bad versions of the code from the edit history. Please remember to ask them to fix both question and answer if you do that. It's the same process as would be used for login credentials, although you might want to select Other instead."
}
] |
[
{
"body": "<p>The code has certainly improved since I last saw it. There's only one thing that stands out to me, and it's the URL construction. The 'simple' way to make it more legible is to split it up onto multiple lines using implicit concatenation:</p>\n\n<pre><code>url = (\n \"http://example.com\"\n \"/arcgis/rest/services/Something\"\n \"/Zones/MapServer/15/query?\"\n \"geometry={0}%2C{1}&\"\n \"geometryType=esriGeometryPoint&\"\n \"spatialRel=esriSpatialRelIntersects&\"\n \"outFields=*&\"\n \"returnGeometry=false&\"\n \"f=pjson\"\n).format(longx, laty)\n</code></pre>\n\n<p>Note that the <code>str</code> calls have also been removed; the <code>format</code> call does that for you.</p>\n\n<p>Also, and this is domain-specific so I can't give any specific advice, but: if you're able to narrow <code>outFields</code> so that you get only the fields back that you need from the server, that will be more efficient than <code>*</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T02:28:22.993",
"Id": "441035",
"Score": "0",
"body": "Thank you! Will implement your suggestions. Any thoughts on NOT hard coding the field name (ZONE) in the LIB_PARSE_JSON script?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T03:38:15.013",
"Id": "441037",
"Score": "1",
"body": "Yes. The invoke script mechanism is kind of goofy. Your two libraries are so small that they deserve to be regular Python functions inside of your main script, if that's possible. Then you can accept the field name as a parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T20:31:43.203",
"Id": "441231",
"Score": "1",
"body": "The DRY principle suggests that keeping the libraries as libraries is a good idea, as otherwise the code will have to be repeated in any other scripts that need to make similar calls. Really, in Maximo terms, library scripts should be thought of as global functions -- admittedly with a clunky invocation syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-04T12:04:24.067",
"Id": "442804",
"Score": "1",
"body": "For what it's worth: the latest version on the code is here: https://stackoverflow.com/a/57730617/10936066"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T02:19:07.313",
"Id": "226806",
"ParentId": "226786",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226806",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T17:31:58.217",
"Id": "226786",
"Score": "1",
"Tags": [
"python",
"json",
"geospatial",
"jython"
],
"Title": "Work order spatial query (Part 2)"
}
|
226786
|
<p><strong>Bit Swapping</strong></p>
<p>You’re given two binary matrices, m rows and n columns. Both matrices have the same size i.e. same number of rows and same number of columns. Each cell is a bit either 0 or 1. You need to find the minimum number of swaps are required in the first matrix in order for it’s arrangement to match that of the second. If the matched arrangement can never be achieved output -1.</p>
<p><strong>Input Format</strong></p>
<p>The first line contains a single integer t, denoting the number of test cases.<br>
The first line of each test case contains two space separated integers m and n denoting the number of rows and number of columns. Next m lines each contains n elements of the first matrix. Next m lines each contains n elements of the second matrix.</p>
<p><strong>Output Format</strong></p>
<p>For each test case print the minimum swaps.</p>
<p><strong>Constraints</strong></p>
<p>1 <= t <= 1000</p>
<p>1 <= m <= 100</p>
<p>1 <= n <= 100</p>
<p><strong>Sample Input</strong></p>
<pre><code>6
2 2
00
11
01
10
2 2
00
11
00
11
2 2
00
11
01
00
1 7
0011011
0101101
1 1
0
1
1 1
0
0
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>1
0
-1
2
-1
0
</code></pre>
<p><strong>Code:</strong> </p>
<pre><code>for each in range(int(input())): #t test cases
m = int(input().split(' ')[0]) # m and n dimensions out of which im using m only
a1 = []
a2 = []
for i in range(m): # first matrix input
a1 += [int(k) for j in input() for k in j]
for i in range(m): # second matrix input
a2 += [int(k) for j in input() for k in j]
if a1.count(1) != a2.count(1): # counting if count of 1 and 0 are same in both matrix
print(-1) # if not then print -1
else:
c = 0
for j in range(len(a1)):
if a1[j] != a2[j]:
c += 1
print(c//2) # if yes then print minimum number of swaps
</code></pre>
<p>This is a Code Golf contest where shorter source awards higher score. Score is calculated by the following formula </p>
<pre><code>(1 - s/10000)*100
</code></pre>
<p>where s is the number of characters in your source. </p>
<p>For example, if a correct source uses 1000 characters, a score of (1 - 1000/10000)*100 i.e. 90 will be awarded. The source limit is 10000 characters.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T20:31:51.897",
"Id": "441016",
"Score": "1",
"body": "Is this code working as intended? Could you provide a unit test?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T21:24:43.693",
"Id": "441017",
"Score": "0",
"body": "Yes, this code is working and have updated test case @dfhwze"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T00:30:36.037",
"Id": "441026",
"Score": "0",
"body": "What URL did you pull this problem from? In several regards the question as stated is unclear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T06:30:24.997",
"Id": "441277",
"Score": "0",
"body": "Is this a programing-challange?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:15:31.780",
"Id": "441436",
"Score": "0",
"body": "yes, i have updated the question as well scoring method"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T19:09:39.340",
"Id": "226789",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Minimum number of swaps for two 2D arrays to make the first one identical to other"
}
|
226789
|
<p>I am new to Python (it's my first language), been coding for a couple of weeks now.</p>
<p>I have already made a couple of simple scripts to download and manipulate some financial data, but lately I thought about making a simple hangman game. I tested it thoroughly and it seems to work just fine.</p>
<p>However, as I do not yet know a lot about the best practices of writing an optimal code, could somebody please review the attached code and give me some feedback about how could I improve it? </p>
<pre><code>#import packages
from random_words import RandomWords
from colorama import Fore, Back, Style
rw = RandomWords()
import os
import time
#list of 7 possible states of the hangman
hangman_pics = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''']
#define function to clear the screen
def clear_screen():
return os.system('cls')
#game on/off switch
game_on = False
#opening statement
os.system('cls')
print ('Welcome to the Hangman!\n')
#ask player to start the game
while game_on is False:
game_start = input ('Would you like to start a new game? [y/n]... ').upper()
if game_start == 'Y':
game_on = True
elif game_start == 'N':
game_on = False
clear_screen()
else:
clear_screen()
print ("Please input [y] or [n]")
clear_screen()
while game_on is True:
#generate a random word to guess and transform to a list
word_to_guess = rw.random_word()
word_to_guess_list = list(word_to_guess)
length_of_word_to_guess = len((word_to_guess_list))
#generate a placeholder list for tried but wrong guesses
tried_but_wrong = []
#create a representation of word_to_guess_list with hidden spaces
hidden_word = ('_')*length_of_word_to_guess
hidden_word_list = list(hidden_word)
#info about generated word to guess
print ('I have just generated a random word for you to guess!')
print (f'\nThe word has {length_of_word_to_guess} letters.')
#initialize the number of attempts left
attempts_left = 6
hangman_state = 0
print (f'\nYou have {attempts_left} attempts left.')
#start the while loop for the game's logic
while attempts_left>0 or hidden_word_list != word_to_guess_list:
#initialize the guessed letter
guess = ('')
#print the current state of the hangman
print (hangman_pics[hangman_state])
#print the letter already used an not in the word to guess
if tried_but_wrong == []:
pass
else:
print(f'\nTip: you have alread tried these letters: {tried_but_wrong}\n')
#while loop for guessing a letter
while len(guess) != 1 or type (guess) != str:
print (f'This is the word you are trying to guess:'+'\n'*2+f'{hidden_word_list}')
guess = input ('\nPlease select a letter you think is in the hidden word... ')
clear_screen()
#check if guessed letter is in the word to guess and not already guessed
if guess in word_to_guess_list and guess not in hidden_word_list:
print (f'''Great! You guessed correctly, "{guess}" is in the word you are trying to guess.''')
#check the indices of guessed letter(s)
print (f'You have {attempts_left} attempts left.')
indices_of_guessed_letter = [i for i, x in enumerate(word_to_guess_list) if x == guess]
#replace blank spots in hidden_word_list with guessed letter(s)
for indices in indices_of_guessed_letter:
hidden_word_list [indices] = guess
#inform the player that they already guessed the selected letter
elif guess in hidden_word_list:
print ('Woops! Looks like you have already guessed this one! Please try again!')
#inform the player that they already tried that letter and it's not in the word to guess
elif guess in tried_but_wrong:
print (f'There is no "{guess}" in the word you are trying to guess, but you have already tried that one.')
#else: inform the player that they guessed wrong
else:
print (f'There is no "{guess}" in the word you are trying to guess.')
#add the guessed and wrong letter to a list of already tried guesses
tried_but_wrong.append(guess)
#reduce the number of attempts left
attempts_left -= 1
#progress the hangman state
hangman_state += 1
#print the info about the number of attempts left
print (f'You have {attempts_left} attempts left.')
#check for win or loss
#check for win
if word_to_guess_list == hidden_word_list:
time.sleep(2)
clear_screen()
print (f'You correctly guessed the word, which is ' + Fore.GREEN + f'"{word_to_guess}"'+ Style.RESET_ALL+'.')
print (f'You had {attempts_left} attempts left.')
break
#check for loss
if attempts_left == 0:
time.sleep(2)
clear_screen()
print
print (f"You lost. The word you were trying to guess was " + Fore.RED+ f'"{word_to_guess}"' + Style.RESET_ALL + '.')
print ('\nUnfortunately, you are dead.')
print (hangman_pics[hangman_state])
break
#ask if player wants to replay
restart = False
while restart is False:
game_restart = input ('\nWould you like to start a new game? [y/n]... ').upper()
if game_restart == 'Y':
restart = True
clear_screen()
game_on = True
elif game_restart == 'N':
restart = True
clear_screen()
print ("Thank you for playing!")
time.sleep(3)
game_on = False
clear_screen()
else:
clear_screen()
print ("Please input [y] or [n]")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T10:42:45.020",
"Id": "441112",
"Score": "3",
"body": "Nice pictures by the way!"
}
] |
[
{
"body": "<p>You define a <code>clear_screen</code> function, but then at the top you have</p>\n<pre><code>#opening statement\nos.system('cls') # Here\nprint ('Welcome to the Hangman!\\n')\n</code></pre>\n<p>You might as well use the function there.</p>\n<hr />\n<p>A little further down you have:</p>\n<pre><code>while game_on is True:\n</code></pre>\n<p>The <code>is</code> check is only necessary if <code>game_on</code> could be some truthy value other than <code>True</code>, and you wanted to check if it was literally only equal to <code>True</code>. <code>game_on</code> will only every have the values <code>True</code> or <code>False</code> though, so you can just write:</p>\n<pre><code>while game_on:\n</code></pre>\n<p>Which reads nicer anyways.</p>\n<hr />\n<p><code>tried_but_wrong</code> is a list, but you're using it to do membership tests when you write</p>\n<pre><code>guess in tried_but_wrong\n</code></pre>\n<p>If you're using <code>in</code> to test for membership like you are here, ideally, the collection shouldn't be a list. <code>x in some_list</code> requires that the entire list is potentially checked, which can be an expensive operation. It would be better if <code>tried_but_wrong</code> was a set, since you don't seem to need the insertion order maintained anyway.</p>\n<pre><code>tried_but_wrong = set() # An empty set. Python doesn't have a literal for an empty set\n. . .\nif not tried_but_wrong: # Empty sets and lists are falsey\n. . .\ntried_but_wrong.add(guess)\n</code></pre>\n<p>Membership lookups on sets are very fast due to how they're implemented. If the purpose of a collection is just to track what you've "seen" already, and you don't care about order, use a set.</p>\n<hr />\n<p>In Python 3, <code>print</code> is a function call, yet you're using "detached braces":</p>\n<pre><code>print ("Please input [y] or [n]")\n</code></pre>\n<p>All this does is momentarily make your code look like Python 2. Since it's an ordinary function call, format it as such and have the braces "attached" to the call:</p>\n<pre><code>print("Please input [y] or [n]")\n</code></pre>\n<p>And the same goes for code like:</p>\n<pre><code>hidden_word_list [indices] = guess\n</code></pre>\n<p><code>[indices]</code> is a part of <code>hidden_word_list</code>. Having the indexing floating there makes it slightly less obvious what's going on. Keep them attached.</p>\n<p>And this isn't just my word. PEP 8, Python's style guide, <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statement\" rel=\"nofollow noreferrer\">explicitly recommends this</a>.</p>\n<p>And on the subject of white-space styling, make sure you have white-space around binary operators. Lines like</p>\n<pre><code>while attempts_left>0 or hidden_word_list != word_to_guess_list:\n</code></pre>\n<p>Are inconsistent and violate the guide. Have space around <code>></code>:</p>\n<pre><code>while attempts_left > 0 or hidden_word_list != word_to_guess_list:\n</code></pre>\n<p>Even if you were fine violating PEP 8, you're inconsistent with how you style things. You space some things out in some places but not others. <strong>Be consistent</strong>. Consistency and proper naming are two very valuable tools that ensure your code is readable.</p>\n<hr />\n<p>A few places, you're putting parenthesis around string literals for some reason:</p>\n<pre><code>hidden_word = ('_')*length_of_word_to_guess\n. . . \nguess = ('')\n</code></pre>\n<p>I'm not sure why though. This momentarily makes it seem like they're tuples. Just use bare strings, and for the first line there, again, put space around <code>*</code>.</p>\n<hr />\n<pre><code>if tried_but_wrong == []:\n pass\nelse:\n print(f'\\nTip: you have alread tried these letters: {tried_but_wrong}\\n')\n</code></pre>\n<p>This has a couple things off; one of which I mentioned earlier:</p>\n<ul>\n<li><p>Empty collections are falsey. It's generally regarded as idiomatic to use <code>if some_coll</code> to test if a collection has elements (or <code>if not some_coll</code> to test if it's empty).</p>\n</li>\n<li><p>You're testing for a condition, then only using the <code>else</code>. Just negate the condition if necessary. Here though, negation isn't even needed:</p>\n<pre><code> if tried_but_wrong:\n print(f'\\nTip: you have already tried these letters: {tried_but_wrong}\\n')\n</code></pre>\n</li>\n</ul>\n<hr />\n<hr />\n<p>There are some things I like though:</p>\n<ul>\n<li><p>You're making good use of f-strings. That certainly makes the string construction neater.</p>\n</li>\n<li><p>You use snake_case and use descriptive names. Both are good practices.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T19:57:34.743",
"Id": "226792",
"ParentId": "226790",
"Score": "30"
}
},
{
"body": "<p>Welcome to code review...</p>\n\n<h1>Import statements</h1>\n\n<blockquote>\n<pre><code>from random_words import RandomWords\nfrom colorama import Fore, Back, Style\n</code></pre>\n</blockquote>\n\n<p>Assuming that someone wants to run your program, how would he run it without having this <code>random_words</code> thing? You should include it with the rest of your code unless it's an official Python module.</p>\n\n<p>Back in the second import statement is not used, should be ommitted/cleaned up.</p>\n\n<h1>Style</h1>\n\n<p>I suggest you check <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP0008</a>, the official Python style guide. </p>\n\n<p>Here are a few comments:</p>\n\n<blockquote>\n<pre><code>#define function to clear the screen\ndef clear_screen():\n return os.system('cls')\n</code></pre>\n</blockquote>\n\n<ul>\n<li><p><strong>Docstrings:</strong> \nPython documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docstring is defined by including a string constant as the first statement in the object's definition. You might write a docstring instead of the comment above the function.</p>\n\n<pre><code>def clear_screen():\n \"\"\"Clear the screen.\"\"\"\n return os.system('cls')\n</code></pre></li>\n<li><p><strong>Comments:</strong> You might want to include comments on a need basis and omit the unnecessary explanations; according to PEP0008 you should use comments sparingly. lots of things are self-explanatory.\nAnd a comment starts with <code># comment</code> not <code>#comment</code>.</p>\n\n<pre><code># import packages\n# define function to clear the screen\n# opening statement\n</code></pre></li>\n<li><p><strong>Blank lines:</strong> (pep008) Extra blank lines may be used #(sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations). </p></li>\n<li><p><strong>Too long lines:</strong> PEP 8 suggests lines should be limited to 79 characters.</p></li>\n<li><pre><code>while game_on is True:\n</code></pre>\n\n<p>can be expressed:</p>\n\n<pre><code>while game_on:\n</code></pre></li>\n<li><p><strong>Missing white space around operators:</strong> 1 space on both sides of binary operators(+ - / * // & | ^ % = > < == !=) except for function default values.</p>\n\n<pre><code>hidden_word = ('_')*length_of_word_to_guess\nprint (f'You correctly guessed the word, which is ' + Fore.GREEN + \nf'\"{word_to_guess}\"'+ Style.RESET_ALL+'.')\n</code></pre></li>\n</ul>\n\n<h1>Bugs</h1>\n\n<pre><code>Tip: you have alread tried these letters: ['7']\n</code></pre>\n\n<p><strong>Invalid input:</strong> no catching of problematic inputs such as numbers (7 in the case above, the program indicates that I already tried 7 before).\nThe same goes for invalid inputs in the first question (do you want to start the game? y/n) - suppose a user entered yes or no instead of n or y or N or Y, then the program should indicate the invalid input or have cases covering such possible occurrences (it's not very unlikely that someone enters yes or no).</p>\n\n<p><strong>Clear screen function</strong> <code>os.system('cls')</code> clears only on Windows systems, <code>os.system('clear')</code> for Unix (including Mac and Linux) systems otherwise are going to throw some error; you should indicate that in the docstring or implement another function to support Unix systems (I have a macbook, so I had to change it to run properly).</p>\n\n<p><strong>Would you like to start a new game?</strong> infinite loop if the answer is no (n) at the very start of the game, so the user is compelled to play; he has no actual choice!</p>\n\n<p><strong>Upper case letters</strong> the program assumes the user will enter only lower case letters.</p>\n\n<blockquote>\n<pre><code>os.system('cls')\nprint ('Welcome to the Hangman!\\n')\n</code></pre>\n</blockquote>\n\n<p>Why use <code>os.system('cls')</code> and you already defined a function to do so? why not ...</p>\n\n<pre><code>clear_screen()\nprint ('Welcome to the Hangman!\\n')\n</code></pre>\n\n<h1>Functions</h1>\n\n<p>A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. You can enclose your code into separate functions that perform different tasks; it's better for readability/modularity and easier to debug/ change (what if you want to change some value that keeps repeating through the code?).</p>\n\n<p>Here's a refactored version of the code:</p>\n\n<p>You will need to download this <a href=\"https://drive.google.com/file/d/1am_sdLI-NCs31G-O7b-7pJKx9t5QIGqs/view?usp=sharing\" rel=\"nofollow noreferrer\">word list</a> for running the code (put the file in the same folder with the script).</p>\n\n<pre><code>import random\nimport string\n\nwords = [word for word in open('random_words.txt').read().split()]\nattempts = 6\nhangman_pics = ['''\n +---+\n | |\n |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n | |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n /| |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n /|\\ |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n /|\\ |\n / |\n |\n=========''', '''\n +---+\n | |\n O |\n /|\\ |\n / \\ |\n |\n========='''][::-1]\n\n\ndef get_current_figure():\n \"\"\"Print current state of Hangman.\"\"\"\n print(hangman_pics[attempts])\n\n\ndef play_game():\n \"\"\"Play game.\"\"\"\n global attempts\n available_letters = list(string.ascii_lowercase)\n letters_guessed = []\n secret_word = random.choice(words)\n slots = ['_' for _ in range(len(secret_word))]\n valid_responses = ['y', 'yes', 'n', 'no']\n print('Welcome to the hangman!')\n confirm_start = input('Would you like to start a new game?' 'y/n: ').lower()\n while confirm_start not in valid_responses:\n print(f'Invalid response! {confirm_start} Enter y/n')\n confirm_start = input('Would you like to start a new game?' 'y/n: ').lower()\n if confirm_start == 'n' or confirm_start == 'no':\n print('Thank you for playing Hangman.')\n print(29 * '=')\n exit(0)\n while confirm_start == 'y' or confirm_start == 'yes':\n if not attempts:\n get_current_figure()\n print(f\"You're dead, the word was {secret_word}\")\n break\n check_win = 0\n for letter in secret_word:\n if letter in letters_guessed:\n check_win += 1\n if check_win == len(secret_word):\n print(f'Well done! you win.\\nThe correct word is {secret_word}')\n print(45 * '=')\n get_current_figure()\n print(f\"Available letters: {''.join(available_letters)}\")\n print(f\"Letters used: {''.join(sorted(letters_guessed))}\")\n print(f'You have {attempts} attempts left.')\n print(slots, '\\n')\n letter_guessed = input('Guess a letter: ').lower()\n if letter_guessed in letters_guessed:\n print(f'You already tried that letter {letter_guessed}')\n attempts -= 1\n if letter_guessed.isalpha() and len(letter_guessed) == 1 and letter_guessed not in letters_guessed:\n available_letters.remove(letter_guessed)\n letters_guessed.append(letter_guessed)\n if letter_guessed in secret_word and len(letter_guessed) == 1:\n for index, letter in enumerate(secret_word):\n if letter_guessed == letter:\n slots[index] = letter\n print(f'Correct guess! {letter_guessed} is in the word.')\n if letter_guessed not in secret_word:\n attempts -= 1\n print(f'Wrong guess! {letter_guessed} not in the word.')\n if not letter_guessed.isalpha() or len(letter_guessed) > 1:\n print(f'Invalid entry {letter_guessed}')\n print('You have been penalized and lost 2 attempts!')\n attempts -= 2\n\n\ndef replay_game():\n \"\"\"Return True for a game replay, False otherwise.\"\"\"\n valid_responses = ['y', 'yes', 'n', 'no']\n replay = input('Would you like to play another game? y/n ').lower()\n while replay not in valid_responses:\n print(f'Invalid response {replay}')\n replay = input('Would you like to play another game? y/n ').lower()\n if replay == 'y' or replay == 'yes':\n return True\n if replay == 'n' or replay == 'no':\n print('Thank you for playing Hangman.')\n print(29 * '=')\n exit(0)\n return False\n\n\nif __name__ == '__main__':\n while True:\n play_game()\n replay = replay_game()\n if replay:\n attempts = 6\n play_game()\n else:\n exit(0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T12:33:12.777",
"Id": "441135",
"Score": "2",
"body": "Even just looking at your `if __name__ == \"__main__\"` block, there are problems - making `attempts` a global variable here is very bad form, just pass it as an argument to `play_game()` (which then passes it as an argument to `get_current_figure()`) or alternatively just make it a local variable in `play_game()`. Also, `get_current_figure()` is a bad name for something that prints something - it should either return the string (not print it) or be called `draw_current_figure()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:11:08.800",
"Id": "441171",
"Score": "0",
"body": "I didn't like the global variable thing but since the get_current_figure uses the variable attempts to print state. regarding the naming of get_current_figure, at first, I made it print_current_figure and for some reason the editor highlighted the name, so I changed it to get_current_figure ... print_current_figure is better anyway"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:30:37.840",
"Id": "441175",
"Score": "0",
"body": "And I suggest you focus more on the actual code being reviewed here, not on comments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:09:43.233",
"Id": "441190",
"Score": "7",
"body": "Critiquing code in answers is arguably more important than critiquing the original code, since by answering this question you're automatically assuming sort of a position of authority - if no one says anything, then the OP, as a beginner, can only assume that code in answers is good code and that they should code that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:12:49.947",
"Id": "441191",
"Score": "1",
"body": "I guess you have a point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T19:53:56.897",
"Id": "441225",
"Score": "0",
"body": "The comment \"Play game.\" for a function called `play_game` is useless and should be removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T19:57:59.327",
"Id": "441227",
"Score": "0",
"body": "In `replay_game` there is an `exit(0)` followed by `return False`. The latter code cannot be reached."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T23:47:02.750",
"Id": "226802",
"ParentId": "226790",
"Score": "11"
}
},
{
"body": "<p>It's not that great of an optimization but if you're new to programming it can be interesting to consider something along the line of :</p>\n\n<pre><code>hangman_part = ['O','|','/','\\\\','/','\\\\']\nhangman_base ='''\n +---+\n | |\n 0 |\n 213 |\n 4 5 |\n |\n========='''\n</code></pre>\n\n<p>and</p>\n\n<pre><code>def get_current_figure():\n \"\"\"Print current state of Hangman.\"\"\"\n hangman_pic = hangman_base\n for i in range(6) :\n if 5-attempts >= i:\n hangman_pic = hangman_pic.replace(i, hangman_part[i])\n else:\n hangman_pic = hangman_pic.replace(i, ' ')\n print(hangman_pic)\n</code></pre>\n\n<p>(I don't use Python so I may have missed something, it's more for the idea anyway)</p>\n\n<p>This code sacrifice some perfs (usually negligible) for an improved maintainability. Let's say you want to change the design of your gallows (or your man), now you only need to do it once !</p>\n\n<p>Sure, in your specific case, there's not that much possible changes, nor that many gallows to change. But you're doing it to practice and in practice, it's nearly always a good idea to go for maintainability.</p>\n\n<p>I'd like to argue that it also improved readability, since you now have way less lines, but it's not granted since we added a bit of complexity. I guess it may vary depending on the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T19:19:09.260",
"Id": "441221",
"Score": "2",
"body": "hangman_part = ['O','|','/','\\','/','\\'] this line contains a syntax error due to the so-called backslash you added and since it looks like you're new to Python and maybe programming in general, I suggest you check PEP8 https://www.python.org/dev/peps/pep-0008/ the official Python style guide before writing some code in Python to avoid making mistakes like this for i in range(0, 5) (and it is 6 btw not 5 attempts) and is expressed : for i in range(5) (no need to add 0) Please revise your code and run it instead of this leap of faith."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T08:42:08.523",
"Id": "441290",
"Score": "0",
"body": "@emadboctor : `(I don't use Python so I may have missed something, it's more for the idea anyway)` ^^... As you can see in the `hangman_base`, there is only [0-5] numbers (and parts) to replace, going up to 6 should issue some error no ? Thanks for correcting my `\\\\`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:00:13.647",
"Id": "441351",
"Score": "0",
"body": "@Nomis The Python `range(start, stop)` object is “half-open”; it includes the `start` value but excludes the `stop` value. So `range(0, 5)` only includes the 5 values `0, 1, 2, 3, 4`. It is similar to the C/C++ loop: `for(int i=0; i<5; i++) {...}` in this respect; the loop ends when the endpoint is reached instead of after the endpoint is reached."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:16:15.847",
"Id": "441356",
"Score": "0",
"body": "@AJNeufeld : wow, it was so intuitive that I never got up to this part in the doc ><. Thanks to you two for pointing it out and taking the time to explain it !"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T10:23:14.360",
"Id": "226831",
"ParentId": "226790",
"Score": "14"
}
},
{
"body": "<h2>Clearing the screen</h2>\n\n<p><code>os.system('cls')</code> is a horrible way of clearing the screen.</p>\n\n<p>The cross-platform <code>os.system('cls' if os.name == 'nt' else 'clear')</code> alternative is just as bad.</p>\n\n<p>What this is doing is forking a child process, and in the child process (which is currently a copy of the current process's code and data memory):</p>\n\n<ul>\n<li>replace the current process image with the \"shell\" image (such as <code>cmd.exe</code> or <code>/bin/sh</code>)</li>\n<li>is run to interpret the <code>'cls'</code> or <code>'clear'</code> command, which in turn may fork yet another new child process to execute that command, if not a built-in command.</li>\n</ul>\n\n<p>In addition, the <code>cls</code> or <code>clear</code> commands might not be the standard commands if another program by that name is discovered on the shell's <code>$PATH</code>.</p>\n\n<p>You already using <code>colorama</code>, so simply use it to clear the screen:</p>\n\n<pre><code>import colorama\n\ndef clear_screen():\n print(colorama.ansi.clear_screen())\n\ncolorama.init()\n\nclear_screen()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:07:50.930",
"Id": "441355",
"Score": "0",
"body": "Thanks for the tip! What if I didn't use colorama? Would importing colorama just to clear the screen still be an optimal way or shall I try something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T14:41:43.043",
"Id": "441361",
"Score": "0",
"body": "`colorama.ansi.clear_screen()` is a verbose way of getting (IIRC) the string `\"\\x1b[2J\"`. If the terminal you are running in supports ANSI escape sequences, you may simply use `print(\"\\x1b[2J\")`. On Window, on a non-ANSI terminal, `colorama.init()` will replace `sys.stdout` with its own stream that filters out ANSI escape sequences and calls the appropriate Win32 functions in their place. The fact that you used `Fore.GREEN` and `Fore.RED` without calling `colorama.init()` suggests the terminal already supports ANSI escape sequences..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T19:42:15.830",
"Id": "226869",
"ParentId": "226790",
"Score": "8"
}
},
{
"body": "<p><strong>Layout</strong></p>\n\n<p>One trivial thing I didn't notice in the other answers is that </p>\n\n<pre><code>hangman_pics = ['''\n ...\n=========''']\n</code></pre>\n\n<p>would be better written as </p>\n\n<pre><code>hangman_pics = [\n '''\n ...\n=========''',\n]\n</code></pre>\n\n<p>just because the triple-quoted multi-line strings slightly mess with the usual indentation protocol for the individual elements of such a list, doesn't mean that you should not bother to make the open and close square brackets as prominent as possible (with the <code>]</code> re-establishing the indentation level for a human reader of the code which follows, which here is zero indentation). </p>\n\n<p>I once coded something similar in which the triple-quoted strings had to span even more lines and were less similar, and I then felt that building the list dynamically kept it clearer. I don't think it's necessary here, but for reference:</p>\n\n<pre><code>hangman_pics = []\nhangman_pics.append( '''\n ...\n''' )\nhangman_pics.append( '''\n ...\n''' )\n# etc. \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T11:48:49.057",
"Id": "226917",
"ParentId": "226790",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T19:18:31.953",
"Id": "226790",
"Score": "28",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"hangman"
],
"Title": "A first \"Hangman\" game in Python"
}
|
226790
|
<p>I built a simple console version of the rock paper scissors game. I would love to get some constructive criticism!</p>
<p><strong>Questions</strong></p>
<ol>
<li>How could I code this in an object-oriented way?</li>
<li>Did my code follow the DRY principle?</li>
</ol>
<p><strong>Link to code</strong></p>
<p>Repl: <a href="https://repl.it/@antgotfan/CrowdedGreenFlatassembler" rel="nofollow noreferrer">https://repl.it/@antgotfan/CrowdedGreenFlatassembler</a></p>
<pre><code> var moves, result, images, relativePath, playerSelection, computerSelection;
moves = {
rock: 0,
paper: 1,
scissors: 2,
};
function init() {
result = {
player: 0,
tie: 0,
computer: 0
};
}
init();
function convertMoves() {
// when any rock paper scissor button is clicked
// then return that string into the moves object
// return a number corresponding to the handsign.
playerSelection = prompt("Please choose rock, paper, or scissors!");
return moves[playerSelection];
}
function computerPlay() {
var movesValues = Object.values(moves);
var random = Math.floor(Math.random() * movesValues.length);
return movesValues[random];
}
function playRound(playerSelection, computerSelection) {
computerSelection = computerPlay();
playerSelection = convertMoves();
var processResult = (3 + computerSelection - playerSelection) % 3;
if (!processResult) {
++result.tie;
console.log('tie');
} else if (1 === processResult) {
++result.computer;
console.log('Computer won');
} else {
++result.player;
console.log('Player won');
}
return result;
}
function game() {
for (var perRound = 1; perRound < 5; perRound++) {
playRound(playerSelection, computerSelection);
}
}
game();
console.log(playRound(playerSelection, computerSelection));
</code></pre>
|
[] |
[
{
"body": "<p>This doesn't quite answer your questions, but still hopefully helpful.</p>\n\n<p><code>var perRound = 1; perRound < 5; perRound++</code> only executes four times; the fifth execution is coming from the last line of your program. It's customary to use <code>i</code> when simply doing something multiple times, and to start with <code>0</code> such as: <code>var i = 0; i < 5; i++</code>. Then remove that extra <code>playRound</code> at the end so you still have five rounds.</p>\n\n<p>I would rename <code>convertMoves</code> to <code>playerMove</code> to better describe what it does instead of how it does it.</p>\n\n<p><code>playRound</code> isn't using its arguments. So you can change the first few lines to:</p>\n\n<pre><code> function playRound() {\n var computerSelection = computerPlay();\n var playerSelection = convertMoves();\n</code></pre>\n\n<p>You might play with changing <code>moves</code> to an array and see if you like it better as <code>moves = ['rock', 'paper', 'scissors'];</code>. This will require several other changes to how you use it but I think it'll read easier in the end.</p>\n\n<p>Just as a matter of style, put the <code>++</code> after the variable except for the rare times when you really need the other behavior.</p>\n\n<p>Again, hope this helps.</p>\n\n<p>Edit: I see now why you have the extra <code>playRound</code> at the end. But <code>result</code> is already global so you can simply end with <code>console.log(result)</code> instead of returning it from <code>playRound</code> each time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T04:17:30.123",
"Id": "441038",
"Score": "0",
"body": "This was really helpful! Thank you Nathan."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T03:50:27.867",
"Id": "226810",
"ParentId": "226794",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T20:42:53.380",
"Id": "226794",
"Score": "2",
"Tags": [
"javascript",
"game",
"rock-paper-scissors"
],
"Title": "JavaScript - Rock Paper Scissors Game"
}
|
226794
|
<p>I am working on a basic blog application in <strong>Codeigniter 3.1.8</strong> and <strong>Bootstrap 4</strong>.</p>
<p>The application allows Registration and Login. I have concerns about the security level of the Registration system I have put together.</p>
<p>The Register controller:</p>
<pre><code>class Register extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index() {
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['tagline'] = 'Want to write for ' . $data['site_title'] . '? Create an account.';
$data['categories'] = $this->Categories_model->get_categories();
$this->form_validation->set_rules('first_name', 'First name', 'required');
$this->form_validation->set_rules('last_name', 'Last name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
$this->form_validation->set_rules('terms', 'Terms and Conditions', 'required', array('required' => 'You have to accept the Terms and Conditions'));
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
// If validation fails
if ($this->form_validation->run() === FALSE) {
$this->load->view('partials/header', $data);
$this->load->view('auth/register');
$this->load->view('partials/footer');
} else {
// If the provided email does not already
// exist in the authors table, register user
if (!$this->Usermodel->email_exists()) {
// Encrypt the password
$enc_password = md5($this->input->post('password'));
// Give the first author admin privileges
if ($this->Usermodel->get_num_rows() < 1) {
$active = 1;
$is_admin = 1;
} else {
$active = 0;
$is_admin = 0;
}
// Register user
$this->Usermodel->register_user($enc_password, $active, $is_admin);
if ($this->Usermodel->get_num_rows() == 1) {
$this->session->set_flashdata('user_registered', "You are now registered as an admin. You can sign in");
} else {
$this->session->set_flashdata('user_registered', "You are now registered. Your account needs the admin's aproval before you can sign in.");
}
redirect('login');
} else {
// The user is already registered
$this->session->set_flashdata('already_registered', "The email you provided already exists in our database. Please login.");
redirect('login');
}
}
}
}
</code></pre>
<p>The Usermodel model:</p>
<pre><code>class Usermodel extends CI_Model {
public function email_exists() {
$query = $this->db->get_where('authors', ['email' => $this->input->post('email')]);
return $query->num_rows() > 0;
}
public function get_num_rows() {
$query = $this->db->get('authors');
return $query->num_rows();
}
public function getAuthors(){
$query = $this->db->get('authors');
return $query->result();
}
public function deleteAuthor($id) {
return $this->db->delete('authors', array('id' => $id));
}
public function activateAuthor($id) {
$author = null;
$updateQuery = $this->db->where(['id' => $id, 'is_admin' => 0])->update('authors', array('active' => 1));
if ($updateQuery !== false) {
$authorQuery = $this->db->get_where('authors', array('id' => $id));
$author = $authorQuery->row();
}
return $author;
}
public function deactivateAuthor($id) {
$author = null;
$updateQuery = $this->db->where(['id' => $id, 'is_admin' => 0])->update('authors', array('active' => 0));
if ($updateQuery !== false) {
$authorQuery = $this->db->get_where('authors', array('id' => $id));
$author = $authorQuery->row();
}
return $author;
}
public function register_user($enc_password, $active, $is_admin) {
// User data
$data = [
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
'password' => $enc_password,
'register_date' => date('Y-m-d H:i:s'),
'active' => $active,
'is_admin' => $is_admin
];
return $this->db->insert('authors', $data);
}
public function user_login($email, $password)
{
$query = $this->db->get_where('authors', ['email' => $email, 'password' => md5($password)]);
return $query->row();
}
}
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>I have decided to post the <code>login()</code> method, from the Login controller, as changing the <code>Register</code> class would require changing the login accordingly:</p>
<pre><code>public function login() {
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if ($this->form_validation->run()) {
$email = $this->input->post('email');
$password = $this->input->post('password');
$this->load->model('Usermodel');
$current_user = $this->Usermodel->user_login($email, $password);
// If we find a user
if ($current_user) {
// If the user found is active
if ($current_user->active == 1) {
$this->session->set_userdata(
array(
'user_id' => $current_user->id,
'user_email' => $current_user->email,
'user_first_name' => $current_user->first_name,
'user_is_admin' => $current_user->is_admin,
'user_active' => $current_user->active,
'is_logged_in' => TRUE
)
);
// After login, display flash message
$this->session->set_flashdata('user_signin', 'You have signed in');
//and redirect to the posts page
redirect('/dashboard');
} else {
// If the user found is NOT active
$this->session->set_flashdata("login_failure_activation", "Your account has not been activated yet.");
redirect('login');
}
} else {
// If we do NOT find a user
$this->session->set_flashdata("login_failure_incorrect", "Incorrect email or password.");
redirect('login');
}
}
else {
$this->index();
}
}
</code></pre>
<p>Looking for feedback and improvement ideas.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T23:49:10.663",
"Id": "442168",
"Score": "0",
"body": "I just happened to open this question. So it's not a complete review. Instead of making `email_exists()` you can add this rule `is_unique[authors.email]` in your validation. You should not use `md5` for encrypting password. Use `password_hash()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T14:07:43.863",
"Id": "442254",
"Score": "0",
"body": "Since you have added the `Login` controller could you please add the `index()` function for that class too?"
}
] |
[
{
"body": "<p>There are a number of things I'd do differently and the first is a <strong>must</strong>.</p>\n\n<p>First, using <code>md5()</code> to encode a password is universally considered a bad practice. It's been considered too weak for that purpose since at least 2004 if not earlier. Instead, use the PHP function <a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">password_hash</a>. </p>\n\n<p>I would encrypt the password in the model. In fact, I'd move almost all the registration logic to the model. Here's my version of <code>Usermodel::register_user()</code></p>\n\n<pre><code>public function register_user()\n{\n // Get the entire $_POST array with one call then extract what we need\n $posted = $this->input->post();\n\n $field_list = ['first_name', 'last_name', 'email', 'password'];\n foreach($field_list as $field){\n $data[$field] = $posted[$field];\n }\n\n $enc_password = password_hash($data['password']);\n\n // if password_hash fails it's time to bail\n if( ! $enc_password)\n {\n return false;\n }\n // update $data with encrypted password\n $data['password'] = $enc_password;\n\n // Put additional items in the $data array \n $data['register_date'] = date('Y-m-d H:i:s');\n // CodeIgniter has a method to count records - use it. Remove get_num_rows() from model\n $data['is_admin'] = $this->db->count_all('authors') === 0 ? 1 : 0;\n $data['active'] = $data['is_admin'];\n\n if($inserted = $this->db->insert('authors', $data) === TRUE)\n {\n if($data['is_admin'] === 1)\n {\n $msg = \"You are now registered as an admin. You can sign in\";\n }\n else\n {\n $msg = \"You are now registered. Your account needs the admin's approval before you can sign in.\";\n }\n $this->session->set_flashdata('user_registered', $msg);\n }\n return $inserted;\n}\n</code></pre>\n\n<p>With that new method and a little rearranging in the controller, we can make the code a bit more concise</p>\n\n<pre><code>public function index()\n{\n $this->form_validation\n ->set_rules('first_name', 'First name', 'required')\n ->set_rules('last_name', 'Last name', 'required')\n ->set_rules('email', 'Email', 'required|trim|valid_email')\n ->set_rules('password', 'Password', 'required|min_length[6]')\n ->set_rules('cpassword', 'Confirm password', 'required|matches[password]')\n ->set_rules('terms', 'Terms and Conditions', 'required',\n array('required' => 'You have to accept the Terms and Conditions'))\n ->set_error_delimiters('<p class=\"error-message\">', '</p>');\n\n if($this->form_validation->run())\n {\n // If the provided email isn't on record then register user\n if( ! $this->Usermodel->email_exists())\n {\n // Register user\n if($this->Usermodel->register_user())\n {\n // worked - go to login\n redirect('login');\n }\n // register_user() returned false - set an error message for use in 'auth/register' view\n $data['registration_error_msg'] = \"Registration Failed! Please contact Administrator.\";\n }\n else\n {\n // The user is already registered\n $this->session->set_flashdata('user_registered',\n \"The email you provided already exists in our database. Please login.\");\n redirect('login');\n }\n }\n\n // Validation or registration failed or it's the first load of this page\n $data = $this->Static_model->get_static_data();\n $data['pages'] = $this->Pages_model->get_pages();\n $data['tagline'] = 'Want to write for '.$data['site_title'].'? Create an account.';\n $data['categories'] = $this->Categories_model->get_categories();\n $this->load->view('partials/header', $data);\n $this->load->view('auth/register');\n $this->load->view('partials/footer');\n}\n</code></pre>\n\n<p>Using <code>password_hash()</code> means the login logic needs to be refactored also and the PHP function <code>password_verify()</code> must be used. <code>password_verify</code> — confirms that a password matches a hash of that password. With that in mind, `Usermodel::user_login might look like this.</p>\n\n<pre><code>public function user_login()\n{\n $email = filter_var($this->input->post('email'), FILTER_SANITIZE_EMAIL);\n\n if(filter_var($email, FILTER_VALIDATE_EMAIL))\n {\n $user = $this->db\n ->select('password, user_id, active')\n ->get_where('authors', ['email' => $email])\n ->row();\n\n if(password_verify($this->input->post('password'), $user->password))\n {\n if($user->active)\n {\n return $user->user_id;\n }\n $this->session->set_flashdata(\"login_failure_activation\", \"Your account has not been activated yet.\");\n }\n else\n {\n $this->session->set_flashdata(\"login_failure_incorrect\", \"Incorrect email or password.\");\n }\n }\n return false;\n}\n</code></pre>\n\n<p>The above is going to mean that the controller's <code>login()</code> method will need to be reworked too.</p>\n\n<p>An unbreakable security rule is <strong>\"Never Trust User Input!\"</strong></p>\n\n<p>So, any data sent to the server must be sanitized and validated. This is true even for some identifier (like a user_id) that is part of a URL that you put on the screen. With that in mind, you should always (at the very minimum) make sure that any model function that has a <code>$id</code> argument is getting the right datatype.</p>\n\n<p>Let's assume your user_id type is an integer. For instance, the controller method that activates an author might make this kind of check before sending it to the model. </p>\n\n<pre><code>public function activate_author($id)\n{\n if(filter_var($id, FILTER_VALIDATE_INT)) \n {\n $this->Usermodel->activateAuthor($id)\n // other code \n } \n else \n {\n //respond in a way that doesn't give a bad-actor too much info\n }\n\n}\n</code></pre>\n\n<p>While CodeIgniter's validation library is quite good it doesn't go far enough. Particularly when it comes to sanitizing. A serious study of the <a href=\"https://www.php.net/manual/en/book.filter.php\" rel=\"nofollow noreferrer\">PHP docs on Filters</a> is recommended. There are lots of online tutorials on using <code>filter_var</code> too.</p>\n\n<p>Further Reading on PHP Security:</p>\n\n<p><a href=\"https://paragonie.com/blog/2015/08/gentle-introduction-application-security\" rel=\"nofollow noreferrer\">A Gentle Introduction to Application Security</a></p>\n\n<p><a href=\"https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software\" rel=\"nofollow noreferrer\">The 2018 Guide to Building Secure PHP Software</a></p>\n\n<p><a href=\"https://paragonie.com/blog/2017/04/checklist-driven-security-considered-harmful\" rel=\"nofollow noreferrer\">Checklist-Driven Security Considered Harmful</a></p>\n\n<p><a href=\"https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence\" rel=\"nofollow noreferrer\">Implementing Secure User Authentication in PHP Applications with Long-Term Persistence</a> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T05:52:17.413",
"Id": "442187",
"Score": "0",
"body": "Thanks for the elaborated answer. Please provide one for **[this](https://stackoverflow.com/questions/57646370/codeigniter-application-how-can-i-display-pagination-as-json)** question too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T06:33:57.733",
"Id": "442192",
"Score": "0",
"body": "Registration with `password_hash` works fine but my login function does no work, even though I replaced `md5()` with `password_hash`: `public function user_login($email, $password){\n $query = $this->db->get_where('authors', ['email' => $email, 'password' => $hashed_password]);\n return $query->row();\n }`\n\nIn the Login controller: $hashed_password = password_hash($password, PASSWORD_DEFAULT);\n\nWhat shall I change?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:24:00.487",
"Id": "442452",
"Score": "0",
"body": "@RazvanZamfir I have added code showing how to check against a `password_hash()` value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:41:25.297",
"Id": "442455",
"Score": "0",
"body": "The first that registers as author must be automatically active, therefore he/she mist not see the \"Your account has not been activated yet.\" message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:47:42.587",
"Id": "442456",
"Score": "0",
"body": "The first that registers **is** made active automatically. `user_login()` will also set the \"not activated yet\" message."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T04:27:41.553",
"Id": "227249",
"ParentId": "226795",
"Score": "4"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/227249/200133\">DFriend's answer</a> is good, but it sounds like some more clarity is needed about how to use the built-in <code>password_hash</code> function, and there are some architectural things you could improve.</p>\n\n<p>Is the email address the primary key for the <code>authors</code> table? That's not an excellent choice, but we'll roll with it.</p>\n\n<p>To properly use <a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">password_hash</a>, you must also use <a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">password_verify and password_needs_rehash</a>. This means that you can't just re-hash the password and look for the hash in the database. You have to identify the user-row in the database, load the stored hash into the PHP layer, and check that against the provided password in question. I haven't tested the below, but it's more-or-less how I'd write it.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Password_helper {\n const ALGO = PASSWORD_DEFAULT;\n\n public static set_password(CI_Controller $CI, string $email, string $p):bool{\n // We could do any password-strength rules or setting of optional arguments here,\n // but I'll assume you're not doing that.\n return $CI->db->update(\n 'authors',\n ['password' => password_hash($p, self::ALGO)],\n ['email' => $email]);\n }\n\n public static check_and_upkeep(CI_Controller $CI, string $email, string $p):bool{\n $_user = $CI->db->get_where(\n 'authors',\n ['email' => $email], \n 1)\n ->result();\n if($_user){\n $user = $_user[0];\n if(password_verify($p, $user->password)){\n if(password_needs_rehash($user->password, self::ALGO)){\n self::set_password($CI, $email, $p);\n }\n return true;\n }\n else{\n return false;\n }\n }\n else{\n return false;\n }\n }\n}\n</code></pre>\n\n<p>The above might not jive perfectly with the concept of a \"model\" you're using; CodeIgniter's \"model\" concept is frankly problematic. Also, to use the above, you'll need to insert the user to the database <em>first</em>, then set their password. That's fine; you can just temporarily set their password to \"\".</p>\n\n<h3>Another security detail:</h3>\n\n<p>The business of making the first author the (an?) administrator is not good. There's hypothetically a chance someone might snipe you, and anyway it'll be cluttering up the codebase forever.<br>\nDepending what you mean by \"admin\", you maybe shouldn't even have \"admins\" in the same table as \"users\". In any case, remove that whole business from the registration stack; you can set your first admin manually in the database using some other tool. </p>\n\n<h3>Other stuff:</h3>\n\n<ul>\n<li>A key and specific role of the Controller \"endpoint\" function (<code>index()</code> for example) is to parse, sanitize, and validate input, all of it. Both you and DFriend are reading <code>POST</code> values down in the model layer; those values should be passed down as arguments. If the number of arguments starts to feel unworldly, you can make classes (\"models\") for different data structures like Authors.</li>\n<li>I imagine you've repeated that trio of <code>$this->load->view()</code> calls, and the associated construction of <code>$data</code>, several times throughout your site. Wrap all of that up in a single place, either as a method of a Controller base class, or as a method of a Loader extension class. Also note that you can load views from inside of views, so a single master-template may be better than having separate header and footer \"partial\" views.</li>\n<li>Similar to what I mentioned above, don't use <code>$this->Usermodel->get_num_rows() == 1</code> to check if the user is an admin or is active; at that point you should have the user's data on hand and be able to check literally. </li>\n<li>I don't like flashdata, I'd rather use the url hash to pass a narrow range of messages to javascript running on the target page. But that's just personal preference.</li>\n<li>You could consolidate your (de)activateAuthor functions if you want. When they're called, you should have already validated that the target exists, so getting a falsy value from the DB would be grounds to throw an error.</li>\n<li>As much as I hate CI's \"models\", they'll be slightly less painful if you throw them all in your auto-load config file; then you don't need to load them explicitly.</li>\n<li>Your <code>login()</code> endpoint method calls the <code>index()</code> endpoint method if validation fails. That's an odd choice.</li>\n<li>Using typed function signatures will make your code easier to read and <em>more</em> likely to break in obvious ways. The advantage being that it's <em>less</em> likely to break in <em>insidious</em> ways. <strong>I strongly recommend this.</strong></li>\n<li>In DFriend's code:\n\n<ul>\n<li><code>$inserted</code> is assigned a value in the conditional of an if statement. Don't do that.</li>\n<li>Don't rely on <code>redirect</code> or <code>load->view()</code> to stop execution. Even when it works it makes things harder to read. Use explicit return statements, or put the alternate path in an explicit <code>else</code>, or both.</li>\n</ul></li>\n</ul>\n\n<h3>Edit: Hi DFriend!</h3>\n\n<p>You raise several points; it sounded like you were hoping for a response. </p>\n\n<ul>\n<li>I like your point that brevity is part of clarity. The other point of clarity is saying what you mean, and saying it as code is briefer and stronger than leaving a comment.</li>\n<li>Sanitizing, validating, and parsing inputs isn't business logic, as I understand the phrase. <em>A</em> key role of the Controller is to handing inputs. If we take the framework for granted (as we would like to), then we conceptually enter the program in the Controller endpoint method. That method needs to know about inputs (POST values, query strings, url fragments, cookies) because that's where all further action will be directed from. The thing we can do to maintain separation of concerns is <em>make sure nobody else needs to read those input sources</em>.</li>\n<li><code>redirect()</code> stops execution, but you have to know and remember that to make sense of code that relies on it. <code>CI->load->view()</code> doesn't stop execution, but is almost always the last call in the flow. Throwing a <code>return;</code> after all of them <em>is</em> a little verbose, but it's <em>clear</em>. </li>\n<li>It's a fact of life that there will be a lot of conditionals, and I really don't think there's a single pattern that will cover all cases. That said, if you're relying on a section of code only running if a prior <code>if</code> failed, <em>then you're in an else section whether you say so or not</em>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:28:44.217",
"Id": "442453",
"Score": "0",
"body": "Good call on keeping the encryption current through the use of `password_needs_rehash()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T19:58:50.833",
"Id": "442457",
"Score": "0",
"body": "I disagree with the concept that the \"key\" role of a Controller is to \"parse, sanitize, and validate input\". Controllers are responsible for controlling the flow of the application execution and returning a response to requests - **not business logic**."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:00:23.800",
"Id": "442458",
"Score": "0",
"body": "In the case of the Registration controller, ask the question: What does the controller need to know about the posted inputs? Such questions are vital to maintaining a clean Separation of Concerns. In this case, the controller doesn't need to know anything about the contents of `$_POST` other than checking that the basic requirements of the inputs are met (via `form_validation`) and ready for processing by the business logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:03:28.983",
"Id": "442459",
"Score": "0",
"body": "I agree that continually checking for the \"first user\" is begging for a different solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:05:42.107",
"Id": "442460",
"Score": "0",
"body": "You said, \"Your login() endpoint method calls the index() endpoint method if validation fails. That's an odd choice.\" I agree. That's why I asked the OP to include the code for that method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:16:35.730",
"Id": "442463",
"Score": "0",
"body": "You said, \"$inserted is assigned a value in the conditional of an if statement. Don't do that.\" Why? It's very common syntax used to set a var and check its value. While there are cases where you can outsmart yourself by getting too clever that syntax if you stick to a single assignment and compare it works perfectly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:23:02.073",
"Id": "442464",
"Score": "0",
"body": "The CodeIgniter function `redirect()` _will always end code execution_. The last line of the function is `exit;`. Not sure what you're seeing that implies `load->view()` is assumed to end script execution. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T20:37:11.240",
"Id": "442465",
"Score": "0",
"body": "Got to disagree that superflous `else` or redundant, or just plain unreachable `return` calls help readability or execution path comprehension. Deeply nested conditionals can make it just about impossible to tell what code will run, or when. They can also make it hard to keep code DRY. IMO, the more concise the code is the easier it is to read and the cleaner the execution path becomes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T21:34:37.353",
"Id": "442472",
"Score": "0",
"body": "Thanks @DFriend; I replied to a couple things as an edit above."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T18:55:47.257",
"Id": "227352",
"ParentId": "226795",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "227249",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T20:45:06.957",
"Id": "226795",
"Score": "2",
"Tags": [
"beginner",
"php",
"security",
"authentication",
"codeigniter"
],
"Title": "Codeigniter 3 Registration and Login System"
}
|
226795
|
<p>I solved the following problem:</p>
<blockquote>
<p>Write a function expand that takes in an expression with a single, one character variable, and expands it. The expression is in the form <code>(ax+b)^n</code> where <code>a</code> and <code>b</code> are integers which may be positive or negative, <code>x</code> is any one-character long variable, and <code>n</code> is a natural number. If <code>a</code> = 1, no coefficient will be placed in front of the variable. If <code>a</code> = -1, <code>a</code> "-" will be placed in front of the variable.
The expanded form should be returned as a string in the form <code>ax^b+cx^d+ex^f</code>... where <code>a</code>, <code>c</code>, and <code>e</code> are the coefficients of the term, <code>x</code> is the original one character variable that was passed in the original expression and <code>b</code>, <code>d</code>, and <code>f</code>, are the powers that <code>x</code> is being raised to in each term and are in decreasing order. If the coefficient of a term is zero, the term should not be included. If the coefficient of a term is one, the coefficient should not be included. If the coefficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coefficient should be included. If the power of the term is 1, the caret and power should be excluded.</p>
</blockquote>
<p>Examples:</p>
<pre><code>expand("(p-1)^3"); // returns "p^3-3p^2+3p-1"
expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
expand("(-2a-4)^0"); // returns "1"
expand("(-12t+43)^2"); // returns "144t^2-1032t+1849"
expand("(r+0)^203"); // returns "r^203"
expand("(-x-1)^2"); // returns "x^2+2x+1"
</code></pre>
<p>My solution passed all tests but I would like to know how it can be improved.</p>
<pre><code>function expand(str) {
const fac = n => n < 2 ? 1 : n * fac(n - 1);
let result = '', [_, a, x, b, n] = str.match(/\((-?\d*)([a-z])([-+]\d+)\)\^(\d+)/);
a = a ? a == '-' ? -1 : parseInt(a) : 1;
b = parseInt(b); n = parseInt(n);
for (let i = n; i >= 0; i--) {
let k = n - i;
let c = !b && k > 0
? 0
: a**i * b**k * (k == 0
? 1
: fac(n) / (fac(k) * fac(n - k)));
if (Math.abs(c) == 1 && i > 0) c = c > 0 ? '+' : '-';
else c = c > 0 ? `+${c}` : c;
if (c) result += c;
if (i > 0 && c) result += x;
if (i > 1 && c) result += `^${i}`;
}
return result[0] == '+' ? result.substr(1) : result;
}
</code></pre>
<p>I got this problem from a coding challenges site. <a href="https://www.codewars.com/kata/binomial-expansion" rel="nofollow noreferrer">https://www.codewars.com/kata/binomial-expansion</a> All the context that i had to solve it came from the description of the task.</p>
<p>I did not try to obfuscate the code. As Roland Illig stated, most of the single-letter variables come from the task. Variables <code>a, x, b, n</code> come from the parts of the input expression of the form <code>(ax+b)^n</code>. Variable <code>k</code> comes from a math formula <code>n!/(k!(n-k)!)</code> for the binomial coefficient. Variable <code>c</code> is the coefficient of the term being formed, and its mentioned in <code>ax^b+cx^d+ex^f</code>. So names come from problem's domain.</p>
<p>I mostly just do coding challenges for fun, and I like to golf things a bit. I concede the code lacks readability though.</p>
<p>My main concern is that small numbers like 203 have large factorials and produce overflow. One of the test cases is <code>expand("(r+0)^203"); // returns "r^203"</code>. I did not wanted to treat this case separately. Hence I used conditions <code>!b && k > 0</code> and <code>k == 0</code> to avoid calculating factorials for "large" <code>n</code> when <code>b == 0</code>. I would like to change this with a better approach for calculating the binomial coefficients. Sadly I don't know enough math.</p>
<p>If someone solves this problem differently I would love to see their code.</p>
<p>I don't have too much experience writing questions in stackexchange and English is not my native language. Tried to format the text to the best of my ability. Thanks all for your patience.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:47:17.240",
"Id": "441045",
"Score": "6",
"body": "What's with all the single-letter variables? Did you obfuscate this on purpose or do you always write like this? Genuinely concerned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:05:43.067",
"Id": "441050",
"Score": "0",
"body": "Did you create the _expanded form_ or was that also part of the challenge?"
}
] |
[
{
"body": "<p>Due to the lack of real context here (and issues I'll mention later), I can't really speak to the algorithm. I'll just focus on style.</p>\n\n<p>First, you need to take far greater care in creating meaningful names. This is incredibly hard to comprehend; and naming is the biggest contributor to the problem.</p>\n\n<p>Take a step back, pretend you didn't write this, and look at</p>\n\n<pre><code>let result = '', [_, a, x, b, n] = str.match(/\\((-?\\d*)([a-z])([-+]\\d+)\\)\\^(\\d+)/);\n</code></pre>\n\n<p>What are <code>a</code>, <code>x</code>, <code>b</code>, and <code>n</code>? Because they're coming from a regex match, they aren't self-descriptive. You need to give them proper names so that people like me (and others reading your code) can know the <em>intent</em> of the variable at a glance without needed to dig through and \"discover\" what they're for. I can't give suggestions due to the lack of context, but any names would be better than the single-letters being used now.</p>\n\n<p>If the line gets long, split it up. Do the deconstruction on a second line if need-be.</p>\n\n<hr>\n\n<p>I'm not a fan of your use of nested ternaries here. A line like</p>\n\n<pre><code>a = a ? a == '-' ? -1 : parseInt(a) : 1;\n</code></pre>\n\n<p>is unfortunate and takes longer to comprehend than it should, but is still mostly legible. At the very least, I'd add some brackets in so the grouping is more obvious:</p>\n\n<pre><code>a = a ? (a == '-' ? -1 : parseInt(a)) : 1;\n</code></pre>\n\n<p>or maybe, split that off into a function (local or otherwise):</p>\n\n<pre><code>function magnitude(a) {\n return a == '-' ? -1 : parseInt(a);\n}\n\n. . .\n\na = a ? magnitude(a) : 1;\n</code></pre>\n\n<p>At least now the line is simplified, and there's a name associated with part of the operation (<code>magnitude</code> was a bad guess. You know the intent so you'll be able to come up with a better name).</p>\n\n<p>On the other hand though,</p>\n\n<pre><code>let c = !b && k > 0\n ? 0\n : a**i * b**k * (k == 0\n ? 1\n : fac(n) / (fac(k) * fac(n - k)));\n</code></pre>\n\n<p>is bad. You are attempting to cram far too much functionality into too small of a space. Between the lack of proper names and the density, this is very hard to comprehend. I would definitely split this up. Maybe split it over a couple lines (with descriptively-named variables holding intermediate results), or maybe even split some off into a function.</p>\n\n<p>Along the same theme, you also have lines like</p>\n\n<pre><code>let result = '', [_, a, x, b, n] = str.match(/\\((-?\\d*)([a-z])([-+]\\d+)\\)\\^(\\d+)/);\n\nb = parseInt(b); n = parseInt(n);\n</code></pre>\n\n<p>There's little need to put them on the same line like this. I always advocate for declarations to be split over multiple lines in most cases (with the exception being maybe a simple destructuring).</p>\n\n<p>I would split these up:</p>\n\n<pre><code>let [_, a, x, b, n] = str.match(/\\((-?\\d*)([a-z])([-+]\\d+)\\)\\^(\\d+)/);\nlet result = \"\";\n\nlet b = parseInt(b);\nlet n = parseInt(n);\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>Overall, I would encourage you to spend far more time practicing making your code readable. Practice putting yourself in the shoes of someone who has never seen your code before. This can be hard to do, but allows you to find your own readability problems. I would also like to emphasize that dense, packed, small code is not good in most scenarios. If code needs to be minified, it can be run through a minifier after the fact. Your base source should be readable so it can be maintained into the future.</p>\n\n<hr>\n\n<p>It was pointed out that <code>a</code>, <code>x</code>, <code>b</code>, and <code>n</code> are pulled directly from the question, so they're appropriate. If possible I still think they should have better names, but if those are the accepted names to be used in the math equation, or they're too arbitrary for proper names, then yes, they're fine. <code>k</code> and <code>c</code> though both seem like they're not directly related to the equation, so better name there would help. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T22:24:02.967",
"Id": "441019",
"Score": "3",
"body": "Most of the single-letter names come directly from the task, so there's nothing from with them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T14:46:30.530",
"Id": "441155",
"Score": "2",
"body": "@RolandIllig If you included comments describing the task there, they would be good. If you don't, it doesn't matter if the task used them (to me), they still suck as names."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T22:17:21.183",
"Id": "226798",
"ParentId": "226797",
"Score": "7"
}
},
{
"body": "<p>You don't need the special case for <code>k == 0</code>. When <code>k == 0</code>, the result of the other expression will be 1 as well.</p>\n\n<p>For this sequence of binomial coefficients you don't need to calculate the full <code>fak</code> expression each time. You can also start with <code>c = a ** i</code>, and then, for each k, multiply by <code>(n - k) / (k + 1) * b / a</code>. That's a bit faster and provides less risk of producing numeric overflows, which would result in slightly incorrect coefficients. The Wikipedia article on binomial coefficients should explain this in more detail.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T12:36:30.120",
"Id": "441326",
"Score": "0",
"body": "How would I use `(n - k) / (k + 1) * b / a` to calculate de binomial coefficient? Can you elaborate on this please? How would it work for `(r+0)^203`? For `k = 0` it would be `(203 - 0) / (0 + 1) * 0 / 1 = 0`. Thanks for your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T17:39:34.300",
"Id": "441383",
"Score": "0",
"body": "Did you read the Wikipedia article?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:33:34.197",
"Id": "441477",
"Score": "0",
"body": "Im going through the Wikipedia page for Binomial Coefficient. It has several code samples that are far more efficient than the factorial formula. I will put that to use. Thank you for your help."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T22:21:54.377",
"Id": "226799",
"ParentId": "226797",
"Score": "8"
}
},
{
"body": "<p>This <code>fac(n) / (fac(k) * fac(n - k)</code> is an inefficient way to calculate n choose k. n choose k requires 2min(k, n-k) multiplications, yours does 2n multiplications. You iterate k from 0 to n, so yours does 2n^2+2n total multiplications over all coefficients -- the other one does about 1/4 of that.</p>\n\n<p>Calculating a binomial coefficient of (a,b) is something that has limited inputs and outputs, and is greatly suited to being a function. Write that function.</p>\n\n<p>I'd consider writing a term concept. A term is a coefficient, letter, and power of the letter; how that structure is defined is up to you.</p>\n\n<p>Write code that prints a term, instead of mixing it in with the rest of the logic -- the single responsibility principle.</p>\n\n<p>So you'd have code that (a) calculates n choose k, (b) given a linear term and a constant coefficient and n and k generates a binomial output term.</p>\n\n<p>Your main loop is then \"for each i from 0 to n, generate binomial term, print binomial term\".</p>\n\n<p>I'd also split the string-parsing code from the main body. Parsing a string <code>\"(ax+b)^n\"</code> into components is nearly completely orthogonal to the rest of the function's tasks.</p>\n\n<p>Write a function that does that, and only that.</p>\n\n<p>So, in pseudo code:</p>\n\n<pre><code> function task( string input ) \n [linear_coeff, variable, constant_coeff, exponent] = a_times_x_plus_b_pow_n_parse(input);\n for ( k from exponent downto 0 )\n output_coefficient = binomial_coefficient( linear_coeff, constant_coeff, k, exponent )\n term = make_term( output_coefficient, variable )\n print_term( term )\n</code></pre>\n\n<p>now write <code>a_times_x_plus_b_pow_n_parse</code>, <code>binomial_coefficient</code>, <code>make_term</code> and <code>print_term</code> functions.</p>\n\n<p>The big difference is that someone reading your code can see what everything is and what each step is supposed to do. In real production, each of those functions can be reasonably unit tested.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T14:59:13.587",
"Id": "226849",
"ParentId": "226797",
"Score": "3"
}
},
{
"body": "<p>The readability of this code suffers for multiple reasons. The biggest thing I see is multiple ternary operators in a single line. It is wise to limit the code to only one ternary operator per line. If you have to use more than one, then consider using parentheses to help anyone reading your code.</p>\n\n<p>As other have already pointed out, the variable names aren't very descriptive. Also, it is wise to wrap statements in curly braces, even for a single line - that way if you ever decide to add a line to the statement block you would be less likely to forget to wrap them.</p>\n\n<p>So instead of lines like this:</p>\n\n<blockquote>\n<pre><code>if (Math.abs(c) == 1 && i > 0) c = c > 0 ? '+' : '-';\nelse c = c > 0 ? `+${c}` : c;\nif (c) result += c;\n\nif (i > 0 && c) result += x;\nif (i > 1 && c) result += `^${i}`;\n</code></pre>\n</blockquote>\n\n<p>Use braces:</p>\n\n<pre><code>if (Math.abs(c) == 1 && i > 0) { c = c > 0 ? '+' : '-'; }\nelse { c = c > 0 ? `+${c}` : c; }\nif (c) {result += c; }\n\nif (i > 0 && c) { result += x;}\nif (i > 1 && c) { result += `^${i}`; }\n</code></pre>\n\n<hr>\n\n<p>If you are going to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt\" rel=\"nofollow noreferrer\"><code>parseInt()</code></a>, it is wise to specify the radix using the second parameter - unless you are using a unique number system like hexidecimal, octal, etc. then specify 10 for decimal numbers. </p>\n\n<blockquote>\n <p><strong>Always specify this parameter</strong> to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<pre><code>a = a ? a == '-' ? -1 : parseInt(a, 10) : 1;\nb = parseInt(b, 10); n = parseInt(n, 10);\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Parameters</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T21:19:47.723",
"Id": "226875",
"ParentId": "226797",
"Score": "0"
}
},
{
"body": "<h2>Lets move above JavaScript 101</h2>\n\n<p>To OP, I first must address the quality of some parts of some of the given answers that concern me.</p>\n\n<p>I am continually shocked at the misunderstanding of JavaScript here in Code Review, Sorry if I rub some the wrong way but please, we are professionals and our answers should reflect that fact.</p>\n\n<h3>Issues</h3>\n\n<ul>\n<li><p>The naming critique is nit picking and not worthy of a mention as the abstract is not in the realm of natural language.</p></li>\n<li><p>The critique of the nested ternaries is a worry, particularly in this problem as it deals with JS strings and alternatives ignore the need to avoid string building concatenation overhead. </p>\n\n<p>I would expect a first year JS101 student to be thrown by nested ternaries, but not professionals, the ongoing emphasize in this forum on avoiding them makes it look like an undergrad hangout.</p></li>\n<li><p>No one noticed the precision problem!!!! </p></li>\n</ul>\n\n<h2>The review</h2>\n\n<p>I found your function to be of good quality, naming is kept simple and in line with what one would expect from a mathematician. Due to the nature of the problem I would not expect someone without that type of knowledge to modify or get near the function.</p>\n\n<p>There are some simple style problems and can be DRY er</p>\n\n<p>The only major issue is that there is no (implied or direct) accounting for the the precision issue, </p>\n\n<h3>Number precision</h3>\n\n<p>I am surprised that your function passes all the tests because the upper limit of the polynomial order is well above the floating point (Double) precision of JavaScript Numbers</p>\n\n<p>Lets start with the most inefficient section of your code. The function you call <code>fac</code> that generates the factorial sequence. </p>\n\n<p>The size of value grows very quickly with <code>f(n) = f(70) = 1.197857166996989e100</code> that is close enough to a google to be called a <code>1.2 google</code></p>\n\n<p>If we consider that <code>Number.MAX_SAFE_INTEGER = 9.007199254740991e15</code> is 85 orders of magnitude below the 71st factorial any integer calculations around this range are going to produce rounding errors.</p>\n\n<h3>Ambiguous results due to precedence</h3>\n\n<p>This becomes even more pronounced as integer math seriously breaks down when we pass the precision limit.</p>\n\n<p>For example lets strip out some of your code and look at the second line in the <code>for</code> loop. Substituting some constants to demonstrate the problem</p>\n\n<pre><code>const fac = n => n < 2 ? 1 : n * fac(n - 1);\nconst a = 3, b = 13, n = 23, i = 11;\nconst k = n - i;\nconst c = !b && k > 0 ? 0 : a**i * b**k * (k === 0 ? 1 : fac(n) / (fac(k) * fac(n - k)));\n</code></pre>\n\n<p>In this special case the last line assigning to <code>c</code> has some redundancy that one would naturally reduce to the following line</p>\n\n<pre><code>const c1 = a**i * b**k * fac(n) / (fac(k) * fac(n - k));\n</code></pre>\n\n<p>We have not changed the equation, we have simply removed a brackets that separated the ternary with clause <code>(k === 0 ? ...)</code> (BTW could have been <code>(!k ? ...)</code>.</p>\n\n<p>However due to the way the rounding error is propagated the two lines <code>c</code>, <code>c1</code> will return two different values</p>\n\n<pre><code>console.log(c) // 5.580277237278821e+24\nconsole.log(c1) // 5.580277237278822e+24\nconsole.log(c === c1) // false\n</code></pre>\n\n<p>The different is minor and inconsequential in the order we are using, ~1 billion apart, but as the result is a string and as there are many ways to correctly arrange the precedence of the calculations there are many results that are about correct yet would not pass a string comparison.</p>\n\n<h3>Why did your function pass?</h3>\n\n<p>For high order polynomials getting the correct answer, is either,</p>\n\n<ol>\n<li>Just pure luck, </li>\n<li>The test is inclusive of all rounding errors (seriously doubt that)</li>\n<li>The test expects that you use <code>BigInt</code> in the calculations to avoid loss of precision (maybe but as you have passed all tests, my guess is that this is not so)</li>\n<li>You are never passed a polynomial above the precision range of a double that can not be optimized. eg <code>\"(x+0)^204\"</code> does not suffer precision problem as all but the first coefficients are 0 and the first is 1 with the result <code>\"x^204\"</code></li>\n</ol>\n\n<h2>Rewrite</h2>\n\n<p>If we consider that option 4 is the reality of the problem then we have a handy optimization available by using a lookup for the factorial sequence rather than calculating it of each coff. Limiting it to <code>Number.MAX_SAFE_INTEGER</code> we can cover that range up to <code>fac(24)</code></p>\n\n<p><strong>PLEASE NOTE</strong> that this is the upper limit and that as the order approaches 24 the chance of precision error increases depending on the size of the values of a and b. The order 24 represents the max order that may return reliable results, not the max order that will. eg <code>(12345235423875623537345x+1)^1</code> will likely fail.</p>\n\n<p>Rewriting your function with some changes to address style and performance </p>\n\n<ul>\n<li>Use <code>Number</code> rather than <code>parseInt</code></li>\n<li>Use constants for values that do not change</li>\n<li>Use the name <code>p</code> (power) or <code>o</code> (order) to replace <code>n</code>. I opt for 'p' as <code>o</code> is too near <code>0</code> for me (bad eyesight)</li>\n<li>Replace <code>x</code> with <code>name</code></li>\n<li>Drop the unneeded assignment to <code>_</code> underscore in the destructure declaration. eg <code>const [ _, a, b] = [1,2,3]</code> can also be written as <code>const [ , a, b] = [1,2,3]</code> you do not need to define unwanted items</li>\n<li>Rearrange the declarations a little. Assign the <code>String.match</code> to an array and then destructure to constants rather than variables.</li>\n<li>Avoiding the string building overhead of concatenating strings by using an array, to hold the coefficients (as strings) that is joined on the return to avoid overhead due to the need to iterate and reassign each time you concat a string variable.</li>\n<li>To further avoid the string building overhead we need to create a coefficient string in one expression and push that to an array of strings. That means we have no choise but to use <strong>NESTED ternaries</strong></li>\n<li>Use the less noisy <code>while</code> loop and move the top and bottom coefficient out of the loop and be handled as special cases.</li>\n<li>Add tests for early exits possible when <code>a = 0</code>, <code>p = 1</code> (<code>p</code> formaly <code>n</code>), eg <code>\"(x+0)^203\"</code> will return <code>\"x^203\"</code> without iterating 203 pointless coefficient calculations</li>\n<li>And some minor repeated calculations (and now a lookup) as stored constants rather than calculated. eg <code>k - n === i</code> so <code>fac(k - n)</code> can be <code>fac(i)</code> and fac(n) is the same each iteration so assign that to a constant <code>facN</code> before the loop.</li>\n<li>Add the function <code>signed</code> that returns the partial formatted coefficient string, with arguments to deal with leading sign.</li>\n<li>Add function <code>finalCoff</code> to handle the two cases when we tack on the last coff</li>\n</ul>\n\nOutput change\n\n<p>One change to the output as it makes no sense as it stands. When simplifying, eg <code>\"0x^2 + 2\"</code> becomes <code>\"2\"</code> however your function returns an empty string for <code>\"0x^2 + 0\"</code> becomes <code>\"\"</code>. This is not what one would expect, at minimum a number is expected, thus the function will return \"0\" rather than \"\"</p>\n\n<p>As you are running this in a test environment you will likely not be ablue to close over the array <code>facSeq</code> so I have placed it inside the function.</p>\n\n<pre><code>function expandA(str) {\n const facSeq = [0,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,6227020800,87178291200,1307674368000,20922789888000,355687428096000,6402373705728000,121645100408832000,2432902008176640000,51090942171709440000,1.1240007277776077e21,2.585201673888498e22,6.204484017332394e23];\n const finalCoff = n => n < 0 ? n : (n ? \"+\" + n : \"\");\n const signed = (n, pow, plus = \"+\") => (\n n < 0 ? \n (pow ? (n === -1 ? \"-\" : n) : (!pow ? n : \"-\")) : \n (n ? plus + (n > 1 ? n : \"\") : \"\")\n ) + \n (pow > 1 ? name + \"^\" + pow : (pow === 1 ? name : \"\"));\n\n const mt = str.match(/\\((-?\\d*)([a-z])([-+]\\d+)\\)\\^(\\d+)/)\n const [ , a, name, b, p] = [,\n mt[1] ? mt[1] == '-' ? -1 : Number(mt[1]) : 1,\n mt[2], Number(mt[3]), Number(mt[4])];\n\n if (a === 0) { return \"\" + b ** p }\n if (p === 1) { return (a ? signed(a, p, \"\") : \"\") + finalCoff(b) }\n const facN = facSeq[p];\n var i = p, coffs = [signed(a ** p, p, \"\")];\n while (i-- > 1) {\n const pos = p - i, cof = a ** i * b ** pos * facN / (facSeq[pos] * facSeq[i]);\n cof && coffs.push(signed(cof, i));\n }\n return coffs.join(\"\") + finalCoff(b ** p);\n}\n</code></pre>\n\n<p>If you find that this does not work, because the polynomials you need all coffs for are in orders greater than 24. You can reinstate the <code>fac</code> function, modified to lookup first and calculate if needed. <strong>NOTE</strong> still returns \"0\" rather than \"\"</p>\n\n<pre><code>function expandA(str) {\n const facSeq = [0,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600,6227020800,87178291200,1307674368000,20922789888000,355687428096000,6402373705728000,121645100408832000,2432902008176640000,51090942171709440000,1.1240007277776077e21,2.585201673888498e22,6.204484017332394e23];\n const fac = n => facSeq[n] ? facSeq[n] : (n < 2 ? 1 : n * fac(n - 1));\n const finalCoff = n => n < 0 ? n : (n ? \"+\" + n : \"\");\n const signed = (n, pow, plus = \"+\") => (\n n < 0 ? \n (pow ? (n === -1 ? \"-\" : n) : (!pow ? n : \"-\")) : \n (n ? plus + (n > 1 ? n : \"\") : \"\")\n ) + \n (pow > 1 ? name + \"^\" + pow : (pow === 1 ? name : \"\"));\n\n const mt = str.match(/\\((-?\\d*)([a-z])([-+]\\d+)\\)\\^(\\d+)/)\n const [ , a, name, b, p] = [,\n mt[1] ? mt[1] == '-' ? -1 : Number(mt[1]) : 1,\n mt[2], Number(mt[3]), Number(mt[4])];\n\n if (a === 0) { return \"\" + b ** p }\n if (p === 1) { return (a ? signed(a, p, \"\") : \"\") + finalCoff(b) }\n const facN = fac(p);\n var i = p, coffs = [signed(a ** p, p, \"\")];\n while (i-- > 1) {\n const pos = p - i, cof = a ** i * b ** pos * facN / (fac(pos) * fac(i));\n cof && coffs.push(signed(cof, i));\n }\n return coffs.join(\"\") + finalCoff(b ** p);\n}\n</code></pre>\n\n<h2>Performance</h2>\n\n<p>using the second version function and testing for a even distribution of <code>(nx+n)^m</code> where m is <code>1 <= m <= 300</code> and n is <code>-1000 < n < 1000</code> there is a marginal performance benefit of 10%</p>\n\n<p>If we avoid rounding errors by only passing zero for the first term <code>\"nx\"</code> n = 0 when <code>m > 20</code> and only making 5% of calls in the range <code>m > 20</code> the performance increases is near 40%</p>\n\n<p>The first version will not handle a full range but has an even better performance and may well pass the test suit you use. (excluding the \"0\")</p>\n\n<h2>Final</h2>\n\n<p>I expect this will get some down votes, and please do if you feel it warranted. </p>\n\n<p>If you do please do provide a comment regarding the reasoning for the benefit of the OP and others.</p>\n\n<p>I am not going to enter into debate and reply to comments of such nature unless specifically asked a question (collection of words ending with ?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:46:34.120",
"Id": "441439",
"Score": "0",
"body": "_The naming critique is nit picking and not worthy of a mention as the abstract is not in the realm of natural language._ I do believe even in math terms, critique on naming is warranted here. Naievely incrementing variable names in alphabetical order hurts readability. At some point we encounter _f_, which I would assume stands for _function_. I would have loved to see pairs of a multiplier and power (a, pa), (b, pb) and so on, rather than (a,b), (c,d)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:27:09.330",
"Id": "441475",
"Score": "0",
"body": "There are various things I like about your review. Mainly the focus on performance. My function passed the tests because of _4. You are never passed a polynomial above the precision range of a double that can not be optimized_. The test suite does not check for high powers. But I knew my code was'nt good enough, that's why I posted here. The choise of the formula that uses factorial was the worse pick. Im reading about options to replace it. I will test your code and will use some of your proposed changes. Thanks a lot for taking the time to review my code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:38:14.750",
"Id": "226947",
"ParentId": "226797",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T21:27:58.730",
"Id": "226797",
"Score": "8",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"ecmascript-6",
"symbolic-math"
],
"Title": "Expanding powers of expressions of the form ax+b"
}
|
226797
|
<p><code>source.Bottom(n, x => x)</code> should be the same as well known LINQ <code>source.OrderBy(x => x).Take(n)</code> but is more memory/run-time efficient as it does not keep all items in memory as <code>OrderBy</code> does:</p>
<pre><code>public static class BottomN
{
public static async IAsyncEnumerable<T> Bottom<T, TValue>(
this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector)
where TValue : IComparable<TValue>
{
var list = new List<T>();
await foreach(var item in source)
{
list.Insert(list.BestIndex(item, selector), item);
if (list.Count > number)
list.RemoveAt(number);
}
foreach (var item in list)
yield return item;
}
static int BestIndex<T, TValue>(this IList<T> list, T value, Func<T, TValue> selector)
where TValue : IComparable<TValue>
{
return bestIndex(0, list.Count);
int bestIndex(int s, int e) =>
s == e ? s :
selector(list[(s + e) / 2]).CompareTo(selector(value)) > 0
? bestIndex(s, (s + e) / 2)
: bestIndex((s + e) / 2 + 1, e);
}
}
</code></pre>
<p>To test:</p>
<pre><code> [TestMethod]
public async Task Keep_Three()
{
var values = new[] { 10, 22, 3, 55, 66, 100, 200, 2 };
var bottom = await values.ToAsyncEnumerable().Bottom(3, v => v).ToArrayAsync();
CollectionAssert.AreEqual(new int[] { 2, 3, 10 }, bottom);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T23:16:06.513",
"Id": "441023",
"Score": "4",
"body": "What is wrong about this question? It would be nice to write a comment after -1 :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T00:16:37.240",
"Id": "441025",
"Score": "5",
"body": "You should include more information about what this code is supposed to accomplish. I'm assuming the -1 is for the one sentence that fails to describe what this program is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T00:43:45.297",
"Id": "441029",
"Score": "0",
"body": "@Linny Thanks, updated :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:44:57.723",
"Id": "441043",
"Score": "0",
"body": "Yes, much better already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:54:54.327",
"Id": "441061",
"Score": "0",
"body": "@t3chb0t so how will you tackle this one? :p Didn't Henrik Hansen ask a similar question once?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:02:14.717",
"Id": "441062",
"Score": "1",
"body": "@dfhwze I wonder that there is actually only one `=>`... this code could be definitely made harder to read :-] but I love the magic _jambo_ ternary operators. This is another Code Golf like question :-[ I would never let this into production."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:11:39.760",
"Id": "441063",
"Score": "1",
"body": "Why don't you call this method something like `LazyOrderBy` or `OrderByAsync` or `LazyOrderByAsync` etc. Admit, you gave it the name `Bottom` to make it more confusing for the user ;-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:59:37.997",
"Id": "441069",
"Score": "0",
"body": "@t3chb0t It does not sort the whole collection - it keeps in memory only best n elements. It is also not so `lazy` - the entire source is being processed. 'Top N' and 'Bottom N' are well known terms in DB world as well as data science of all kind."
}
] |
[
{
"body": "<h1><code>where TValue : IComparable<TValue></code></h1>\n\n<p>Don't do this. <code>OrderBy</code> doesn't require its type parameters to implement this interface like this either. Instead it uses the <code>IComparer<T></code> interface. What's the difference? With <code>IComparable<T></code>, the implementation of the comparison logic is sitting on the class <code>T</code> itself. This means that there is one and only one way of ordering elements of <code>T</code>. If I wanted to sort them using some customized logic, I would be out of luck.</p>\n\n<p>Instead, <code>IComparer<T></code> is a separate class that compares <code>T</code>s. Providing an instance of that interface to the method allows me to use whatever logic I want to order <code>T</code>.</p>\n\n<p>But what if I don't want to implement an entire class, but instead want to use <code>IComparable<T></code>? This is where <code>Comparer<T>.Default</code> comes to play. This static property provides a default implementation for <code>IComparer<T></code> for <code>T</code>, which, if <code>T</code> implements <code>IComparable<T></code>, will default to call that logic.</p>\n\n<p>So how would your interface look? We have an overload with the <code>IComparer<TValue></code> argument, and an overload without:</p>\n\n<pre><code>public static async IAsyncEnumerable<T> Bottom<T, TValue>(\n this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector, IComparer<TValue> comparer)\n{\n return Bottom(source, number, selector, Comparer<TValue>.Default);\n}\n\npublic static async IAsyncEnumerable<T> Bottom<T, TValue>(\n this IAsyncEnumerable<T> source, int number, Func<T, TValue> selector, IComparer<TValue> comparer)\n{\n // Actual implementation.\n}\n</code></pre>\n\n<h1>Binary tree</h1>\n\n<p>I think this problem would call for a binary tree, instead of a list that's sorted/ranked continuously. This would you can quickly check whether the item you are iterating would even be in the top-<code>number</code> of items in the collection, without having to add and subsequently having to remove it again. The downside is that C# doesn't have a built-in Binary Tree that isn't hidden within the <code>SortedX</code> collection set. These classes sadly require unique values in their collections, which isn't guaranteed here.</p>\n\n<p>Alternatively, if you can handle adding another few lines to your solution, you can check if the index returned by <code>BestIndex</code> is equal to <code>number</code>, and skip adding and removing it from the list if this is the case.</p>\n\n<h1>Code style</h1>\n\n<p>This needs to be said. Your code is really compact. It took me multiple reads to figure out what on earth <code>BestIndex</code> was actually doing. Docstrings, comments and/or intermediate variables with clear names please. Something as simple as \"Returns the rank of <code>value</code> in the list by performing a merge-sort style algorithm.\" is enough to understand its role in <code>Bottom</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:17:36.833",
"Id": "441094",
"Score": "0",
"body": "Would you think there is a case for using a _Func<TValue, TValue, int>_ instead of _IComparer<TValue>_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T10:53:46.960",
"Id": "441113",
"Score": "1",
"body": "@dfhwze well, you could implement it like that, but I'd say this is more intuitive, since it matches the other `Linq` and collections API."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:02:26.477",
"Id": "226824",
"ParentId": "226801",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226824",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T23:07:25.380",
"Id": "226801",
"Score": "3",
"Tags": [
"c#",
"sorting",
"linq",
"async-await",
"extension-methods"
],
"Title": "LINQ for extracting N bottom items (async streams)"
}
|
226801
|
<p><code>Permutate()</code> is supposed to generate all possible permutations of the source sequence:</p>
<pre><code>foreach(var s in "abc".Permutate())
Console.WriteLine(s); // abc
// acb
// bac
// bca
// cab
// cba
</code></pre>
<p>Where:</p>
<pre><code> public static IEnumerable<string> Permutate(this string source) =>
source.AsEnumerable().Permutate().Select(a => new string(a));
public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> source)
{
return permutate(source, Enumerable.Empty<T>());
IEnumerable<T[]> permutate(IEnumerable<T> reminder, IEnumerable<T> prefix) =>
!reminder.Any() ? new[] { prefix.ToArray() } :
reminder.SelectMany((c, i) => permutate(
reminder.Take(i).Concat(reminder.Skip(i+1)).ToArray(),
prefix.Append(c)));
}
</code></pre>
<p>Any optimizations? Could it be shorter?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:03:21.260",
"Id": "441040",
"Score": "0",
"body": "Would _List_ be a better class for performance in the local function? _AddRange_ instead of _Concat_ and _Add_ instead of _Append_ seem like optimisations, but it should be benchmarked. And you'll lose precious code compactness o_O"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:29:19.657",
"Id": "441042",
"Score": "4",
"body": "You ask interesting questions but the way you format the code is virtually incomprihensible ;-P Using `=>` greatly hurts readability here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:23:20.527",
"Id": "441056",
"Score": "2",
"body": "Another possible optimization would be a custom `Skip` extension. I'm not sure you remember... but the built-in one doesn't recognize `IList` so it always enumerates from the beginning. I use `SkipFast` where this matters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:23:57.323",
"Id": "441072",
"Score": "2",
"body": "We do not add updated code to the question... please turn it into a self-answer... otherwise a rollback is on its way ;-] (keep in mind that we'll need a summary of changes too)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:28:20.280",
"Id": "441074",
"Score": "2",
"body": "@t3chb0t Rolled back. The revision history contains the updated code, if you wish to make a self-answer instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T13:44:25.713",
"Id": "441139",
"Score": "0",
"body": "A little longer, but I wrote one a ways back: https://stackoverflow.com/a/15150493/3312"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T02:11:45.813",
"Id": "441245",
"Score": "1",
"body": "Hey man, all code-hate aside, i love using => ultra condensed code. I think it's super clean, and in most cases actually easier to follow. The only optimization that i know off hand is not calling the LINQ functions, breaking it into raw code with no function, but i doubt it would be worth it unless you permuting massive multidimensional arrays."
}
] |
[
{
"body": "<p>Using line breaks and <code>{}</code> in code is not a crime :-P Only because we have the nice <code>=></code> doesn't mean we have to use it <strong>everywhere</strong>. The code is so condensed that it's hard to say where anything begins and ends.</p>\n\n<p>I find you should first try to write this function in such a way that it is easy to read and one can see what and where could be optimized.</p>\n\n<p>So, I think in this case the <code>Permutate</code> extension would benefit from the query syntax and two <code>let</code> <em>helpers</em>. This would shorten the calls and make it also easier to format and read. Now we can try to use @dfhwze suggestions.</p>\n\n<p>How about this?</p>\n\n<pre><code>public static IEnumerable<string> Permutate(this string source)\n{\n return\n source\n .AsEnumerable() // <-- not necessary, string is already IEnumerable<char>\n .Permutate()\n .Select(a => new string(a));\n}\n\npublic static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> source)\n{\n return permutate(source, Enumerable.Empty<T>());\n\n IEnumerable<T[]> permutate(IEnumerable<T> reminder, IEnumerable<T> prefix)\n {\n if (reminder.Any())\n {\n return\n from t in reminder.Select((r, i) => (r, i))\n let nextReminder = reminder.Take(t.i).Concat(reminder.Skip(t.i + 1)).ToArray()\n let nextPrefix = prefix.Append(t.r)\n from permutation in permutate(nextReminder, nextPrefix)\n select permutation;\n\n }\n else\n {\n return new[] { prefix.ToArray() };\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:04:18.700",
"Id": "441049",
"Score": "0",
"body": "`AsEnumerable()` helps preventing `Permutate(this string source)` to call itself instead of `Permutate<T>(this IEnumerable<T> source)`. And I personally spend more time reading longer code than a shorter one - FP programming can be very different stylistically from an imperative approach. Your version of code does not look like FP - it is a way more verbose as a typical imperative code will be for sure :) Good examples to compare would be [Scala](https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#Scala) and [C#](https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#C.23)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:10:32.120",
"Id": "441052",
"Score": "0",
"body": "@DmitryNogin I like functional style too but using this style just for the sake of using it does more harm than good. We have the luxary to pick a style that better suites the current situation. Since C# is not pure functional, it consequently does not always results in _nice_ code which this code is a good example of."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:16:53.460",
"Id": "441053",
"Score": "0",
"body": "@DmitryNogin well, the comparison between Scala and C# is unfair. In scala they've just implemented the pure algorithm which would most probably fit into an extension like yours but instead, they've build an entire module with properties, validations, argument checking etc etc. I'm not really sure what is the point of these examples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:19:35.917",
"Id": "441054",
"Score": "0",
"body": "@DmitryNogin have you considered writing such utilities in F#? I bet it would satisfy both your functional needs and my good taste of code ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:19:38.283",
"Id": "441055",
"Score": "1",
"body": "I can't find an intersection for these questions: (1) _Any optimizations?_ (2) _Could it be shorter?_ Each of these questions deserves a completely different answer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:43:44.033",
"Id": "226813",
"ParentId": "226804",
"Score": "7"
}
},
{
"body": "<p>You did also ask for a shortened version. I believe readability should not be a concern here (meaning the code should aim at being functional, not readable). Remove the local recursive function and allow the public API to have an optional parameter.</p>\n\n<pre><code>public static IEnumerable<T[]> Permutate<T>(\n this IEnumerable<T> source, IEnumerable<T> prefix = null) => \n !source.Any() ? new[] { (prefix ?? Enumerable.Empty<T>()).ToArray() } :\n source.SelectMany((c, i) =>\n source.Take(i).Concat(source.Skip(i+1)).ToArray().Permutate(\n prefix.Append(c)));\n</code></pre>\n\n<p><sup>use in production code at own risk :-)</sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:36:00.590",
"Id": "441057",
"Score": "2",
"body": "this'll be the first time where I don't agree. The ternary operator is barely visible and the optional parameter just makes me scratch my head asking myself what do they need from me here? :-\\ you could name it `placebo` or like in the emails `do_not_use_this_argument` :-P similar to _no-replay_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:40:22.833",
"Id": "441059",
"Score": "2",
"body": "As pointed out, the shortened version has nothing to do with readability, and I would never use it in production code. But it provides a solution only using functional programming (no additional statements with _;_ delimited) which is what OP requested. It's more of a Code Golf answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:47:12.610",
"Id": "441060",
"Score": "1",
"body": "ok, now with the mini-comment, I can +1 it ;-]"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:30:47.750",
"Id": "226815",
"ParentId": "226804",
"Score": "4"
}
},
{
"body": "<h3>English language</h3>\n\n<p>These are relatively minor issues, but fixing them might help other people to use / maintain your code.</p>\n\n<ol>\n<li>The verb corresponding to <em>permutation</em> is <em>permute</em>.</li>\n<li>I'm pretty sure that <code>reminder</code> is intended as <code>remainder</code>.</li>\n</ol>\n\n<h3>Code</h3>\n\n<blockquote>\n<pre><code> public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> source)\n {\n return permutate(source, Enumerable.Empty<T>());\n IEnumerable<T[]> permutate(IEnumerable<T> reminder, IEnumerable<T> prefix) =>\n !reminder.Any() ? new[] { prefix.ToArray() } :\n reminder.SelectMany((c, i) => permutate(\n reminder.Take(i).Concat(reminder.Skip(i+1)).ToArray(),\n prefix.Append(c)));\n }\n</code></pre>\n</blockquote>\n\n<p>To return a permutation of <code>source</code> it is necessary to find all of the elements of <code>source</code>, so I think this is a case where the first thing the method should do is to fully evaluate <code>source</code> (e.g. with <code>ToList()</code> or <code>ToArray()</code>), and then work with that list rather than <code>source</code>. Apart from the efficiency benefits, that guarantees that all of the permutations will be permutations of the same size and elements, even if <code>source</code> has side-effects.</p>\n\n<p>There are a couple of things you can then do with a list to make it much more efficient. Either you can use a standard \"next permutation\" algorithm (<a href=\"https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order\" rel=\"noreferrer\">see Wikipedia</a>: for arbitrary inputs it can be done by permuting an array of integers and copying the operations on the array of <code>T</code>) or you can recursively select an element from the first <code>k</code>, swap it to position <code>k</code>, recurse on <code>k-1</code>, and then swap it back. When <code>k==0</code> you instead copy the entire array and yield the copy. This avoids building up chains of <code>Append</code> and the overheads of <code>Take</code>/<code>Skip</code>/<code>Concat</code>. I expect that the most efficient would be the \"next permutation\" approach, because it is non-recursive and so doesn't wrap coroutine in coroutine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:27:06.373",
"Id": "226816",
"ParentId": "226804",
"Score": "10"
}
},
{
"body": "<p>An updated version, please see an accepted answer for details.</p>\n\n<pre><code>public static IEnumerable<string> Permute(this string source) =>\n source.AsEnumerable().Permute().Select(a => new string(a));\n\npublic static IEnumerable<T[]> Permute<T>(this IEnumerable<T> source)\n{\n return permute(source.ToArray(), Enumerable.Empty<T>());\n IEnumerable<T[]> permute(IEnumerable<T> remainder, IEnumerable<T> prefix) =>\n !remainder.Any() ? new[] { prefix.ToArray() } :\n remainder.SelectMany((c, i) => permute(\n remainder.Take(i).Concat(remainder.Skip(i+1)).ToArray(),\n prefix.Append(c)));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:43:33.490",
"Id": "441077",
"Score": "0",
"body": "mhmm... the only difference I can see is `Permutate` became `Permute` - I'm not sure this is worth posting :-\\ have you possibly posted the wrong code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:54:43.360",
"Id": "441081",
"Score": "1",
"body": "@t3chb0t, there's also a `ToArray()` in line 6. It's not a wholehearted acceptance of my advice, but it is less buggy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:57:34.557",
"Id": "441082",
"Score": "2",
"body": "@t3chb0t Permute, remainder, source.ToArray(). P. S. Intensively looking for a new interesting job - here comes a lot of interview preparation questions adapted to FP, some snippets could be useful latter to copy/paste, so trying to have a clean version ready :) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T19:11:45.703",
"Id": "441220",
"Score": "0",
"body": "Comments are not for extended discussion, let alone for soliciting job interviews and well-meaning banter. For that purpose there's [chat]. Please use it. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:27:40.713",
"Id": "226821",
"ParentId": "226804",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226816",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T01:18:14.417",
"Id": "226804",
"Score": "6",
"Tags": [
"c#",
"linq",
"combinatorics",
"extension-methods"
],
"Title": "LINQ for generating all possible permutations"
}
|
226804
|
<p>I completed an algorithm problem just as a personal study, and I can't help but feel like my solution is a bit needlessly complicated, although I can't figure out a better way to do it. Here's the problem : </p>
<blockquote>
<p>Given a number N, and a list of users currently on a stage, find out the failure rate of each stage up to N, and list the stages in descending order of failure rate. The failure rate is the percentage of users currently stuck on a stage, out of all the users who are currently playing the current stage or higher.</p>
</blockquote>
<p>Example :
<code>stages = [2, 1, 2, 6, 2, 4, 3, 3], N = 5</code></p>
<ul>
<li>There is 1 user currently playing stage 1, therefore out of the list of 8 users playing stage 1 or higher the failure rate of stage 1 is 1/8.</li>
<li>There are 3 users currently playing stage 2, therefore out of 7 users playing stage 2 or higher the failure rate is 3/7.</li>
<li>There are 2 users currently playing stage 3, therefore out of 4 users playing stage 3 or higher the failure rate is 2/4.</li>
<li>There is 1 user currently playing stage 4, therefore out of 2 users playing stage 4 or higher the failure rate is 1/2.</li>
<li>There are 0 users currently playing stage 5, therefore out of 1 users playing stage 5 or higher the failure rate is 0/1.</li>
</ul>
<p>Therefore the result is : <code>[3, 4, 2, 1, 5]</code></p>
<p>My solution : </p>
<pre><code>public class StageFailureRate {
private ArrayList<Integer> result;
public StageFailureRate(int N, Integer[] stages) {
result = new ArrayList<>();
Map<Integer, Integer> usersOnStage = new HashMap<>();
//count how many users are on each stage
for (int stage : stages) {
if (!usersOnStage.containsKey(stage)) {
usersOnStage.put(stage, 1);
} else {
usersOnStage.put(stage, usersOnStage.get(stage) + 1);
}
}
//compute the failure rate for each stage, up to N stages
int total = stages.length;
Map<Integer, Float> failureRates = new HashMap<Integer, Float>();
float failureRate = 0;
for (int i = 1; i <= N; ++i) {
if (usersOnStage.containsKey(i)) {
failureRate = (float) usersOnStage.get(i) / (float) total;
total = total - usersOnStage.get(i);
} else {
failureRate = 0 / total;
}
failureRates.put(i, failureRate);
}
//Sort into descending order and get the result.
Map<Integer, Float> sortedMap = sortByValue(failureRates);
for (Map.Entry<Integer, Float> entry : sortedMap.entrySet()) {
result.add(entry.getKey());
}
}
public ArrayList<Integer> getResult() {
return result;
}
private static Map<Integer, Float> sortByValue(Map<Integer, Float> unsortedMap) {
List<Map.Entry<Integer, Float>> list =
new LinkedList<Map.Entry<Integer, Float>>(unsortedMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Float>>() {
public int compare(Map.Entry<Integer, Float> o1,
Map.Entry<Integer, Float> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
Map<Integer, Float> sortedMap = new LinkedHashMap<Integer, Float>();
for (Map.Entry<Integer, Float> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
</code></pre>
<p>This solution is correct. Do you think it's the most optimal solution or could this be optimized to be much faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T06:08:48.743",
"Id": "441051",
"Score": "0",
"body": "Did you try to sort `stages` and see what happen?"
}
] |
[
{
"body": "<ol>\n<li><p>you should define <code>float failureRate = 0;</code> inside the <code>for (int i = 1; i <= N; ++i)</code> loop, because you are not using it outside the loop. See <a href=\"https://stackoverflow.com/questions/7959573/declaring-variables-inside-loops-good-practice-or-bad-practice\">this</a> for more info.</p></li>\n<li><p>When you calculate <code>failureRate</code>, just cast one of <code>usersOnStage.get(i)</code> or <code>total</code> to float. You don't need to cast both.</p></li>\n<li><p><code>else {failureRate = 0 / total;}</code> is redundant because you'll always set failureRate to 0, which is its default value.</p></li>\n</ol>\n\n<p>As for optimization to make it faster, since this piece of code is likely to be used in a video game, <code>stages</code> should be a small list, where efficiency of the algorithm doesn't matter much. You'd probably want to use simpler data structures, for a smaller overhead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:34:03.523",
"Id": "226818",
"ParentId": "226807",
"Score": "2"
}
},
{
"body": "<p>I made some modifies to your code focusing on simplify the code you posted starting from the signature of the constructor <code>public StageFailureRate(int N, Integer[] stages)</code>, better to use <code>public StageFailureRate(int N, int[] stages)</code> because in the body of the constructor you never use <code>the ArrayList</code> methods.\nInstead of</p>\n\n<pre><code>for (int stage : stages) {\n if (!usersOnStage.containsKey(stage)) {\n usersOnStage.put(stage, 1);\n } else {\n usersOnStage.put(stage, usersOnStage.get(stage) + 1);\n }\n}\n</code></pre>\n\n<p>You can omit the <code>if else</code> and write:</p>\n\n<pre><code>for (int stage : stages) {\n int count = usersOnStage.containsKey(stage) ? usersOnStage.get(stage) : 0;\n usersOnStage.put(stage, count + 1);\n}\n</code></pre>\n\n<p>You can convert <code>total = stages.length</code> to <code>float</code> and rewrite the calculus cycle in this way:</p>\n\n<pre><code>float total = stages.length;\nMap<Integer, Float> failureRates = new HashMap<Integer, Float>();\n\nfor (int i = 1; i <= N; ++i) {\n float failureRate = 0;\n if (usersOnStage.containsKey(i)) {\n failureRate = usersOnStage.get(i) / total;\n total -= usersOnStage.get(i);\n } \n failureRates.put(i, failureRate);\n}\n</code></pre>\n\n<p>The method <code>sortByValues</code> can be simplified using java streams and you can write it in this way:</p>\n\n<pre><code>private Map<Integer, Float> sortByValue(Map<Integer, Float> map) {\n Map<Integer, Float> reverseSortedMap = new LinkedHashMap<>();\n map \n .entrySet()\n .stream()\n .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) \n .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));\n return reverseSortedMap;\n}\n</code></pre>\n\n<p>Now you can rewrite the end of your constructor:</p>\n\n<pre><code>Map<Integer, Float> sortedMap = sortByValue(failureRates);\nSet<Integer> keys = sortedMap.keySet();\nfor (Integer key : keys) {\n result.add(key);\n}\n</code></pre>\n\n<p>Above the code of the class modified:</p>\n\n<p><strong>StageFailureRate.java</strong></p>\n\n<pre><code>package stackoverflow;\n\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class StageFailureRate {\n private List<Integer> result;\n\n public StageFailureRate(int N, int[] stages) {\n result = new ArrayList<>();\n Map<Integer, Integer> usersOnStage = new HashMap<>();\n\n //count how many users are on each stage\n for (int stage : stages) {\n int count = usersOnStage.containsKey(stage) ? usersOnStage.get(stage) : 0;\n usersOnStage.put(stage, count + 1);\n }\n\n\n //compute the failure rate for each stage, up to N stages\n float total = stages.length;\n Map<Integer, Float> failureRates = new HashMap<Integer, Float>();\n\n for (int i = 1; i <= N; ++i) {\n float failureRate = 0;\n if (usersOnStage.containsKey(i)) {\n failureRate = usersOnStage.get(i) / total;\n total -= usersOnStage.get(i);\n } \n failureRates.put(i, failureRate);\n }\n\n //Sort into descending order and get the result.\n Map<Integer, Float> sortedMap = sortByValue(failureRates);\n\n Set<Integer> keys = sortedMap.keySet();\n for (Integer key : keys) {\n result.add(key);\n }\n\n }\n\n private Map<Integer, Float> sortByValue(Map<Integer, Float> map) {\n Map<Integer, Float> reverseSortedMap = new LinkedHashMap<>();\n map \n .entrySet()\n .stream()\n .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) \n .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));\n return reverseSortedMap;\n }\n\n public List<Integer> getResult() {\n return result;\n }\n\n\n public static void main(String[] args) {\n int[] stages = {2, 1, 2, 6, 2, 4, 3, 3};\n int N = 5;\n StageFailureRate rate = new StageFailureRate(N, stages);\n System.out.println(rate.getResult());\n }\n}\n</code></pre>\n\n<p>I preferred not modify all the methods of your class , normally in the constructor is always preferred just to initialize fields of the class, computations like <code>result</code> are encapsulated in <code>static</code> methods or at least outside constructor.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T13:05:00.370",
"Id": "226838",
"ParentId": "226807",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T02:40:41.140",
"Id": "226807",
"Score": "5",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"dynamic-programming"
],
"Title": "Calculate the rates at which users get stuck at each stage"
}
|
226807
|
<p>This code works as it is intended. What I seek is a feedback on the quality of my code. Where should I have written it differently or how should have I approached instead of the way that I have?</p>
<p>These functions will be moved to a separate file to be used on other pages as well. My goal is to have this code reusable as well.</p>
<p>I tried using <code>onMouseOver={ani.bind(this)}</code></p>
<p>I've also tried <code>let element = ani()</code> but received undefined</p>
<p><code><img className="gPic" src={img['roofRepair1'].src} alt={img['roofRepair1'].alt} id="special" onMouseOver={ani} onMouseLeave={revani}/></code></p>
<pre class="lang-js prettyprint-override"><code>//Function anime: Anime.js
function ani(p){
let element = p.target.id
anime({
targets: '#'+ element,
scale: 2,
})
return element;
}
function revani(p){
let element = p.target.id
anime({
targets:'#'+ element,
scale: 1
})
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T04:55:22.243",
"Id": "441039",
"Score": "0",
"body": "Welcome to Code Review. This code is much to sketchy for us to give you proper advice. Ideally, you should press Control-M in the question editor to make a working demonstration. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T05:58:11.547",
"Id": "441048",
"Score": "0",
"body": "_My goal is to have this code reusable as well._ -> each attempt you tried so far failed _but received undefined_. Is the code really working as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:50:11.813",
"Id": "441068",
"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": "2019-08-26T16:45:40.150",
"Id": "441178",
"Score": "0",
"body": "The title might be better as Animations using JavaScript. The question would be better if you added an explanation of what the code is animating and provided some working examples."
}
] |
[
{
"body": "<p>You can reduce this code down to one function by using <a href=\"https://en.wikipedia.org/wiki/Default_argument\" rel=\"nofollow noreferrer\">default arguments</a>.</p>\n\n<pre><code>function ani(p, reverse=false){\n let element = p.target.id;\n let scale = 2;\n if (reverse)\n scale = 1;\n anime({\n targets: '#'+ element,\n scale: scale,\n })\n return element;\n}\n</code></pre>\n\n<p>Also, don't forget your semicolons ;-P</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T03:28:17.413",
"Id": "226809",
"ParentId": "226808",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "226809",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T03:17:33.023",
"Id": "226808",
"Score": "0",
"Tags": [
"javascript",
"react.js"
],
"Title": "Code Improvement/Insight: Should I have approached these functions differently? Animations using Javascript"
}
|
226808
|
<p>I'm still new in javascript and learning. I want to create a date picker using html and javascript. Below is what I have tried and it's working, so my question is "how can I do it better?" My idea is to create a custom tag in HTML and allow multiple of these tags. The javascript part will then handle the build and functionality of all the custom tags. Like I said it is working, I just want to get some feedback to help making it better.</p>
<p>I have done everything, The HTML and javascript and both are working. See below my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let currentDate = new Date();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
let months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October","November", "December"];
let daysOfTheMonth = ["S","M","T","W","T","F","S"];
var datePickers = document.getElementsByTagName("datePicker");
class Calendar {
constructor(id,year, month) {
this.id = id,
this.year = year,
this.month = month,
this.header = months[this.month] + " " + this.year;
}
previous(calendarBody,calendarHeader,mainHeader){
this.year = (this.month === 0) ? this.year - 1 : this.year;
this.month = (this.month === 0) ? 11 : this.month - 1;
this.update(calendarBody,calendarHeader,mainHeader)
}
next(calendarBody,calendarHeader,mainHeader) {
this.year = (this.month === 11) ? this.year + 1 : this.year;
this.month = (this.month + 1) % 12;
this.update(calendarBody,calendarHeader,mainHeader)
}
selectDate(date){
let year = this.year;
let month = this.month;
let newDate = new Date(year, month, date)
const newMonth = newDate.toLocaleString('default', { month: 'short' });
var dayName = newDate.toString().split(' ')[0];
document.getElementById("topHeader_"+ this.id).innerHTML = dayName+", "+ newMonth + " "+ date
document.getElementById("input_"+ this.id).value = formatDate(newDate)
}
update(calendarBody,calendarHeader,mainHeader){
let month = currentDate.toLocaleString('default', { month: 'short' });
let dayName = currentDate.toString().split(' ')[0];
mainHeader.innerHTML = dayName+", "+ month + " " + currentDate.getDate();
calendarHeader.innerHTML = months[this.month] + " " + this.year;
calendarBody.innerHTML = "";
let firstDay = (new Date(this.year, this.month)).getDay();
let daysInMonth = 32 - new Date(this.year, this.month, 32).getDate();
let date = 1;
for (let i = 0; i < 6; i++) {
let row = document.createElement("tr");
for (let j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
let cell = document.createElement("td");
cell.innerHTML = ""
row.appendChild(cell);
}
else if (date > daysInMonth) {
break;
}
else {
let vm = this;
let cell = document.createElement("td");
let button = document.createElement("button");
button.innerHTML = date;
cell.appendChild(button);
button.addEventListener('click',function(e){
vm.selectDate(e.target.innerHTML);
});
if (date === currentDate.getDate() && this.year === currentDate.getFullYear() && this.month === currentDate.getMonth()) {
cell.classList.add("today");
}
row.appendChild(cell);
date++;
}
}
calendarBody.appendChild(row);
}
}
createPicker(datePicker){
let vm = this;
let mainHeader = document.createElement("div");
mainHeader.setAttribute("id", "topHeader_"+ vm.id)
mainHeader.classList.add("topHeader");
mainHeader.innerHTML = vm.header;
let calendar = document.createElement("div");
calendar.setAttribute("id", "calendar_"+vm.id);
calendar.setAttribute("class", "calendar");
calendar.style.display = "none";
calendar.appendChild(mainHeader);
let input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", "input_"+ vm.id);
input.setAttribute("tagName", "input");
input.setAttribute("class", "datePickerInput");
input.setAttribute("calendar", "calendar_"+vm.id);
input.setAttribute("placeholder", "Select a date");
datePicker.appendChild(input);
let calendarHeaderContainer = document.createElement("div");
let prevButton = document.createElement("button");
prevButton.setAttribute("id", "prevButton_"+vm.id);
prevButton.innerHTML = "<";
let nextButton = document.createElement("button");
nextButton.setAttribute("id", "nextButton_"+vm.id);
nextButton.innerHTML = ">";
calendarHeaderContainer.appendChild(prevButton);
let calendarHeader = document.createElement("div");
calendarHeader.setAttribute("id", "calendar_header_"+vm.id);
calendarHeader.setAttribute("class", "calendar_header");
calendarHeader.innerHTML = vm.header;
calendarHeaderContainer.appendChild(calendarHeader);
calendarHeaderContainer.appendChild(nextButton);
let calendarTable = document.createElement("table");
calendarTable.setAttribute("id", "calendar_body_"+vm.id);
let calendarTableBody = calendarTable.createTBody();
let calendarTableHeader = calendarTable.createTHead();
calendarTableHeader.classList.add("daysOfTheMonth");
let row = document.createElement("tr");
for (let j = 0; j < daysOfTheMonth.length; j++) {
let cell = document.createElement("td");
cell.innerHTML = daysOfTheMonth[j];
row.appendChild(cell);
}
calendarTableHeader.appendChild(row);
this.update(calendarTableBody,calendarHeader,mainHeader)
calendar.appendChild(calendarHeaderContainer);
calendar.appendChild(calendarTable);
datePicker.appendChild(calendar);
input.addEventListener('click',function(e){
let calendar = document.getElementById(this.getAttribute("calendar"));
if(calendar.style.display === "none"){
calendar.style.display = "block"
}else{
calendar.style.display = "none"
}
});
nextButton.addEventListener('click',function(e){
vm.next(calendarTableBody,calendarHeader,mainHeader);
});
prevButton.addEventListener('click',function(e){
vm.previous(calendarTableBody,calendarHeader,mainHeader);
});
}
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
for ( var x = 0; x < datePickers.length; x++) {
var calendar = new Calendar(x, currentYear, currentMonth);
calendar.createPicker(datePickers[x])
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.calendar {
width: 250px;
background: gainsboro;
border-radius: 5px;
}
.calendarHeaderContainer {
display: flex;
justify-content: space-between;
align-items: center;
}
.topHeader {
font-size: 20px;
background: #03A9F4;
padding: 10px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
/*Button Reset*/
button {
background: none;
border: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Date Picker</h1>
<datePicker></datePicker></code></pre>
</div>
</div>
</p>
<p>One thing I do want to know is: I want to return the selected date for each picker and it also has to be by the id of the picker so you know what date goes where.</p>
<p>Thanks again, everyone.</p>
|
[] |
[
{
"body": "<p>You probably are familiar with <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date\" rel=\"nofollow noreferrer\"><code><input type=\"date\"></code></a> but maybe you aren't satisfied by the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date#Browser_compatibility\" rel=\"nofollow noreferrer\">browser compatibility</a> or wanted to try your hand at <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged 'reinventing-the-wheel'\" rel=\"tag\">reinventing-the-wheel</a>.</p>\n\n<p>Instead of creating numerous HTML elements with the Javascript Logic, have you considered using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\" rel=\"nofollow noreferrer\"><code><template></code></a> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot#\" rel=\"nofollow noreferrer\"><code><slot></code></a> tags and replacing values as needed.</p>\n\n<p>Also, I see many variables declared with <code>let</code> but only one with <code>const</code> (i.e. <code>newMonth</code>). It is wise to use <code>const</code> as a default and then when it is determined that re-assignment is necessary switch to <code>let</code>.</p>\n\n<p>Instead of assigning a reference to <code>this</code> in <code>vm</code> use arrow functions (because there would be no separate <code>this</code> context) or else set the context of those anonymous functions to <code>this</code> using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind()</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-03T05:48:56.563",
"Id": "442511",
"Score": "0",
"body": "Sam Thank you so much for this advice i will def keep that in mind. Great great advice. I will def try to use template tags think that is the best way to go"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-02T03:21:48.290",
"Id": "227294",
"ParentId": "226817",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:30:33.220",
"Id": "226817",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"html",
"ecmascript-6"
],
"Title": "JavaScript HTML DatePicker"
}
|
226817
|
<p><code>Make()</code> takes projects with a list of tuples representing project references in the form of <code>(Dependency, Dependent)</code> and returns projects in the order to be build:</p>
<pre><code>static void Main(string[] args)
{
var projects = new[] { "a", "b", "c", "d", "e", "f" };
var dependencies = new[] { ("a", "b"), ("a", "c"), ("e", "f"), ("c", "f"), ("f", "d") };
Console.WriteLine(
string.Join(", ", Make(projects, dependencies))); // a, e, b, c, f, d
}
</code></pre>
<p>Where:</p>
<pre><code>static IEnumerable<string> Make(
IEnumerable<string> projects,
IEnumerable<(string Dependency, string Dependent)> references)
{
var dependents = new HashSet<string>(references.Select(d => d.Dependent));
var build = new HashSet<string>(projects.Except(dependents));
return
!projects.Any() ? Enumerable.Empty<string>() :
!build.Any() ? throw new Exception("Circled references detected.") :
build.Concat(Make(
projects.Except(build).ToArray(),
references.Where(r => !build.Contains(r.Dependency)).ToArray()));
}
</code></pre>
<p>What about run-time complexity of this one? Could it be optimized?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:06:32.397",
"Id": "441070",
"Score": "0",
"body": "I looks like there is already an _official_ algorithm for that. See [Nikita B's answer](https://codereview.stackexchange.com/a/156610/59161) to a similar question of mine. However, not so compact. Although I think it could be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:12:58.627",
"Id": "441071",
"Score": "2",
"body": "@t3chb0t Yep, I just tried to be immutable and as concise as possible (as usual :), it is almost the same. There is one in [Cracking coding interview](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850) on page 250 (common, everybody has this book :) - but there it looks really, really scary :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:51:51.307",
"Id": "441078",
"Score": "1",
"body": "You probably should add a notice in your questions that reviews should favor functional solutions ;-)"
}
] |
[
{
"body": "<h1>Exit early</h1>\n\n<p>Instead of stuffing everything in one return statements, return as early as possible.</p>\n\n<pre><code>if (!projects.Any()) return Enumerable.Empty<string>();\n</code></pre>\n\n<p>can be the first statement of your method. It saves recreating the hashset objects and it makes the flow of your method with its recursion more clear. I think sacrificing a bit of \"conciseness\" for readability is worth it. </p>\n\n<h1><code>ToArray</code></h1>\n\n<p>Are unnecessary and cause additional loops over your sets.</p>\n\n<h1><code>Except</code> and <code>HashSet</code></h1>\n\n<p><code>Enumerable.Except</code> is already implemented using sets. The second argument is added to a set and the first is streamed through it. Creating the <code>HashSet</code> manually is a wasted effort. See <a href=\"https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,899\" rel=\"noreferrer\">the reference source.</a></p>\n\n<p>So <code>dependents</code> can just be:</p>\n\n<pre><code>var dependents = references.Select(d => d.Dependent);\n</code></pre>\n\n<h1><code>Contains</code> and <code>HashSet</code></h1>\n\n<p><code>Contains</code> on the other hand benefits from the <code>HashSet</code> overload, since the <code>Enumerable.Contains</code> implementation just loops over the sequence. So <code>build</code> should be a <code>HashSet</code> to cope with larger inputs. While we're at it, we're using <code>Linq</code>, so <code>ToHashSet</code>().</p>\n\n<pre><code>static IEnumerable<string> Make(\n IEnumerable<string> projects,\n IEnumerable<(string Dependency, string Dependent)> references)\n{\n if (!projects.Any())\n {\n return Enumerable.Empty<string>();\n }\n var dependents = references.Select(d => d.Dependent);\n var build = projects.Except(dependents).ToHashSet();\n if (!build.Any())\n {\n throw new Exception(\"Circled references detected.\");\n }\n else\n {\n return build.Concat(Make(\n projects.Except(build),\n references.Where(r => !build.Contains(r.Dependency))));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:46:56.723",
"Id": "226822",
"ParentId": "226819",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "226822",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:39:30.480",
"Id": "226819",
"Score": "5",
"Tags": [
"c#",
"functional-programming",
"linq"
],
"Title": "Make utility using LINQ"
}
|
226819
|
<p>I have an algorithm that performs the base conversion. The input is a string and two ints b1 and b2. The string represents an int in base b1 and converts it into base in b2.</p>
<p>My code is:</p>
<pre><code>def convert_base(num_as_string, b1, b2):
if num_as_string == '0' or num_as_string == '-0':
return num_as_string
base10, degree = 0, 0
is_neg = False
if num_as_string[0] == '-':
is_neg, num_as_string = True, num_as_string[1:]
if b1 == 10:
base10 = int(num_as_string)
else:
for digit in num_as_string[::-1]:
base10 += string.hexdigits.index(digit.lower()) * (b1 ** degree)
degree += 1
if b2 == 10:
return '-' + str(base10) if is_neg else str(base10)
converted = []
while base10 > 0:
digit = base10 % b2
converted.append(digit)
base10 //= b2
res = ''
for i in converted[::-1]:
res += string.hexdigits[i].upper()
return '-' + res if is_neg else res
</code></pre>
<p>Now I am trying to see if this can be improved in terms of time and space complexity. But I am not sure how to analyze the complexity of this code.</p>
<p>I know everything is constant before <code>for digit in num_as_string[::-1]:</code>. In this loop, it's just `O(n) where n is just number of digits of the input. </p>
<p>Then in <code>while base10 > 0</code>, it runs the look while <code>base10</code> becomes 0. So, this would be something like <code>O(number of digits in base10)</code></p>
<p>Finally, on <code>for i in converted[::-1]</code>, this would also be <code>O(number of digits in base10)</code>.</p>
<p>So, I am assuming the time complexity of this code is something like <code>O(n) + 2 * O(number of digits in base10)</code> which is linear.</p>
<p>For space, I am assuming it's <code>O(number of digits in base10)</code> because I store it in <code>converted</code> list. </p>
<p>Are my observations correct? If not, what am I missing? Also, can this code be improved in terms of time and space complexity?</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:25:58.107",
"Id": "441073",
"Score": "0",
"body": "Just a quick question to check your goal here. Do you only want suggestions for your algorithm, or do you also want general programming advice (e.g. suggestions to use python's standard library for some of the base conversions)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:41:43.983",
"Id": "441076",
"Score": "0",
"body": "What happens if `b2` is, say, 20?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:06:27.660",
"Id": "441090",
"Score": "0",
"body": "@IvoMerchiers Just for my algorithm. This is a practice for a coding interview. @Mathias Ettinger Sorry. Forgot to mention that `b1` and `b2` is between 2 and 16"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T02:16:17.087",
"Id": "441247",
"Score": "0",
"body": "What if num_as_string starts with a '+' sign?"
}
] |
[
{
"body": "<p>Much of the following feedback is not really performance-related, but will make the code more easily legible and easily analyzed for the purposes of performance improvement.</p>\n\n<h2>Add type hints</h2>\n\n<p><code>b1</code> and <code>b2</code> are presumably <code>int</code>, so add <code>: int</code> after their declaration. <code>num_as_string</code> and the function's return value are both <code>str</code>.</p>\n\n<h2>Multiple assignment</h2>\n\n<p>...has its limited applications, and in this case:</p>\n\n<pre><code>is_neg, num_as_string = True, num_as_string[1:]\n</code></pre>\n\n<p>there's not really an advantage to combining these two statements. Just do them separately, for legibility.</p>\n\n<h2>Exponentiation</h2>\n\n<p>You do this:</p>\n\n<pre><code> base10 += string.hexdigits.index(digit.lower()) * (b1 ** degree)\n degree += 1\n</code></pre>\n\n<p>But rather than maintaining <code>degree</code> as a number that increases linearly, it's probably a better idea to maintain a number that increases by a multiplicative factor of <code>b1</code> on every iteration.</p>\n\n<h2>Separation of concerns</h2>\n\n<p>Fundamentally, <code>convert_base</code> is doing two different things: parsing a string given a particular base into a number, and formatting a number given a particular base into a string. So just make two functions. It's more useful, testable, legible and maintainable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T21:35:51.870",
"Id": "441237",
"Score": "0",
"body": "Thanks for the detailed answer. Do you think my analysis of the time and space complexity looks correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:37:13.053",
"Id": "441478",
"Score": "0",
"body": "Have a read through https://wiki.python.org/moin/TimeComplexity . `num_as_string[1:]` is not constant time, strictly-speaking; it's an O(k) \"get slice\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T02:39:48.493",
"Id": "441479",
"Score": "0",
"body": "Otherwise, refer to the other answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:34:55.497",
"Id": "226865",
"ParentId": "226820",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>... <code>for digit in num_as_string[::-1]:</code>. In this loop, it's just <span class=\"math-container\">\\$O(n)\\$</span> where n is just number of digits of the input.</p>\n<p>I am assuming the time complexity of this code is something like O(n) + 2 * O(number of digits in base10) which is linear.</p>\n</blockquote>\n<p>This is not quite right. The second and third loops will loop the number of digits <strong>in base <span class=\"math-container\">\\$b_2\\$</span></strong> (not in base 10), which is approximately <span class=\"math-container\">\\$n * \\frac {\\log b_1}{\\log b_2}\\$</span> times, so your time complexity would be:</p>\n<p><span class=\"math-container\">$$O(n) + 2 * \\frac{\\log b_1}{\\log b_2} * O(n)$$</span></p>\n<p>which is of course is still simply <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<p>This also means your space complexity is not "<em>O(number of digits in base10)</em>"; it is O(number digits in <span class=\"math-container\">\\$b_2\\$</span>), but again, these are constant factors, and becomes simply <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<p>Still, it is unusual to express it the complexity in terms of the number of digits of the input. Usually, you have an input value N, (which can be expressed in <span class=\"math-container\">\\$\\log_{b_1}N\\$</span> digits), and would express the complexity of the algorithm as <span class=\"math-container\">\\$O(\\log N)\\$</span>.</p>\n<hr />\n<h2>Except ...</h2>\n<pre><code>res = ''\nfor i in converted[::-1]:\n res += string.hexdigits[i].upper()\n</code></pre>\n<p>Which actually makes this an <span class=\"math-container\">\\$O(n^2)\\$</span> algorithm, since while you are looping, you are copying all previous digits to add one character. Convert all the digits into the appropriate character, and then join them all together at once:</p>\n<pre><code>res = ''.join(string.hexdigits[digit] for digit in converted[::-1]).upper()\n</code></pre>\n<hr />\n<p>Using <code>% b2</code> and <code>//= b2</code> back-to-back is generally inefficient. When the math library computes one, it almost always has computed the other as a side effect. The <code>divmod()</code> function returns both values:</p>\n<pre><code>while base10 > 0:\n base10, digit = divmod(base10, b2)\n converted.append(digit)\n</code></pre>\n<hr />\n<p>Practice for a coding interview? You'd better clean up this code considerably. In addition to @Reinderien's suggestions, look at your two <code>return</code> statements</p>\n<pre><code>return '-' + str(base10) if is_neg else str(base10)\nreturn '-' + res if is_neg else res\n</code></pre>\n<p>These look exactly the same, if <code>res = str(base10)</code>. Try to rework your code to handle the <code>is_neg</code> test only once, and only use 1 <code>return</code> statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T02:12:35.473",
"Id": "441246",
"Score": "0",
"body": "whenever I have timed it, separate `%=` and `//=` statements have been faster than a `divmod` call. I suspect it is because the interpreter has op codes for the former and needs to do a function call for the later. However, the `divmod` call is usually clearer, particularly with well named variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T20:03:34.557",
"Id": "441433",
"Score": "0",
"body": "@RootTwo Interesting. My timing experiments seem to agree ... as long as you operate on integers, `divmod` takes about 50% longer. With either argument as a float, `divmod` appears to be slightly faster."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T23:17:36.287",
"Id": "226878",
"ParentId": "226820",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "226878",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T07:50:18.820",
"Id": "226820",
"Score": "3",
"Tags": [
"python",
"complexity"
],
"Title": "Time and space complexity of base conversion code"
}
|
226820
|
<p>I want to write my own Work-In-Progress form to use it throughout my app (for the time being, mostly as an exercise).</p>
<p>I came up with the following code, I would like to know what are the design issues, if this is not the way to go, if it could be simpler or more generic.</p>
<p><strong>Main form:</strong></p>
<pre><code>public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
delegate void InvokeMethodDelegate(ProgressBar pb, Label status, string statusText);
private void button1_Click(object sender, EventArgs e)
{
var frmWorking = new Form3();
var wds = new WorkingDialogSettings("Working...", 1, 1, 1, 10, /*async*/ (pb) =>
{
for (long i = 0; i < 10; i++)
{
doWork(frmWorking.ProgressBar, frmWorking.Label, $"Progress step {i + 1}");
Thread.Sleep(TimeSpan.FromSeconds(1));
//if I use await the task immediately completes, using thread sleep blocks it till completion
//await Task.Delay(TimeSpan.FromSeconds(1));
}
});
frmWorking.ShowDialog(wds);
}
private async void doWork(ProgressBar pb, Label status, string statusText)
{
if (pb.InvokeRequired || status.InvokeRequired)
{
pb?.Invoke(new InvokeMethodDelegate(doWork), pb, status, statusText);
return;
}
pb.PerformStep();
await Task.Delay(TimeSpan.FromSeconds(0.5));
status.Text = statusText;
}
}
</code></pre>
<p><strong>Work-In-Progress form:</strong></p>
<pre><code> public partial class Form3 : Form
{
public Label Label { get { return label1; } }
public ProgressBar ProgressBar { get { return progressBar1; } }
private WorkingDialogSettings _wds;
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
Task.Run(() =>
{
_wds.ProgressBarAction(ProgressBar);
}).ContinueWith((t) =>
{
if (t.Status == TaskStatus.RanToCompletion)
{
Label.Text = "*** COMPLETED ***";
Cursor = Cursors.Default;
}
});
}
public void ShowDialog(WorkingDialogSettings workingDialogSettings)
{
_wds = workingDialogSettings;
ProgressBar.Minimum = workingDialogSettings.Minimum;
ProgressBar.Maximum = workingDialogSettings.Maximum;
ProgressBar.Step = workingDialogSettings.Step;
ProgressBar.Value = workingDialogSettings.Value;
this.Text = workingDialogSettings.Title;
this.ShowDialog();
}
}
public class WorkingDialogSettings
{
public WorkingDialogSettings(string title, int step, int value, int minimum, int maximum, Action<ProgressBar> progressBarAction, List<string> statuses = null)
{
Title = title;
Step = step;
Value = value;
Minimum = minimum;
Maximum = maximum;
ProgressBarAction = progressBarAction;
Statuses = statuses;
}
public string Title { get; private set; }
public int Step { get; private set; }
public int Value { get; private set; }
public int Minimum { get; private set; }
public int Maximum { get; private set; }
public IEnumerable<string> Statuses { get; private set; }
public Action<ProgressBar> ProgressBarAction { get; private set; }
}
</code></pre>
<p><strong>Any corrections, suggestions, remarks</strong> ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:13:10.623",
"Id": "441093",
"Score": "1",
"body": "That code in _Form3_Load_ should use a BackGroundWorker in WinForms. It synchronizes thread scheduling for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:25:43.317",
"Id": "441096",
"Score": "0",
"body": "@dfhwze would you nowadays still use that ancient thing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:27:59.143",
"Id": "441097",
"Score": "0",
"body": "@t3chb0t It's consistent with the archaic technology called _WinForms_ :p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:28:25.147",
"Id": "441098",
"Score": "0",
"body": "@t3chb0t: as I said, this came out as an exercise"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:30:49.273",
"Id": "441099",
"Score": "0",
"body": "@dfhwze: Does not [Task.Run](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=netframework-4.8) already take care of scheduling the task in the task pool ? That is not enough ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:34:31.180",
"Id": "441100",
"Score": "2",
"body": "Check out this post what ContinueWith requires to post back to UI: https://www.codeproject.com/Articles/1018071/ContinueWith-Vs-await. That being said, _async/await_ is the de facto standard these days"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T08:51:18.160",
"Id": "226823",
"Score": "1",
"Tags": [
"c#",
"winforms"
],
"Title": "Work-in-Progress Form to be used throughout an application"
}
|
226823
|
<p>I fetch a bunch of categories for a <code>DropDown</code> tree, and have to implement search in this dropdown. If there is a match in one of the elements, it should also get all parents to display in the dropdown hierarchy. The number of childnodes is unknown, and can be changed at any given time (example has only 3 levels but can be 5 also).</p>
<p>The search applies on every ScrapCategory description.</p>
<p><a href="https://i.stack.imgur.com/3KAkb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3KAkb.png" alt="enter image description here"></a></p>
<p>I get the expected result but I would love to see this in <span class="math-container">\$O(N)\$</span>.</p>
<pre class="lang-cs prettyprint-override"><code>public sealed class ScrapCategory
{
public int Id { get; set; }
public bool IsActive { get; set; }
public string Description { get; set; }
public int Level { get; set; }
public int ParentId { get; set; }
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>public ScrapCategory[] Filter(ScrapCategory[] categories, string searchString)
{
var result = new List<ScrapCategory>();
foreach (ScrapCategory category in categories)
{
if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
result.Add(category);
if (category.ParentId > 0)
{
int parentId = category.ParentId;
while (parentId > 0)
{
var parent = categories.Where(x => x.Id == parentId)?.First();
if (!result.Contains(parent))
result.Add(parent);
parentId = parent.ParentId;
}
}
}
return result.OrderBy(x => x.Level).ToArray();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T11:42:57.493",
"Id": "441129",
"Score": "1",
"body": "Seems like a problem you want to use a Tree structure for. Why is _ScrapCategory_ a flat object (with Id's rather than references to other family members), and are you in the possibility to change the definition of that class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T11:49:34.267",
"Id": "441132",
"Score": "2",
"body": "We are re-writing 30 year old Pascal/Delphi applications to a new .NET stack but we múst use the existing DB model, procedures, and even use existing queries. We pass ScrapCategory[] to FE and they create the DropDown. ScrapCategory is the representation of how it is stored in DB."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T15:45:57.713",
"Id": "441168",
"Score": "0",
"body": "There is a performance tag that you can add if performance is an issue. I take it that the image showing the drop down menu is from a requirements document. That may make some of the reviewers on this site feel that the question is too vague. Is it possible for you to post all classes involved?"
}
] |
[
{
"body": "<p>A possibility is to store the parents as we go so we don't need to keep searching though the input array. <br/> \nWe can use a dictionary to look up the parents by id.</p>\n\n<p>If we can guarantee that the ancestors for a category all appear in the array before the category then we can do this in one pass.</p>\n\n<p>Reading through the array we add each category to the dictionary, keyed to its id.\nWe can also use the dictionary entry to show if a given item has already been added to the result (this removes the need for the <code>Contains()</code> check)</p>\n\n<p>Then, if it has a parent, we get the parent from the dictionary and if it hasn't been added, add it, and then repeat for the parent't parent (if any), recursing up the tree.</p>\n\n<pre><code>private static Category[] Filter(IEnumerable<Category> categories, string searchString)\n{\n var ret = new List<Category>();\n var dict = new Dictionary<int, DictEntry>();\n foreach (var category in categories)\n {\n dict.Add(category.Id, new DictEntry(category));\n if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n ret.Add(category);\n dict[category.Id].Added = true;\n\n var parentId = category.ParentId;\n\n while (true)\n {\n if (parentId == 0) break;\n var parent = dict[parentId].Category;\n\n if (!dict[parent.Id].Added)\n {\n ret.Add(parent);\n dict[parent.Id].Added = true;\n }\n parentId = parent.ParentId;\n\n }\n }\n }\n return ret.OrderBy(n => n.Level).ToArray();\n}\n</code></pre>\n\n<p>If we cannot guarantee that the ancestors appear ahead of the category then we can do it in two passes. Not O(N) (AFAIK) but still should be notably faster than searching all the inputs for each ancestor.</p>\n\n<pre><code>private Category[] Filter(IEnumerable<Category> categories, string searchString)\n{\n var ret = new List<Category>();\n var dict = new Dictionary<int, DictEntry>();\n foreach(var category in categories)\n {\n dict.Add(category.Id, new DictEntry(category));\n if(category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >=0)\n {\n ret.Add(category);\n dict[category.Id].Added = true;\n }\n }\n\n var ancestors = new List<Category>();\n foreach(var category in ret)\n {\n var parentId = category.ParentId;\n\n while(true)\n {\n if (parentId == 0) break;\n var parent = dict[parentId].Category;\n\n if(!dict[parent.Id].Added)\n {\n ancestors.Add(parent);\n dict[parent.Id].Added = true;\n }\n parentId = parent.ParentId;\n\n }\n\n }\n return ret.Concat(ancestors).OrderBy(n => n.Level).ToArray();\n}\n</code></pre>\n\n<p><strong>Other points:</strong></p>\n\n<p>I would push for having the input being <code>IEnumerable<ScrapCategory></code> rather than <code>ScrapCategory[]</code>. The array requirement limits without adding anything useful.</p>\n\n<p><strong>Edit - Add missing helper class</strong> <br/></p>\n\n<pre><code>class DictEntry\n{\n public DictEntry(Category category)\n {\n Category = category;\n Added = false;\n }\n public Category Category { get; }\n public bool Added { get; set; }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T13:52:07.860",
"Id": "441142",
"Score": "0",
"body": "Maybe I'm missing something here, but what is `DictEntry`? Why not use `Category` (or `ScrapCategory`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T14:17:44.997",
"Id": "441148",
"Score": "0",
"body": "@JAD I wanted to use the added field as well as the Category so that we don't have to check to see if it is already in the list before we add it again. Faster than the `if (!result.Contains(parent))` in the original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T14:20:34.843",
"Id": "441150",
"Score": "0",
"body": "According to the OP, their model is fixed, so adding fields doesn't really fly. If you're worried about duplicate items in your resultslist, use a `HashSet<Category>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T14:41:34.713",
"Id": "441154",
"Score": "0",
"body": "@JAD Adding fields? I'm not sure what you mean. Added is part of the DictEntry which doesn't touch the model. A HashSet<ScrapCategory> will work but could lead to unneeded processing - say we have two sibling grandchildren that meet the search criteria. Grandchild 1 (GC1) adds its parent (P1) and then we add its parent (GP1). We match GC2, we now add its parent (P1) and then its parent (CP1). OK, not a great deal of extra processing but why not short circuit it by saying you (and all your ancestors) have already been added so just move onto the next item?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T17:59:34.280",
"Id": "441202",
"Score": "0",
"body": "I'm not familiar with dictentry, can't find anything on it in the msdn docs either. Hence my initial question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T07:05:33.713",
"Id": "441278",
"Score": "1",
"body": "@JAD My bad, I missed copying that class. Adding now"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T12:01:41.737",
"Id": "226833",
"ParentId": "226827",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code> var result = new List<ScrapCategory>();\n ...\n if (!result.Contains(parent))\n</code></pre>\n</blockquote>\n\n<p>There's one performance problem. Use a data structure which gives fast <code>Contains</code> checks: typically <code>HashSet<></code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var parent = categories.Where(x => x.Id == parentId)?.First();\n</code></pre>\n</blockquote>\n\n<p>There's another one. I assume that IDs are unique, in which case <code>lookup = categories.ToDictionary(category => category.Id)</code> will give you a fast hash map from ID to category.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)\n result.Add(category);\n\n if (category.ParentId > 0)\n {\n int parentId = category.ParentId;\n\n while (parentId > 0)\n {\n ...\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Is this definitely correct? It's not supposed to be</p>\n\n<pre><code> if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)\n {\n result.Add(category);\n\n if (category.ParentId > 0)\n {\n ...\n }\n }\n</code></pre>\n\n<p>?</p>\n\n<p>Either way, the <code>if (category.ParentId > 0)</code> is pointless. The test is repeated by the <code>while</code> loop, and a single assignment to a local variable isn't going to be a performance bottleneck.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (!result.Contains(parent))\n result.Add(parent);\n</code></pre>\n</blockquote>\n\n<p>Note that with the suggestion of making <code>result</code> a <code>HashSet</code> it becomes preferable to just call <code>Add</code>, which returns a <code>bool</code> to tell you whether it changed anything. If it didn't, you can break out of the loop, because you know that all of the further ancestors have already been added.</p>\n\n<hr>\n\n<p>The effect of these changes (except the one I'm unsure about) is</p>\n\n<pre><code>public ScrapCategory[] Filter(ScrapCategory[] categories, string searchString)\n{\n var lookup = categories.ToDictionary(category => category.Id);\n var result = new HashSet<ScrapCategory>();\n\n foreach (ScrapCategory category in categories)\n {\n if (category.Description.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)\n result.Add(category);\n\n int parentId = category.ParentId;\n while (parentId > 0)\n {\n var parent = lookup[parentId];\n if (!result.Add(parent))\n break;\n parentId = parent.ParentId;\n }\n }\n\n return result.OrderBy(x => x.Level).ToArray();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T05:30:14.597",
"Id": "441268",
"Score": "0",
"body": "Your solution with `HashSet<>` exactly what I wanted to achieve. Thanks a lot for the answer and explanation!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T16:40:56.960",
"Id": "226854",
"ParentId": "226827",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "226854",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:44:26.313",
"Id": "226827",
"Score": "4",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "DropDown tree with search"
}
|
226827
|
<p>Still learning JS and I made the following function to convert degrees into cardinal directions respectively. My first iteration of the code was over 50 lines and I was able to get it down to 13 using a for loop.</p>
<p>Is there a way to optimize or simplify the code down even more? Is my logic and implementation ideal?</p>
<p><a href="https://codepen.io/bbbenji/pen/JjPGNmY" rel="nofollow noreferrer">https://codepen.io/bbbenji/pen/JjPGNmY</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function setCardinalDirection() {
value = document.querySelector('#orientation').value // Get current value from range input
document.querySelector(".degrees").textContent = value // Inject current input value into label
direction = document.querySelector(".direction") // Define intercardinal direction display element
degrees = 22.5 // Define range between two intercardinal directions
cardinal = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N"]
for ( i = cardinal.length; i >= 0; i-- ) { // Iterate through cardinal array backwards
if ( value < degrees/2 + degrees * i ) {
cardinalOut = cardinal[i]
}
}
direction.textContent = cardinalOut // Inject current cardinal value into label
}
document.querySelector("#orientation").addEventListener('input', function(event) {
setCardinalDirection()
})
window.addEventListener("load", function(){
setCardinalDirection()
})</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
<label for ="orientation">
Orientation: <strong><span class="degrees"></span>° (<span class="direction"></span>)</strong>
</label>
<br />
<input id="orientation" type="range" min="0" max="360" step="1" value="145">
</form></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T11:44:40.730",
"Id": "441130",
"Score": "1",
"body": "@konijn I did not see this, caching issue perhaps?"
}
] |
[
{
"body": "<p>You can replace the for loop with <code>cardinalOut = cardinal[Math.floor((value / degrees) + 0.5)]</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T00:48:42.667",
"Id": "226880",
"ParentId": "226828",
"Score": "2"
}
},
{
"body": "<h2>Evaluation</h2>\n\n<p>For somebody learning Javascript this code isn't bad, however it does have some inefficiencies and practices that are frowned upon (e.g. Global variables). See the suggestions below for advice about improving it.</p>\n\n<h2>Suggestions</h2>\n\n<h3>Semicolon terminators</h3>\n\n<p>Unless you are intimately familiar with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">the statements that need to be terminated by a semicolon</a> it is wise to always terminate each line with a semi-colon.</p>\n\n<h3>Selecting elements by class vs id attribute</h3>\n\n<p>The first line selects an element from the DOM by the <em>id</em> attribute - i.e. <code>document.querySelector('#orientation')</code>. The next line uses a <em>class</em> selector to select an element: <code>document.querySelector(\".degrees\")</code>. If there is only one element with class name <code>degrees</code> that matters for this application then an <em>id</em> attribute would be more appropriate than <em>class</em>. </p>\n\n<p>Also, it isn't wrong to use <code>document.querySelector()</code> to get elements by <em>id</em> but using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById\" rel=\"nofollow noreferrer\"><code>document.getElementById()</code></a> \"<em>is definitely faster</em>\" <sup><a href=\"https://www.sitepoint.com/community/t/getelementbyid-vs-queryselector/280663/2\" rel=\"nofollow noreferrer\">1</a></sup> (see <a href=\"https://jsperf.com/getelementbyid-vs-queryselector\" rel=\"nofollow noreferrer\">this jsPerf test for comparison</a>). Similarly <code>document.getElementsByClassName()</code> is also faster. I would suggest only using <code>document.querySelector()</code> when there is a complex selector (e.g. <code>form lable[for=\"direction']</code></p>\n\n<h3>Global variables</h3>\n\n<p>Any variable not declared with a keyword like <code>var</code>, <code>const</code> or <code>let</code> is considered <code>global</code>. For a small application like this it likely wouldn't lead to any issues but in a larger application it could lead to unintentional side-effects if the same name is used in different functions.</p>\n\n<h3>Excess closures</h3>\n\n<p>The lines to add event listeners can be simplified:</p>\n\n<blockquote>\n<pre><code>document.querySelector(\"#orientation\").addEventListener('input', function(event) {\n setCardinalDirection()\n})\n\nwindow.addEventListener(\"load\", function(){\n setCardinalDirection()\n})\n</code></pre>\n</blockquote>\n\n<p>Instead of wrapping the calls to <code>setCardinalDirection()</code> in an extra function, just pass the name of the function:</p>\n\n<pre><code>document.querySelector(\"#orientation\").addEventListener('input', setCardinalDirection); \nwindow.addEventListener(\"load\", setCardinalDirection);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-28T08:50:48.523",
"Id": "441514",
"Score": "1",
"body": "Thank you, this was very helpful.\n\nI have taken your input and updated my CodePen: https://codepen.io/bbbenji/pen/JjPGNmY"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-27T15:25:16.180",
"Id": "226931",
"ParentId": "226828",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "226931",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-26T09:59:52.167",
"Id": "226828",
"Score": "2",
"Tags": [
"javascript",
"html",
"event-handling",
"dom"
],
"Title": "Cardinal direction enum from range input"
}
|
226828
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.