text stringlengths 1 2.12k | source dict |
|---|---|
performance, sql, postgresql
Query Plan
Output from EXPLAIN ..., given the above example with actual values and run on a database instance with only 1 profile, which is not a venue.
QUERY PLAN
---------------------------------------------------------------------------------------------------
Limit (cost=8248.43..8248.51 rows=31 width=40)
CTE enumerated
-> WindowAgg (cost=8211.05..8227.32 rows=651 width=317)
-> Sort (cost=8211.05..8212.67 rows=651 width=309)
Sort Key: (('-1'::integer)::double precision), p.name, p.id
-> Hash Join (cost=17.88..8180.62 rows=651 width=309)
Hash Cond: ("*SELECT* 1".profile_id = p.id)
-> Append (cost=0.00..8154.51 rows=651 width=105)
-> Subquery Scan on "*SELECT* 1" (cost=0.00..0.00 rows=1 width=105)
-> Result (cost=0.00..0.00 rows=0 width=101)
One-Time Filter: false
-> Seq Scan on venues (cost=0.00..8144.75 rows=650 width=105)
-> Hash (cost=13.50..13.50 rows=350 width=204)
-> Seq Scan on profiles p (cost=0.00..13.50 rows=350 width=204)
InitPlan 2 (returns $1)
-> Result (cost=0.00..0.00 rows=0 width=0)
One-Time Filter: false
-> Sort (cost=21.11..21.65 rows=217 width=40)
Sort Key: enumerated.index
-> CTE Scan on enumerated (cost=0.00..14.65 rows=217 width=40)
Filter: (index >= COALESCE($1, '0'::bigint))
(21 rows)
Answer: distance
Here's a curious column:
Materialized view "profiles.venue_parents"
Column | Type | Collation | Nullable | Default
-----------+---------+-----------+----------+---------
...
distance | integer | | | | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
Distance to what?
Charing Cross?
Linköping Central Station?
Document the origin point.
Or better, include the pair of (lat, long)'s, for total of five columns,
and then you'll have a self-documenting relation.
I am glad to see it's in SI units of meters.
CREATE MATERIALIZED VIEW venue_parents ...
...
1 AS distance ...
Why a sentinel of one meter, rather than zero?
You seem to sum up +1 and -1 a fair amount -- what does that mean?
Maybe you wanted a different word, like priority, to describe
your ORDER BY preference, if we don't have actual geographic distances here.
long query
Your WITH root_nodes... query is Too Long.
Maybe you can keep all those plates spinning in the air at once, but I can't.
Consider breaking out meaningful relations, giving them names,
and defining each as a VIEW.
Then this long query becomes a much simpler combination of the VIEWs you built up.
Such decomposition doesn't really matter to the backend query planner --
it will catenate them together and still produce plans similar to the current one.
The advantage is that you get to do piecewise debugging,
of both a result's correctness and also its performance.
Also, the VIEWs would hopefully discourage you from sprinkling
expressions like ${filterModel.near?.lng ?? 0}
and ${filterModel.near && 1}::int throughout the interior
of your queries.
Have the query surface attributes like a longitude column,
and then let your UI interface select rows WHERE longitude has some value,
or perhaps WHERE ST_DistanceSphere() has some value.
meaningful names
...
) AS t
That's not really helping me out.
Give it a proper name, describe the relation you just built.
With p.* you at least told us it's the profiles table,
so I know how to mentally pronounce it. | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
query plan
You didn't mention any symptoms like only getting X result rows per second,
or having to wait Y seconds for first result row to appear.
Mostly it all looks good to me.
You can use
EXPLAIN ANALYZE
for more detailed timings.
The EXPLAIN will comment on "how many rows?" and "is there an index?",
without actually fetching rows.
An ANALYZE will fetch the rows, and measure how many seconds that took.
Planning only becomes interesting when you have "lots" of data,
and most of it remains on-disk, ignored by a query that looks
for just a narrow range of result values.
You appear to have only a small amount of data,
less than seven hundred rows,
which suggests that all queries would be fast,
even if there were no indexes.
INSERT more rows if you want to explore performance in depth.
The plan, and the use of indexes, mostly looks fine.
The only noteworthy item that leaps out at me is this tablescan:
-> Seq Scan on venues (cost=0.00..8144.75 rows=650 width=105)
And of course tablescans are not a bad thing, sometimes that's the
very best access plan, if your query needs to retrieve every single stored value.
If we're focused on nice snappy interactive response times, then query
selectivity
is something you want to pay attention to.
A highly selective WHERE clause is one that lets us retrieve just a handful
of rows to obtain a result, while we get to ignore 99% of a table's contents.
Usually some suitable index will help us achieve that.
In contrast a low selectivity query forces the backend to retrieve
most of the rows, and there's just no optimizing that, it fundamentally
requires doing a lot of time consuming work.
Your query is on the complex side.
Think about how storing certain facts in a reporting table
would allow you to submit a query that is both simpler for the backend to plan
and easier for humans to reason about. | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
sql92 keywords
I'm not fond of naming a column index,
given that that is a pretty important part of
DDL.
Prefer an alternate spelling, perhaps idx.
paging
Assume that each interactive user has a unique ID,
perhaps a GUID in a web session cookie.
Equivalently, we could use hash of the first
part of a query, omitting the page number.
You run a complex query and then return just the subset
of result rows that fall within the requested page.
And then re-run it for the subsequent page.
Consider caching the full result set in a reporting table,
indexed on guid + row number.
Now satisfying a 2nd page or 3rd page request becomes trivial.
Put a timestamp in such rows, so you can purge yesterday's trash.
Depending on user behavior, maybe don't bother with
storing results for 1st page requests, if users
typically jump around while looking only at 1st page results
(so any 2nd page effort would typically be wasted).
Once you see a 2nd page request, that may be a fair indicator
that user will soon generate 3rd page and 4th page requests, as well. | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
java, multithreading
Title: Stopping a running thread
Question: I am trying to stop an executing runnable instance after the run method has been called.
I have come up with the below approach
public class StoppableWorkflowTask implements Runnable {
volatile Thread runner = null;
@Override
public void run() {
runner = Thread.currentThread();
try {
while (true) {
System.out.println("Stop Thread " + Thread.currentThread().getId());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
void stop() {
runner.stop();
}
}
public class StoppableWorkflowTaskTest {
public static void main(String[] args) {
StoppableWorkflowTask stoppableTask = new StoppableWorkflowTask();
Thread thread = new Thread(stoppableTask);
thread.start();
System.out.println(thread.currentThread().getId());
try {
stoppableTask.stop();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
As per Java documention it is unsafe to call thread.stop(). I have checked few examples , but all either use thread.sleep() which can be terminated on interrupt.
Answer: The recommended way from Oracle is Thread.interrupt(). For example:
public void stop() {
Thread thread = runner;
runner = null;
thread.interrupt();
}
public void run() {
runner = Thread.currentThread();
while (runner != null) {
System.out.println("Stop Thread " + Thread.currentThread().getId());
}
System.out.println(" Done ");
} | {
"domain": "codereview.stackexchange",
"id": 45275,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, multithreading",
"url": null
} |
java, multithreading
It is true that sleep() can be interrupted (which will raise an InterruptedException), which is what the interrupt() will do. However, afterwards the Thread can continue doing whatever it wants after being “interrupted”, so you must also check for a stop-condition of some kind. Above, we check runner != null. But as you can see above, you don’t need a sleep() in the worker thread.
If you don’t want to run the Thread in a loop, or you have many different loops where the task may spin, you will have to make the stop check in each of those places. | {
"domain": "codereview.stackexchange",
"id": 45275,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, multithreading",
"url": null
} |
python, sqlite, sqlalchemy
Title: Managing users via SQLAlchemy DB model (updated)
Question: I am currently in the process of writing a system application that will be operated by multiple users. This will require individual users to access the application while limiting access to those that shouldn't be using it. The application will have several areas of access, which all users will not have access to. At this time, it may change in the future, the application is more or less a proof of concept and will be storing user information in a DB.
What I have here is what I'm calling the Operator Library. This part of my code is strictly how to access the portion of the DB that interacts with the users table. There will be other libraries that will be written to access the DB related to specific tables in a very similar manner to the below.
UPDATE:
looking at the documentation, it seems they recommend using a with statement for handling opening and using individual sessions. I've also added some simple exception handling.
Anything else I should be adding?
DBOperatorLibary.py
from Models import Operator, engine
from sqlalchemy.orm import sessionmaker
local_session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def create_operator(username, password, privilage):
ret = None
with local_session() as session:
operator = Operator(username=username, privilage=privilage)
if operator.password == "":
operator.password = password
session.add(operator)
try:
session.commit()
session.refresh(operator)
ret = operator
except Exception as e:
ret = e.args
return ret
def get_operators():
with local_session() as session:
operators = session.query(Operator).all()
return operators
def update_operator(operator_id, username, password, privilage):
ret = None | {
"domain": "codereview.stackexchange",
"id": 45276,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, sqlalchemy",
"url": null
} |
python, sqlite, sqlalchemy
def update_operator(operator_id, username, password, privilage):
ret = None
with local_session() as session:
operator = session.query(Operator).get(operator_id)
operator.username = username
operator.password = password
operator.privilage = privilage
try:
session.commit()
session.refresh(operator)
ret = operator
except Exception as e:
ret = e.args
return ret
def delete_operator(operator_id):
ret = None
with local_session() as session:
operator = session.query(Operator).get(operator_id)
session.delete(operator)
try:
session.commit()
ret = operator
except Exception as e:
ret = e.args
return ret
def validate_operator_password(username, password):
with local_session() as session:
operator = (
session.query(Operator)
.filter(Operator.username == username)
.first()
)
if operator is None:
return False
return operator.check_password(password)
if __name__ == "__main__":
...
Models.py
from BaseModel import Base
from OperatorModel import Operator
from RecordModels import Record
from sqlalchemy import create_engine
engine = create_engine("sqlite:///db/application.db", echo=True)
Base.metadata.create_all(bind=engine)
BaseModel.py
from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass
class Base(MappedAsDataclass, DeclarativeBase):
"""subclasses will be converted to dataclasses"""
OperatorModel.py
from datetime import datetime
from BaseModel import Base
from sqlalchemy import func
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import Mapped, mapped_column
from werkzeug.security import check_password_hash, generate_password_hash
class Operator(Base):
__tablename__ = "operators" | {
"domain": "codereview.stackexchange",
"id": 45276,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, sqlalchemy",
"url": null
} |
python, sqlite, sqlalchemy
class Operator(Base):
__tablename__ = "operators"
oid: Mapped[int] = mapped_column(primary_key=True, init=False)
created_on: Mapped[datetime] = mapped_column(
init=False, server_default=func.now()
)
username: Mapped[str]
privilage: Mapped[str]
_password: Mapped[str] = ""
@hybrid_property
def password(self):
return self._password
@password.setter
def password(self, password):
self._password = generate_password_hash(password)
return self._password
def check_password(self, password):
return check_password_hash(self._password, password)
def __repr__(self):
return f"User Record {self.oid}\
\n\tUsername: {self.username} \
\n\tPrivilage: {self.privilage} \
\n\tCreated On: {self.created_on}"
Answer: The with looks good.
operator = Operator(username=username, privilage=privilage)
nit: Please use conventional spelling of "privilege".
type stability
ret = operator
except Exception as e:
ret = e.args
I'm not crazy about the Public API offered by create_operator, there.
You have created a "difficult to consume" API;
caller must distinguish between those two cases.
When there's many call sites, at least one of them likely is buggy,
failing to properly test it.
Better to let that exception bubble up the call stack.
This pattern repeats throughout the code base, bloating it up.
Better to raise at those other locations, as well.
enforce a password policy
if operator.password == "": | {
"domain": "codereview.stackexchange",
"id": 45276,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, sqlalchemy",
"url": null
} |
python, sqlite, sqlalchemy
I don't understand this.
How did that row come to appear in the database?
Delete such rows.
Require that operators shall use credentials for access.
sensible credentials
Please delete that password column.
If (when) an attacker compromises your server,
the release of plaintext passwords will cause
catastrophic harm to you, your users, and to other sites they use.
Use argon2id()
to turn each password into a (salted) hash, and store that
in a new credential column.
blind query
Consider renaming get_operators to get_all_operators.
I was a little surprised by the absence of parameter(s) fed to a WHERE clause.
extra refresh
def update_operator...
...
session.refresh(operator)
What do we believe the refresh() did there?
Looks like "nothing", to me.
rename column
class Operator(Base):
...
def check_password(self, password):
return check_password_hash(self._password, password)
nit: Please use conventional spelling of "library".
Back in DBOperatorLibary your identifiers were telling me that
we're storing cleartext passwords.
But here we are passing around a
hash.
Please use identifiers that tell the truth.
Using pbkdf2 is reasonably good, though
argon2id
would be better (slower for attackers to brute force it).
Your @password.setter uses especially confusing
identifiers, given that same word is used to
represent two radically different concepts.
EDIT
truthful identifiers
Two classic issues in software engineering are
"comments lie!", and
"identifiers lie!"
No one wants to read a two-sentence # comment which
used to speak the truth about an algorithm,
back before requirements changed we altered the code
to have brand new behavior.
No one wants to read code like this all-too-typical example:
def mean(nums: list[int]) -> float:
avg = 0 # accummulator, a running sum
for num in nums:
avg += num
avg /= len(nums)
return avg | {
"domain": "codereview.stackexchange",
"id": 45276,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, sqlalchemy",
"url": null
} |
python, sqlite, sqlalchemy
That variable is clearly in no way an "average" until the very end.
So we can't reason about loop variants in terms of
a mathematical average, we must go through mental gymnastics
to ignore what our eyes are showing us and read that
as "accummulator" or "running sum" within the loop.
Much better to phrase it like this:
def mean(nums: list[int]) -> float:
acc = 0
for num in nums:
acc += num
return acc / len(nums)
(Obviously in python we'd prefer sum(nums) / len(nums),
this is just for illustration.)
Interlude: Here is an example password hash. It is 64-bit prefix of SHA-2.
$ echo -n secret123 | shasum -a 224 | cut -c1-16
8a73901c428f41be
In the OP code, we have several instances where ostensibly
we're passing a password around, so it might have a
value like "secret123". Sometimes those identifiers
speak the truth. Often they are really holding a hash,
and we might expect pw_hash to have a value
like "8a73901c428f41be".
Recommend you rename some of those identifiers.
Future maintenance engineers will thank you. | {
"domain": "codereview.stackexchange",
"id": 45276,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, sqlalchemy",
"url": null
} |
python, sqlite, sqlalchemy
Crypto algorithms often want to see at least 128 bits
of true entropy in key material, in order to make
solid security guarantees.
If you look at passwords memorized by real users,
it appears that often they have trouble remembering
more than about 40 bits of entropy.
(A password like "banana" consumes 48 bits of storage
but has significantly less entropy than that.)
password stretchers
Why do we use pbkdf2, or the better more-modern argon2id?
To thwart certain attack scenarios.
Imagine that Mallory obtains a credential being sent across
the wire or being stored on-disk on the webserver.
She wants to be able to present valid credentials to
your server and to other servers frequented by your users,
which possibly use the same memorized password.
If passwords are stored in a file as plaintext,
a single webserver breach is catastrophic for you
and for other servers.
If credentials are stored as e.g. SHA-2 or SHA-3 hashes,
Mallory can play dictionary words ("apple") and
generated words ("secret1234") against her own GPU
that computes the hash function, hoping for a match.
Those are designed to be quick hash functions,
so in an hour she can explore quite a large key space.
We call this an "off-line" attack, since Mallory
can conduct the search without contacting your on-line server.
If credentials are stored as argon2id hashes,
she can still launch the same attack,
but it was designed to be an intentionally slow hash function
so she'll be able to explore a much much smaller key space
in the same amount of time.
We have also forced her to purchase significantly more RAM
for her GPU, again due to intentional aspects of the
hash function's design.
The design goals for the (earlier) pbkdf2 function
were similar. Experiences with that nice bit of engineering
informed development of the new and improved argon2 suite
of hash functions.
tl;dr: Use argon2id when {storing, checking} a user's memorized password. | {
"domain": "codereview.stackexchange",
"id": 45276,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, sqlalchemy",
"url": null
} |
javascript, programming-challenge, strings
Title: String represents a road. One character travels on the road obeying the stops - Code challenge (advent.js day 5)
Question: This is my code to solve the 5th Adventjs challenge. In that link you can read the instructions.
How can I improve it? It's a bit messy... and I'm repeating some part of the code.
All must be in just one function
function cyberReindeer(road, time) {
// Code here
let theRoad = road;
let roadNow = "";
let greenLight = false;
let roadArr = [];
let stop = false;
for (let i = 0; roadArr.length < time; i++) {
if(greenLight !== true) {
if (theRoad.charAt(i) !== "|" && stop !== true) {
roadNow = theRoad.slice(0, i + 1)
.replace("S", theRoad.charAt(i))
.replace(/.$/,"S")
+ theRoad.slice(i+1, theRoad.length);
roadArr.push(roadNow);
} else {
while(roadArr.length < 5 && roadArr.length < time) {
roadArr.push(roadNow);
stop = true;
}
theRoad = theRoad.replace(/\|/g, '*');
greenLight = true;
roadNow = theRoad.slice(0, i + 1)
.replace("S", ".")
.replace(/.$/,"S")
+ theRoad.slice(i+1, theRoad.length);
if(roadArr.length < time) {
roadArr.push(roadNow);
}
}
} else {
roadNow = theRoad.slice(0, i + 1)
.replace("S", ".")
.replace(/.$/,"S")
+ theRoad.replace(/\|/g, '*')
.slice(i+1, theRoad.length);
roadArr.push(roadNow);
}
}
return roadArr;
}
Answer: carefully read the requirements
The original problem asks us to
Create a function that simulates the sled's movement ...
Somehow you leapt from that to
All must be in just one function.
I see no prohibition on adding a helper function, if you find it convenient. | {
"domain": "codereview.stackexchange",
"id": 45277,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge, strings",
"url": null
} |
javascript, programming-challenge, strings
I see no prohibition on adding a helper function, if you find it convenient.
painting a sprite
Santa is a
spritely
old elf.
Three times you use an odd idiom for erasing his sled and then re-drawing it.
It would be simpler to just copy the original road terrain
to the result each time (thereby "erasing" Sanata),
followed by placing Santa at his new location between a pair of
substrings.
velocity
Surprisingly, we're not modeling Santa's position with an x variable.
The current solution resembles computation by
cellular automata.
Having adopted that we might have a per time-step velocity delta_x,
so the update for each cycle is x += delta_x.
Setting that delta to zero would be a natural way to model Santa
stopping briefly for a Red light.
consistent tests
I was a little surprised to see comparisons to 5 or to time
like this: roadArr.length < time.
It would have been more natural, at time-step i,
to compare against the loop variable: i < time.
Due to how the array grows, the effect is the same. Clarity could be improved.
separation of concerns
This simulation of the world has two things to manage each time-step:
Stop lights ("barriers") sometimes switch from Red to Green
Santa moves, subject to Red light restrictions
It might be worth breaking out a pair of helper functions for that.
This simple world seems very physics based to me -- Santa performs
local sensing of an adjacent barrier.
Yet we have a global comparison to 5 which alters Santa's behavior.
I was hoping to see simpler logic where we change the world
by replacing all | bars with * stars when i == 5,
and then we let Santa move when there's no | bar.
The stop and greenLight booleans seem a bit much,
it's more things to juggle in your head than are necessary. | {
"domain": "codereview.stackexchange",
"id": 45277,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, programming-challenge, strings",
"url": null
} |
c#, object-oriented, classes, enum
Title: Declaring type definition once for all variables
Question: To avoid the use of magic numbers, I created a static class to store some integer values that are represented inside a database. I avoided using enums because I need to cast them every time I use them. To benefit from the clean approach of enums while also enjoying the type definition offered by classes.
The Class Approach
public static class TransactionType
{
public static readonly int
Deposit = 1,
Withdrawal = 2,
Transfer = 3,
Payment = 4,
Refund = 5;
}
// Example Usage
public void ProcessTransactionClass(int transactionTypeId)
{
if (transactionTypeId == TransactionType.Deposit)
{
// Handle deposit
}
else if (transactionTypeId == TransactionType.Withdrawal)
{
// Handle withdrawal
}
// ... and so on for other types
}
Enum Approach
public enum TransactionType
{
Unassigned = 0, // Default value
Deposit = 1,
Withdrawal = 2,
Transfer = 3,
Payment = 4,
Refund = 5
}
// Example Usage
public void ProcessTransactionEnum(int transactionType)
{
if (transactionType == (int)TransactionType.Deposit)
{
// Handle deposit
}
else if (transactionType == (int)TransactionType.Withdrawal)
{
// Handle withdrawal
}
// ... and so on for other types
}
I haven't seen this kind of usage anywhere, is this style any good and acceptable?
Answer: Ah, after much back and forth I think I understand....
I haven't seen this kind of usage anywhere, is this style any good and acceptable?
No. No it's not. Be consistent with Type usage. If these numbers are "kinds of transactions" then write the code that way. Do not flip flop all over the code base, it induces bug risk.
Use enums. They are Type safe. Mistakes are caught at compile time. Cast the DB sourced values to enums, not the other way around. Do this up front, probably in a constructor, THEN use them. | {
"domain": "codereview.stackexchange",
"id": 45278,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, classes, enum",
"url": null
} |
c++, logging
Title: Logger for a Game Engine
Question: So I'm making a logger for a program and it has 6 levels increasing severity and things I don't think its as memory efficient as it could be but I'm just getting into c++ and memory coding. I feel like if I want to put it in a file I cant view it with a text editor using something like JSON or XML.
This is the code in question
#include <iostream>
#include <fstream>
#include <ctime>
enum class LogLevel { GREY, BLUE, GREEN, YELLOW, ORANGE, RED };
std::ostream& operator<<(std::ostream& os, LogLevel level) {
switch (level) {
case LogLevel::GREY:
os << "GREY";
break;
case LogLevel::BLUE:
os << "BLUE";
break;
case LogLevel::GREEN:
os << "GREEN";
break;
case LogLevel::YELLOW:
os << "YELLOW";
break;
case LogLevel::ORANGE:
os << "ORANGE";
break;
case LogLevel::RED:
os << "RED";
break;
default:
os << "UNKNOWN";
break;
}
return os;
}
class Logger {
private:
std::ofstream logFile;
std::string getTimestamp() {
std::time_t now = std::time(nullptr);
struct tm timeInfo;
localtime_s(&timeInfo, &now);
char timestamp[20];
std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &timeInfo);
return timestamp;
}
std::string getColorCode(LogLevel level) {
switch (level) {
case LogLevel::GREY:
return "\033[90m"; // Grey
case LogLevel::BLUE:
return "\033[94m"; // Blue
case LogLevel::GREEN:
return "\033[92m"; // Green
case LogLevel::YELLOW:
return "\033[93m"; // Yellow
case LogLevel::ORANGE:
return "\033[91m"; // Orange
case LogLevel::RED:
return "\033[31m"; // Red
default:
return "\033[0m"; // Reset color
}
} | {
"domain": "codereview.stackexchange",
"id": 45279,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, logging",
"url": null
} |
c++, logging
public:
Logger(const std::string& filename) {
logFile.open(filename, std::ios::out | std::ios::app);
}
~Logger() {
if (logFile.is_open()) {
logFile.close();
}
}
void log(LogLevel level, const std::string& message) {
std::string color = getColorCode(level);
// Print to console with color
std::cout << getTimestamp() << " " << color << message << "\033[0m" << std::endl;
// Write to file
if (logFile.is_open()) {
logFile << getTimestamp() << " " << message << std::endl;
}
}
void trace(const std::string& message) {
log(LogLevel::GREY, message);
}
void debug(const std::string& message) {
log(LogLevel::BLUE, message);
}
void info(const std::string& message) {
log(LogLevel::GREEN, message);
}
void warn(const std::string& message) {
log(LogLevel::YELLOW, message);
}
void error(const std::string& message) {
log(LogLevel::ORANGE, message);
}
void critical(const std::string& message) {
log(LogLevel::RED, message);
}
};
```
Answer: This code does not need a lot of review. You are following most best practices. But, here are a few suggestions. I dont know of any text editors that support colors like this, but you can always use less or cat.
You dont need to explicitly close the file. std::ofstream does that for you.
Add a filename and line number variable to your functions. You can then wrap the function logger functions in a macro and pass FILE and LINE to these variables. This way you can log the location of your messages too.
Provide operator<< overloads for the logger class. Sometimes it is easier to stream messages, specially if they have variables in them.
If you are doing C++20, consider support for std::format.
Consider using std::chrono for time. | {
"domain": "codereview.stackexchange",
"id": 45279,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, logging",
"url": null
} |
javascript
Title: Javascript: Profile Lookup from freecodecamp
Question: This is my answer in freecodecamp "Basic Javascript: Profile Lookup" (third day trying javascript using Udemy and freecodecamp).
My problem with the code is the huge number of lines on my lookUpProfile function. I would like to minimize the lines of code of my lookUpProfile function, can you suggest me ways to achieve that?
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
// Only change code below this line | {
"domain": "codereview.stackexchange",
"id": 45280,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
function lookUpProfile(firstName, prop){
// Only change code below this line
var contain = 0;
if(firstName == "Akira"){
contain = 0;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else if(firstName == "Harry"){
contain = 1;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else if(firstName == "Sherlock"){
contain = 2;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else if(firstName == "Kristian"){
contain = 3;
if(contacts[contain].firstName == firstName)
if(contacts[contain].hasOwnProperty(prop))
return contacts[contain][prop];
else
return "No such property";
else
return "No such contact";
}
else
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "lastName");
Answer: You have very repetitive code. This can be optimized. I'm not sure whether your function name lookUpProfile is the correct one, as you actually look up a property of a Contact and not its whole profile. But if the task is to look up a certain property of a Contact you can simplify the code to this:
function lookUpProfile(firstName, prop) {
for (let contact of contacts) {
if (contact.firstName === firstName) {
return contact[prop];
}
}
return false;
}
How it works
It loops through all contacts:
for (let contact of contacts) { | {
"domain": "codereview.stackexchange",
"id": 45280,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
How it works
It loops through all contacts:
for (let contact of contacts) {
It tests whether the firstName matches:
if (contact.firstName === firstName) {
In case a match is found it returns the requested property or undefined:
return contact[prop];
In case no match is found it returns false:
return false;
What it returns
This function will have a mixed return value. The code that is calling the function can now deal with the result. It will return one of the following:
false if no Contact with the requested firstName exists
undefined if a Contact matches but the requested property doesn't exists
string|array if a match was found and the property exists
So all those calls will work:
console.log(
lookUpProfile(),
lookUpProfile('A'),
lookUpProfile('Sherlock'),
lookUpProfile('Sherlock', 'number'),
lookUpProfile('Kristian', 'likes')
);
The return values are:
false false undefined 0487345643 Array [ "Javascript", "Gaming", "Foxes" ]
What the code doesn't do:
It doesn't check whether there's a choice for Contacts, i.e. if more than one Contact with that name exists. It will always exit at the first match.
jsFiddle Demo
Try before buy
Update "No such property"
Regarding the OP's comment about a different return value, I would suggest keeping the code as is and let other parts worry about a concrete message:
var value = lookUpProfile('Sherlock', 'random');
if ('undefined' === typeof value) {
console.log('No such property');
};
If your task is to include that text into the function you can replace this line:
return contact[prop];
with:
return 'undefined' === typeof contact[prop] ? 'No such property' : contact[prop];
This is a lot harder to handle, as the string "No such property" could be an actual value of a property. | {
"domain": "codereview.stackexchange",
"id": 45280,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
java, strings, recursion
Title: Redouble each occurrence of char recursively, and add n
Question: In following of this question, I would like to have a second review.
The exercise is to write a recursive method that takes a String and a char parameter and returns a String with each occurrence of the char doubled. Additionally, the number of doubling operations should be added at the end of the string. No "extern" variables outside the method are allowed to use. The String parameter can contain any valid char, including numbers.
It's not allowed to use other (recursive) helper methods. The method signature and parameters must not to be change.
My code is working correctly now (I hope), but how to replace the "pre-"calculated map from line 7 to 25 with a simple formula/term? Thanks in advance.
import java.util.HashMap;
public class Redouble {
public static String redouble(final String s, final char c) {
if (s.length() > 0) {
if (s.charAt(0) == c) {
HashMap<Integer, Integer> map = new HashMap<>();
map.put(2, 1);
for (int j = 1; j <= 4; j++) {
int n0 = (int) Math.pow(10, j - 1);
int n1 = (int) Math.pow(10, j);
int i = n0;
for (; i < n0 + j; i++) {
int x = ((int) Math.log10(i) + i * 2 + 3 - j) / 2;
if (!map.containsKey(x)) {
map.put(x, j - 1);
}
}
for (; i < n1; i++) {
int x = ((int) Math.log10(i) + i * 2 + 3 - j) / 2;
if (!map.containsKey(x)) {
map.put(x, j);
}
}
}
//System.out.println("map = " + map); | {
"domain": "codereview.stackexchange",
"id": 45281,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, strings, recursion",
"url": null
} |
java, strings, recursion
int len1 = s.length();
String s1 = "" + c + c + redouble(s.substring(1), c);
int len2 = s1.length();
int lenDiff = len2 - len1;
if (lenDiff > 0) {
int x = map.get(lenDiff);
//System.out.println(lenDiff + " " + x);
int n = Integer.parseInt(s1.substring(s1.length() - x));
return s1.substring(0, s1.length() - x) + (n + 1);
}
return s1;
}
return "" + s.charAt(0) + redouble(s.substring(1), c);
}
return "0";
}
public static void main(final String[] args) {
// Some tests...
String s = "0cac1c01";
for (int i = 2; i <= 1010; i++) {
s += "a";
String s2 = redouble(s, 'a');
System.out.println("Expected: " + i + ", actual: " + s2.substring(s2.length() - (int) Math.log10(i) - 1));
if (!String.valueOf(i).equals(s2.substring(s2.length() - (int) Math.log10(i) - 1))) {
System.out.println("ERROR");
return;
}
}
}
}
Answer: You can calculate the number of doublings instead of looking it up in a map. The code below is otherwise copied from @Roman's answer.
public static String redouble(final String s, final char c) {
if (s.length() <= 0) {
return "0";
} | {
"domain": "codereview.stackexchange",
"id": 45281,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, strings, recursion",
"url": null
} |
java, strings, recursion
if (s.charAt(0) != c) {
return "" + s.charAt(0) + redouble(s.substring(1), c);
}
String original = s.substring(1);
String doubled = redouble(original, c);
// 1st estimate overestimates n because it includes its own string representation
// 2nd estimate is correct or underestimates by one, as the length difference between
// (n + n.toString().length()).toString() and n.toString() is 0 or 1 (prove it yourself)
// 3rd estimate is definitely correct
int n = doubled.length() - original.length();
n -= ("" + n).length();
if ((original + n).length() + n != doubled.length()) {
n += 1;
}
return "" + c + c + doubled.substring(0, original.length() + n) + (n + 1);
}
The most complicated part is proving the assertion mentioned in the comment. The table illustrates what you have to prove for all n (the length difference is always 0 or 1):
n len(n) n + len(n) len(n + len(n)) difference
0 1 1 1 0
1 1 2 1 0
2 1 3 1 0
3 1 4 1 0
4 1 5 1 0
...
8 1 9 1 0
9 1 10 2 1
10 2 12 2 0
11 2 13 2 0
...
97 2 99 2 0
98 2 100 3 1
99 2 101 3 1
100 3 103 3 0
... | {
"domain": "codereview.stackexchange",
"id": 45281,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, strings, recursion",
"url": null
} |
python, cs50
Title: Fuel Gauge Python
Question: I was wondering if my code is good or maybe if it could be written better or simpler.
The task was to implement a program that prompts the user for a fraction, formatted as X/Y, wherein each of X and Y is an integer, and then outputs, as a percentage rounded to the nearest integer, how much fuel is in the tank. If, though, 1% or less remains, output E instead to indicate that the tank is essentially empty. And if 99% or more remains, output F instead to indicate that the tank is essentially full.
If, though, X or Y is not an integer, X is greater than Y, or Y is 0, instead prompt the user again. (It is not necessary for Y to be 4.) Be sure to catch any exceptions like ValueError or ZeroDivisionError.
Here's my code:
def main():
z = get_fraction("Fraction: ")
print(z)
def get_fraction(prompt):
while True:
try:
x, y = input(prompt).split("/")
x = int(x)
y = int(y)
if x <= y:
z = x/y
else:
continue
except (ValueError, ZeroDivisionError):
pass
else:
z *= 100
if z >= 99:
z = "F"
elif z <= 1:
z = "E"
else:
z = f"{z:.0f}%"
return z
main()
It works but I wonder if it could be done better :)
Answer: This seems to mostly compute the right thing. Good job!
The code is much too complex.
In particular, the flow of control wanders around more than necessary,
due to interaction of while True:, exceptions, and the try / else clause.
Also we have one big blob instead of a few small self-contained helper functions.
We need to accomplish a pair of high-level goals, in order.
Keep prompting till we get a valid X/Y input fraction.
Format that fraction. | {
"domain": "codereview.stackexchange",
"id": 45282,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cs50",
"url": null
} |
python, cs50
Keep prompting till we get a valid X/Y input fraction.
Format that fraction.
I would love to see a z = prompt_for_fraction() call to a helper function.
That would make it clear that step (1) has finished and we're
moving on to step (2).
As written, the code keeps jumping in and out of the try block
(with continue and return), and step (2) is bound up in the try's else clause.
Here is one possible implementation, which happens to use
map:
def prompt_for_fraction(prompt: str = "Fraction: ") -> float:
"""Keep prompting until we get a valid fuel gauge reading."""
while True:
line = input(prompt)
try:
x, y = map(int, line.split("/"))
if x <= y:
return x / y
except (ValueError, ZeroDivisionError):
pass
type stability
z = x / y
...
z *= 100
...
z = "F"
Python is a dynamic language, so all three of these assignments work.
But that doesn't mean you have to go crazy with it.
The machine doesn't care what value an object (z) has,
but it matters to humans, who will want to understand what it means.
Here's a simple rule: Once having assigned a certain type to a variable,
let it stick with that type. If you want to switch to a new type like str,
invent a new variable name for that new meaning.
That deals with the third assignment.
The disconnect on the first two assignments is a
more subtle issue of "meaning stability".
First we have a fraction on the unit interval 0 .. 1,
then the second assignment gives us a percentage 0 .. 100.
Better to keep a single meaning for that identifier, like z = 100 * x / y.
Then you'll spend less time worrying about bugs. | {
"domain": "codereview.stackexchange",
"id": 45282,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cs50",
"url": null
} |
python, cs50
requirements
There are code defects, and requirements defects.
This one is definitely not your fault.
And I'm sure the problem author was just trying to keep things simple.
The "tank fullness" fraction can only take on values in the unit interval 0 .. 1.
User input is constrained to be no more than one.
However, we do accept negative values, which seems unfortunate.
This code achieves its design goals.
I would be willing to accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45282,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cs50",
"url": null
} |
python-3.x, programming-challenge
Title: Advent of Code 2023 day 1: Trebuchet
Question: Part 1:
The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits and combining them into a two-digit number. The goal is to find the sum of all these calibration values.
For example:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
#!/usr/bin/env python3
import sys
import re
def main():
if len(sys.argv) != 2:
print("Error - No file provided.", file=sys.stderr)
total = 0
with open(sys.argv[1], "r") as f:
for line in f:
start, end = (
re.search(r"\d", line).group(),
re.search(r"\d", line[::-1]).group(),
)
total += int(start) * 10 + int(end)
print(f"Final value: {total}")
if __name__ == "__main__":
main()
Part 2:
In problem two, the calibration document may include digits spelled out with letters (e.g., "one," "two," etc.). The task is to identify the actual first and last digits in each line, taking into account both numerical digits and spelled-out numbers. The overall objective remains the same: find the sum of the calibration values obtained from combining the first and last digits of each line.
For example:
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.
#!/usr/bin/env python3
import sys
def main():
if len(sys.argv) != 2:
print("Error - No file provided.", file=sys.stderr)
digits = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
total = 0 | {
"domain": "codereview.stackexchange",
"id": 45283,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, programming-challenge",
"url": null
} |
python-3.x, programming-challenge
total = 0
with open(sys.argv[1], "r") as f:
for line in f:
start, end = 0, 0
for idx, ch in enumerate(line):
if ch.isdigit():
if not start:
start = int(ch)
end = int(ch)
else:
for digit in digits:
if line[idx:].startswith(digit):
if not start:
start = digits[digit]
end = digits[digit]
break
total += start * 10 + end
print(f"Final value: {total}")
if __name__ == "__main__":
main()
What is a simpler way to solve the problem? How do I reduce the nesting in part 2?
Answer: Bug
"1zero" is probably supposed to evaluate to 10. You don't handle the digit "zero".
Reversing the string
Your first approach relies on line[::-1] in order to search for the "last" digit, by pretending it is the first in the reversed string.
Instead, you could easily search for the last digit with a slight modification of the regular expression:
re.search(r".*(\d)", line).group(1)
The .* is greedy, so it will match as many characters as possible, and then backtrack to find a digit. This may or may not be as clear for single digits. Without a doubt, it will be clearer than searching for (say) "evif" in a reversed string, so is probably a better approach.
Matching digits/word-digits
You can expand your regex pattern to match "word-digits" as well as digits:
pattern = r"(\d|zero|one|two|three|four|five|six|seven|eight|nine)"
...
re.search(pattern, line)[1] | {
"domain": "codereview.stackexchange",
"id": 45283,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, programming-challenge",
"url": null
} |
python-3.x, programming-challenge
Searching for the last can be done by tacking .* to the front of the pattern as well.
To ints
You use int(digit) or digits[digit] to convert digit/strings into numbers. If you mapped the digit words to the digit characters in the dictionary, then you could look up the character (or word) in the dictionary, (defaulting to the value being looked up, if not present), and then convert than to an integer:
value = int(digits.get(token, token))
Code Organization
You should break your code into reusable functions. If in "Part 1", you had a calibration_total(lines) function, which summed the calibration_value(line) for each line, and calibration_value(line) called first_digit(line) and last_digit(line) functions to get the first and last digit values ...
def first_digit(line: str) -> int:
...
def last_digit(line: str) -> int:
...
def calibration_value(line: str) -> int:
return 10 * first_digit(line) + last_digit(line)
def calibration_total(lines: Iterable[str]):
return sum(map(calibration_value, lines))
def main():
if len(sys.argv) != 2:
print("Error - No file provided.", file=sys.stderr)
with open(sys.argv[1], "r") as f:
total = calibration_total(f)
print(f"Final value: {total}")
if __name__ == "__main__":
main()
then for "Part 2", you'd just be adjusting the first_digit and last_digit functions. The "driving portion" of the program would not have needed to be changed.
Eg:
import re
from typing import Iterable
DIGIT_NAMES = "zero one two three four five six seven eight nine".split()
DIGIT = {key: i for i, key in enumerate(DIGIT_NAMES)}
DIGIT_RE = rf'(\d|{"|".join(DIGIT_NAMES)})'
FIRST_DIGIT_PATTERN = re.compile(DIGIT_RE)
LAST_DIGIT_PATTERN = re.compile(".*" + DIGIT_RE)
def digit_to_int(digit: str) -> int:
return int(DIGIT.get(digit, digit))
def first_digit(line: str) -> int:
return digit_to_int(FIRST_DIGIT_PATTERN.search(line)[1]) | {
"domain": "codereview.stackexchange",
"id": 45283,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, programming-challenge",
"url": null
} |
python-3.x, programming-challenge
def first_digit(line: str) -> int:
return digit_to_int(FIRST_DIGIT_PATTERN.search(line)[1])
def last_digit(line: str) -> int:
return digit_to_int(LAST_DIGIT_PATTERN.search(line)[1]) | {
"domain": "codereview.stackexchange",
"id": 45283,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, programming-challenge",
"url": null
} |
rust, linux, mmap
Title: A simple mmap(2) wrapper
Question: I've written a wrapper for the mmap syscall. It's quite limited in functionality at the moment (there are lots of flags to support) but it's sufficient for mapping anonymous memory regions, which is what I need it for.
It already satisfies clippy, so I'm keen to understand some more advanced improvements that use Rust best-practices.
It's split into three files:
lib.rs containing an Error enum
mmap.rs containing an Mmap and MmapBuilder
syscall.rs containing wrapper for the mmap(2) syscall
lib.rs
#![allow(clippy::double_must_use)]
pub mod mmap;
pub mod syscall;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum Error {
System(i32),
NullPointer(&'static str),
}
impl std::error::Error for Error {}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::System(errno) => std::io::Error::from_raw_os_error(*errno).fmt(f),
Self::NullPointer(msg) => write!(f, "null pointer: {msg}"),
}
}
}
mmap.rs
use crate::Error;
use std::ops::{BitOr, Deref, DerefMut};
use std::ptr::NonNull;
/// Represents a memory region that has been mapped with `mmap(2)`.
///
/// This can only be constructed through the use of [`MmapBuilder`].
///
/// Note that using this memory is inherently unsafe because it can concurrently
/// read and written by other processes; the borrow checker has no power here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mmap {
addr: NonNull<u8>,
len: usize,
}
impl Mmap {
#[must_use]
pub fn builder() -> MmapBuilder {
MmapBuilder::new()
}
#[must_use]
pub fn anon(len: usize) -> Result<Mmap, Error> {
Self::builder().len(len).build()
}
}
impl Drop for Mmap {
fn drop(&mut self) {
crate::syscall::munmap(self.addr, self.len).expect("failed to unmap");
}
} | {
"domain": "codereview.stackexchange",
"id": 45284,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, linux, mmap",
"url": null
} |
rust, linux, mmap
impl AsRef<[u8]> for Mmap {
fn as_ref(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.addr.as_ptr(), self.len) }
}
}
impl AsMut<[u8]> for Mmap {
fn as_mut(&mut self) -> &mut [u8] {
unsafe { std::slice::from_raw_parts_mut(self.addr.as_ptr(), self.len) }
}
}
impl Deref for Mmap {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
impl DerefMut for Mmap {
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_mut()
}
}
/// A builder for mmapped memory regions.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct MmapBuilder {
len: usize,
prot: i32,
flags: i32,
fd: i32,
offset: i64,
visibility: Visibility,
addr: Option<NonNull<u8>>,
}
impl MmapBuilder {
#[must_use]
pub fn new() -> MmapBuilder {
MmapBuilder::default()
}
#[must_use]
pub fn len(mut self, len: usize) -> Self {
self.len = len;
self
}
#[must_use]
pub fn addr(mut self, addr: Option<NonNull<u8>>) -> Self {
self.addr = addr;
self
}
#[must_use]
pub fn visibility(mut self, visibility: Visibility) -> Self {
self.visibility = visibility;
self
}
#[must_use]
pub fn protection<I: Into<i32>>(mut self, protection: I) -> Self {
self.prot = protection.into();
self
}
#[must_use]
pub fn behavior<I: Into<i32>>(mut self, behavior: I) -> Self {
self.flags = behavior.into();
self
}
#[must_use]
pub fn fd(mut self, fd: i32) -> Self {
self.fd = fd;
self
}
#[must_use]
pub fn offset(mut self, offset: i64) -> Self {
self.offset = offset;
self
} | {
"domain": "codereview.stackexchange",
"id": 45284,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, linux, mmap",
"url": null
} |
rust, linux, mmap
#[must_use]
pub fn build(self) -> Result<Mmap, Error> {
let addr = crate::syscall::mmap(
self.addr,
self.len,
self.prot,
self.flags | self.visibility,
self.fd,
self.offset,
)?;
Ok(Mmap {
addr,
len: self.len,
})
}
}
#[derive(Default, Hash, Debug, Copy, Clone, Eq, PartialEq)]
pub enum Visibility {
#[default]
Private,
Shared,
}
impl From<Visibility> for i32 {
fn from(value: Visibility) -> Self {
match value {
Visibility::Private => libc::MAP_PRIVATE,
Visibility::Shared => libc::MAP_SHARED,
}
}
}
impl BitOr<Visibility> for Visibility {
type Output = i32;
fn bitor(self, rhs: Self) -> Self::Output {
i32::from(self) | i32::from(rhs)
}
}
impl BitOr<Visibility> for i32 {
type Output = i32;
fn bitor(self, rhs: Visibility) -> Self::Output {
self | i32::from(rhs)
}
}
#[derive(Default, Hash, Debug, Copy, Clone, Eq, PartialEq)]
pub enum Behavior {
#[default]
Anonymous,
}
impl From<Behavior> for i32 {
fn from(value: Behavior) -> Self {
match value {
Behavior::Anonymous => libc::MAP_ANONYMOUS,
}
}
}
impl BitOr<Behavior> for Behavior {
type Output = i32;
fn bitor(self, rhs: Self) -> Self::Output {
i32::from(self) | i32::from(rhs)
}
}
impl BitOr<Behavior> for i32 {
type Output = i32;
fn bitor(self, rhs: Behavior) -> Self::Output {
self | i32::from(rhs)
}
}
/// Memory protection flags for mmap.
#[derive(Default, Hash, Debug, Copy, Clone, Eq, PartialEq)]
pub enum Protection {
Exec,
Read,
Write,
#[default]
None,
} | {
"domain": "codereview.stackexchange",
"id": 45284,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, linux, mmap",
"url": null
} |
rust, linux, mmap
impl From<Protection> for i32 {
fn from(value: Protection) -> Self {
match value {
Protection::Exec => libc::PROT_EXEC,
Protection::Read => libc::PROT_READ,
Protection::Write => libc::PROT_WRITE,
Protection::None => libc::PROT_NONE,
}
}
}
impl BitOr<Protection> for Protection {
type Output = i32;
fn bitor(self, rhs: Self) -> Self::Output {
i32::from(self) | i32::from(rhs)
}
}
impl BitOr<Protection> for i32 {
type Output = i32;
fn bitor(self, rhs: Protection) -> Self::Output {
self | i32::from(rhs)
}
}
syscall.rs
use crate::Error;
use std::ptr::NonNull;
pub(crate) fn mmap(
addr: Option<NonNull<u8>>,
len: usize,
prot: i32,
flags: i32,
fd: i32,
offset: i64,
) -> Result<NonNull<u8>, Error> {
let ret = unsafe {
let ptr = addr.map(NonNull::as_ptr).unwrap_or(std::ptr::null_mut());
libc::mmap(ptr as *mut _, len, prot, flags, fd, offset)
};
if ret == libc::MAP_FAILED {
Err(Error::System(errno()))
} else {
NonNull::new(ret as *mut _).ok_or(Error::NullPointer("mmap returned null"))
}
}
pub(crate) fn munmap(addr: NonNull<u8>, len: usize) -> Result<(), Error> {
let ret = unsafe { libc::munmap(addr.as_ptr() as *mut _, len) };
if ret == -1 {
Err(Error::System(errno()))
} else {
Ok(())
}
}
#[must_use]
pub(crate) fn errno() -> i32 {
std::io::Error::last_os_error()
.raw_os_error()
.unwrap_or_default()
}
Answer: This looks pretty good overall.
All I am really missing is tests. Some methods and functions may be covered by unit tests.
Some further, rather opinionated, nitpicks: | {
"domain": "codereview.stackexchange",
"id": 45284,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, linux, mmap",
"url": null
} |
rust, linux, mmap
I don't like the ret variables in mmap and munmap. It's a bad name and they're only ever used once.
I also don't like the uncommented comparison to -1 in munmap. It's a magic number and may warrant a constant or a comment like // libc::munmap() failed. A good counter example of what I'd expect is your ret == libc::MAP_FAILED which is self-documenting.
Protection::None looks like you could remove it from the enum and use Option<Protection> on first glance. However, this would make implementing the BitOr stuff a nightmare, though I don't see it being used anywhere anyway. | {
"domain": "codereview.stackexchange",
"id": 45284,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, linux, mmap",
"url": null
} |
python, configuration, pydantic
Title: Python Runtime Config
Question: I am implementing runtime configuration for a python package. I am doing this in mypkg.config.__init__.py. The idea is to load the configuration from a JSON file into a ConfigManagerClass that uses a Pydantic model to validate and store the configuration. The ConfigManager lets users of the package update the config from another JSON file of their choice when needed.
Here's the code:
"""Runtime configuration for the package."""
import importlib.resources as pkg_resources
import json
from mypkg.pydantic.schemas import RuntimeConfigSchema
class RuntimeConfigManager():
with pkg_resources.open_text('mypkg.config', 'default.json') as f:
_config_json = json.load(f)
print('Loading default config')
_config = RuntimeConfigSchema(**_config_json)
print('Config loaded')
@classmethod
def set_config_file(cls, config_file):
"""Update runtime config from file."""
print(f'Updating config from {config_file}')
with open(config_file, 'r') as f:
cls._config_json = json.load(f)
cls._config = RuntimeConfigSchema(**cls._config_json)
print('Config updated')
@classmethod
def get_config(cls):
"""Get current runtime config."""
return cls._config
Is this idiomatic? Are there any failure cases to be aware of?
The package is compatible with Python >=3.8.10, <3.10
Answer:
Is this idiomatic?
Largely it is, yes.
clean import
We strive to minimize side effects at import time,
deferring them until some caller actually calls into the library code.
print('Loading default config')
_config = ...
print('Config loaded') | {
"domain": "codereview.stackexchange",
"id": 45285,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, configuration, pydantic",
"url": null
} |
python, configuration, pydantic
Signalling to other engineers that _config is private works nicely.
The pair of print()'s produce a side effect on stdout
and there's no provision to turn that off.
Prefer to use a
logger
at DEBUG priority.
A caller should be able to pull in this module, say from a
unit test,
and see the import succeed silently.
Similarly for set_config_file.
deprecated function
The package is compatible with Python >=3.8.10, <3.10
Thank you for calling that out.
I am reading the docs:
Deprecated since version 3.11: Calls to this function can be replaced by open().
It would be worth noting that in a # comment or """docstring""",
perhaps at module level.
I imagine you wrote this for a project that happens
to be at cPython 3.8, so you just went with what works.
Consider writing a different classfunction that a 3.12 app
could successfully call.
Consider writing down a sentence or two on "roadmap" or "transition plans".
My concern is that it would be sad for a developer to take
a dependency on this class, and then feel constrained
to ancient interpreters as 3.15 and 3.16 roll out.
getter
@classmethod
def get_config(cls):
"""Get current runtime config."""
return cls._config
This is nice enough.
The _private class attribute is clear,
and we offer no setter.
But are we really concerned that some engineer will
feel emboldened to write crazy stuff onto the config?
We're all adults here.
My reading is that maybe we don't need this getter at all,
and a public cls.config identifier might be the appropriate spelling.
Recall that if you change your mind later,
you can always introduce a @property for the getter,
with no change to app-level callers.
The part of my proposal that's visible at the app level
is whether access is (roughly) through config() or through config.
That second form can still work out to a method call
once a property is involved. | {
"domain": "codereview.stackexchange",
"id": 45285,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, configuration, pydantic",
"url": null
} |
python, configuration, pydantic
helper
I am looking at the _config_json class attribute and thinking
that maybe we just created it by accident?
The cool thing about helper functions is that all local variables
disappear once we return and they go out-of-scope.
I'm thinking that maybe the with should call a helper
which defines a config json temp var,
and then the temp var evaporates upon return.
Down in set_config_file we assign cls._config_json for consistency.
But it seems like it wants to be an ephemeral local variable there.
This code achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45285,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, configuration, pydantic",
"url": null
} |
python, cache, git, docker, dockerfile
Title: How to reduce the build time of Docker image layer in GitHub Actions?
Question: I have a Dockerfile with ubuntu:22.04 as a base image and a manual Python installation(specific version i.e., 3.11.1) layer which takes a long time.
Approach 1:
Build a custom_image with ubuntu:22.04 as a base image and a manual Python installation layer.
Create another Dockerfile with custom_image as the base image and add other layers of the image
Cache the custom_image using docker/build-push-action@v5 action
Approach 2:
Use ubuntu-latest runner with actions/setup-python GitHub action with a specific version.
Once Python setup is successful, copy Python binaries to Docker context like cp -r $RUNNER_TOOL_CACHE/Python/3.11.1/* Python/3.11.1
Copy these files into docker and update the PATH variable like
# Copy Python binaries from the GitHub Actions workflow
COPY Python /opt/Python
# Update PATH to include the copied Python binaries
ENV PATH="/opt/Python/3.11.1/x64/bin:/opt/Python/3.11.1/x64:${PATH}"
# Set the LD_LIBRARY_PATH to include the copied shared libraries
ENV LD_LIBRARY_PATH="/opt/Python/3.11.1/x64/lib:${LD_LIBRARY_PATH}"
Dockerfile:
FROM --platform=linux/amd64 ubuntu:22.04 as base
USER root
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
ENV DEBIAN_FRONTEND noninteractive
COPY . /app
WORKDIR /app
COPY ZscalerRootCertificate-2048-SHA256.crt /usr/local/share/ca-certificates/ZscalerRootCertificate-2048-SHA256.crt
# Copy Python binaries from the GitHub Actions workflow
COPY Python /opt/Python
# Update PATH to include the copied Python binaries
ENV PATH="/opt/Python/3.11.1/x64/bin:/opt/Python/3.11.1/x64:${PATH}"
# Set the LD_LIBRARY_PATH to include the copied shared libraries
ENV LD_LIBRARY_PATH="/opt/python/lib:${LD_LIBRARY_PATH}"
# Fail soon than later, if python wasn't installed
RUN python --version
RUN apt-get update && \
apt-get upgrade -y && \
apt-get install -y software-properties-common ca-certificates && \
update-ca-certificates | {
"domain": "codereview.stackexchange",
"id": 45286,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cache, git, docker, dockerfile",
"url": null
} |
python, cache, git, docker, dockerfile
RUN python -m pip install -U pip
RUN python3.11 -m pip install --no-cache-dir --trusted-host pypi.org --trusted-host files.pythonhosted.org -r requirements/core-requirements.txt
GitHub workflow:
name: Docker Image CI
env:
CONTAINER_NAME: my-use-case
on:
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
permissions:
id-token: write
contents: write
jobs:
integration-tests:
name: Integration Test
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: View directory files
run: |
pwd
echo "$PATH"
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.11.1"
- name: Copy Python binaries to Docker context
run: |
mkdir -p Python/3.11.1
cp -r $RUNNER_TOOL_CACHE/Python/3.11.1/* Python/3.11.1
- name: View directory files
run: |
ls -lhR
echo "$PATH"
- name: Install dependencies
run: |
python --version
python -m pip install --upgrade pip
- name: View directory files
run: |
ls -lhR
- name: Build & push docker image
uses: docker/build-push-action@v2
with:
context: .
push: false
tags: ${{ env.CONTAINER_NAME }}:${{ github.run_number }}
file: ./Dockerfile
Answer:
COPY ZscalerRootCertificate-2048-SHA256.crt /usr/local/share/ca-certificates/ZscalerRootCertificate-2048-SHA256.crt
The command here runs, presumably, on a file.
When Docker performs the copy, Docker compares the file with the file in the cache.
If the files are deemed to be the same then Docker skips the step and moves on using the previously cached image.
As such if you have the above COPY before any other COPYs then the copy will be cached.
COPY . /app
COPY Python /opt/Python | {
"domain": "codereview.stackexchange",
"id": 45286,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cache, git, docker, dockerfile",
"url": null
} |
python, cache, git, docker, dockerfile
COPY . /app
COPY Python /opt/Python
Copying directories to the docker build scope invalidates the cache. And acts as if the files are not the same, even if the files are the same.
If you can change the action to be copying a file (say a .zip or .tar.bz) then you can cache the interaction.
RUN apt-get update && \
apt-get upgrade -y && \
apt-get install -y software-properties-common ca-certificates && \
update-ca-certificates
I don't see why the above RUN command needs to be below the COPY operations. If you don't want to copy an archive then you probably can move the command higher to allow caching to happen.
RUN python -m pip install -U pip
RUN python3.11 -m pip install --no-cache-dir --trusted-host pypi.org --trusted-host files.pythonhosted.org -r requirements/core-requirements.txt
Likewise I'm not sure you need to run the commands after any of the COPY commands.
You can have a single COPY command for the requirements, and possibly any configs you need.
Additionally I normally position the commands in a builder which focuses on building a venv.
I use the standardized python image for the version I'm building against. I then copy the files to optimize caching and then just have a fat 'copy everything and don't care about caching' core.
# Not version pinned, doesn't work
FROM python:3 AS builder
WORKDIR /build
RUN python -m pip install virtualenv
RUN python -m virtualenv venv
COPY requirements.txt requirements.txt
RUN venv/bin/python -m pip install -r requirements.txt
# invalidates the cache
COPY . .
RUN venv/bin/python -m pip install .
FROM nginx/unit:1.26.1-python3.10
EXPOSE 80
EXPOSE 443
VOLUME ["/app/.data"]
WORKDIR /app
ENV PATH /app/venv/bin:$PATH
# no caching needed
COPY nginx_config.json /docker-entrypoint.d/config.json
COPY --from=builder /build/venv venv # copy the venv from the builder
RUN chown unit:unit -R .data venv | {
"domain": "codereview.stackexchange",
"id": 45286,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cache, git, docker, dockerfile",
"url": null
} |
python, cache, git, docker, dockerfile
In more intricate builders I have copied configs and SSH keys to the builder and know the files won't be in the final image. Reducing the clean-up steps. | {
"domain": "codereview.stackexchange",
"id": 45286,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cache, git, docker, dockerfile",
"url": null
} |
c, programming-challenge
Title: Advent of Code 2023 day 1: Trebuchet (Part 1 and 2)
Question: Part 1:
The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits and combining them into a two-digit number. The goal is to find the sum of all these calibration values.
For example:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
/* This would more than just suffice for the sample data. */
#define BUFSIZE 1024
static size_t calibration_value(const char *buf)
{
size_t start = 0;
size_t end = 0;
/* Note: This would return true for 0, but 0 is not part of the
* problem specification, or the input, so we don't need to check
* for it.
*/
for (size_t i = 0; buf[i]; ++i) {
if (isdigit((unsigned char) buf[i])) {
start = !start ? buf[i] - '0' : start;
end = buf[i] - '0';
}
}
return start * 10 + end;
}
static size_t calibration_total(FILE *stream)
{
char buf[BUFSIZE];
size_t total = 0;
while (fgets(buf, sizeof buf, stream)) {
total += calibration_value(buf);
}
return total;
}
int main(int argc, char **argv)
{
if (!argv[0]) {
fputs("Fatal - A null argv[0] was passed in.", stderr);
return EXIT_FAILURE;
}
if (argc != 2) {
fprintf(stderr, "Error - No file provided.\n"
"Usage: %s <FILE>\n", argv[0]);
return EXIT_FAILURE;
}
FILE *const fname = (errno = 0, fopen(argv[1], "r"));
if (!fname) {
errno ? perror(argv[1]) : (void) fputs("Error - Failed to open file.", stderr);
return EXIT_FAILURE;
}
printf("%zu\n", calibration_total(fname));
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45287,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge",
"url": null
} |
c, programming-challenge
printf("%zu\n", calibration_total(fname));
return EXIT_SUCCESS;
}
Part 2:
In part two, the calibration document may include digits spelled out with letters (e.g., "one," "two," etc.). The task is to identify the actual first and last digits in each line, taking into account both numerical digits and spelled-out numbers. The overall objective remains the same: find the sum of the calibration values obtained from combining the first and last digits of each line.
For example:
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
In this example, the calibration values are 29, 83, 13, 24, 42, 14, and 76. Adding these together produces 281.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>
#define INIT_DMAP(_name, _val) {.dname = _name, .val = _val}
struct digit_map {
const char *const dname;
const unsigned int val;
} digits[] = {
INIT_DMAP("one", 1),
INIT_DMAP("two", 2),
INIT_DMAP("three", 3),
INIT_DMAP("four", 4),
INIT_DMAP("five", 5),
INIT_DMAP("six", 6),
INIT_DMAP("seven", 7),
INIT_DMAP("eight", 8),
INIT_DMAP("nine", 9)
};
/* This would more than just suffice for the sample data. */
#define BUFSIZE 1024
static size_t calibration_value(const char *buf)
{
unsigned int start = 0;
unsigned int end = 0; | {
"domain": "codereview.stackexchange",
"id": 45287,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge",
"url": null
} |
c, programming-challenge
for (size_t i = 0; buf[i]; ++i) {
/* Note: This would return true for 0, but 0 is not part of the
* problem specification, or the input, so we don't need to check
* for it.
*/
if (isdigit((unsigned char) buf[i])) {
start = !start ? buf[i] - '0' : start;
end = buf[i] - '0';
} else {
for (size_t j = 0; j < sizeof digits / sizeof *digits; ++j) {
if (!strncmp(buf + i, digits[j].dname, strlen(digits[j].dname))) {
start = !start ? digits[j].val : start;
end = digits[j].val;
}
}
}
}
return start * 10 + end;
}
static size_t calibration_total(FILE *stream)
{
char buf[BUFSIZE];
size_t total = 0;
while (fgets(buf, sizeof buf, stream)) {
total += calibration_value(buf);
}
return total;
}
int main(int argc, char **argv)
{
if (!argv[0]) {
fputs("Fatal - A null argv[0] was passed in.", stderr);
return EXIT_FAILURE;
}
if (argc != 2) {
fprintf(stderr, "Error - No file provided.\n"
"Usage: %s <FILE>\n", argv[0]);
return EXIT_FAILURE;
}
FILE *const fname = (errno = 0, fopen(argv[1], "r"));
if (!fname) {
errno ? perror(argv[1]) : (void) fputs("Error - Failed to open file.", stderr);
return EXIT_FAILURE;
}
printf("Total: %zu\n", calibration_total(fname));
return EXIT_SUCCESS;
}
What improvements can be made to the code?
Note: 0/zero isn't part of the input, nor is included in the problem specification, so it is not a valid digit. | {
"domain": "codereview.stackexchange",
"id": 45287,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge",
"url": null
} |
c, programming-challenge
Answer: Don't assume all lines will fit into a fixed-size buffer
You use a buffer with a hardcoded size of 1024 characters. As you write in the comments, it suffices for the sample data. But what if you would use this code on a different input that could have arbitrarily long lines?
The problem is not so much the size of the buffer, but rather that you assume each and every line in the input will fit into that buffer. I see two possible ways to make it more robust:
Use the POSIX getline() function. It will allocate a large enough buffer for you.
Use the fixed size buffer, but check if it actually contains the newline character '\n'. If not, keep the intermediate start and end value,fgets() again, and then continue updating start and end, until you actually do see the end of the line.
The former option is easy, but might use a lot of memory. The second option is a little bit more work but will work even if you have very little memory.
Inappropriate use of size_t
size_t should be used for sizes, counts and indices. So it's the right type to use for the loop counter i for example. However, calibrarion_value() can only return a value of at most 99, so size_t is complete overkill here. I recommend just using unsigned int here as it's large enough, and usually the fastest for the CPU to work with as well.
On the other hand, the input file might actually be larger than would fit into memory, and size_t might be too small for total. It's better to use a fixed-size integer type: either you know the largest value you expect and you can choose the proper type accordingly, or just use uintmax_t.
Avoid comma and ternary operator tricks
While it might be "smart" and result in a bit more compact code, avoid using tricks using the comma operator or ternary operator. Just write multiple statements and regular if-statements:
errno = 0;
FILE *const fname = fopen(argv[1], "r"); | {
"domain": "codereview.stackexchange",
"id": 45287,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge",
"url": null
} |
c, programming-challenge
if (!fname) {
if (errno) {
perror(argv[1]);
} else {
fputs("Error - Failed to open file.", stderr);
}
return EXIT_FAILURE;
}
While it is more verbose, it is easier to understand, meaning the code will be more maintainable and will have less chance of bugs.
Naming
If I see a variable named fname, I might think that this is a string holding a filename. However, it is a pointer to the FILE object itself. I would rather call it file.
Missing error handling
While you check for errors when opening a file, you don't check for errors while reading from it. I/O errors can happen at any point. Check that feof(stream) is true at the end of calibration_total(); if it's not then you know something happened before getting to the end of the file. Print an error message and return EXIT_FAILURE in this case.
INIT_DMAP is unnecessary
You don't need this macro. Simply write:
struct digit_map {
const char *const dname;
const unsigned int val;
} digits[] = {
{"one", 1},
{"two", 2},
…
};
The order of the member variables is right there at the top, so it's hard to make a mistake here.
Performance
In part two, you use a very simple algorithm to find digits spelled out with letters. However, it means that for almost every non-numeric character, you use 10 calls to strncmp(). A better solution might be to use a prefix tree.
Also, once you have found a word describing a digit, then you can also know how many characters you can skip. For example, if you found "seven", you know that you can skip the next three characters ("eve"), and continue from the "n" (as that might become a "nine").
However, if you are interested in improving performance, don't blindly implement a different algorithm, actually measure the performance of all the alternatives on some representative input. | {
"domain": "codereview.stackexchange",
"id": 45287,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, programming-challenge",
"url": null
} |
python, cryptography, websocket
Title: Encryption implementation for websocket chat (RSA + AES)
Question: For learning purposes I am trying to make a encrypted chat in Python using Websockets. I am using AES and RSA to make it safe.
The idea of the chat is that it's a group-chat. Users can join a chat by running python3 client.py --password=pass123.
This is how it works.
The server has already generated a RSA keypair.
The client enters a password when running the client.py script.
The client requests the public key from the server > the server sends this key to the client.
The client encrypts the password using the public RSA key and sends the encrypted string to the server.
The server decrypts the encrypted string using the private RSA-key so it knows the password the client has inputted.
Using that password the server generates a derived key using PBKDF2_HMAC and a Bcrypt-salt (the Bcrypt-salt is rotated for each chat-session).
The server sends the derived key back to the client. (Isn't this a vulnerability??)
The client generates a AES-key (ECB).
All messages sent to the server are encrypted using this AES-key.
With this implementation multiple clients can communicate in a chat. But they'll only be able to read the messages sent if they all entered the same password. Someone trying to join the chat with a different password will only see encrypted garbage. Also the server only sees encrypted garbage.
I made a simplified code showing my implementation.
server.py
import asyncio
import websockets
import binascii
import bcrypt
import hashlib
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 1. Generate a RSA-keypair.
keypair = RSA.generate(3072)
publicKey = keypair.publickey()
publicKeyPEM = publicKey.exportKey()
privateKeyPEM = keypair.exportKey() | {
"domain": "codereview.stackexchange",
"id": 45288,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, websocket",
"url": null
} |
python, cryptography, websocket
# Function to handle connection (Only one connection and one client in this simplified code).
async def handle_connection(websocket, url):
# Server sends public key to client after client requested it.
await websocket.recv()
await websocket.send(publicKeyPEM.decode('ascii'))
# 5. Server decrypts encrypted password using private key.
decryptor = PKCS1_OAEP.new(keypair)
decryptedPassword = decryptor.decrypt(binascii.unhexlify(await websocket.recv()))
# 6. Generate derived key using password.
salt = bcrypt.gensalt() # (Salt unique for each chat session).
derivedKey = hashlib.pbkdf2_hmac('sha-256', decryptedPassword, salt, 600000)
# 7. Server sends derived key back to client.
# (Note: The derived key is sent unencrypted. Only SSL in real life).
await websocket.send(binascii.hexlify(derivedKey).decode('utf-8'))
# Finally: Receive and echo back some messages
incomingMessage = await websocket.recv()
print(incomingMessage)
await websocket.send(incomingMessage)
incomingMessage = await websocket.recv()
print(incomingMessage)
await websocket.send(incomingMessage)
start = websockets.serve(handle_connection, "localhost", 1234)
asyncio.get_event_loop().run_until_complete(start)
asyncio.get_event_loop().run_forever()
client.py
import asyncio
import websockets
import hashlib
import bcrypt
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import binascii
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 2. Client enters a password.
password = b'pass123'
async def connect():
url = "ws://localhost:1234"
async with websockets.connect(url) as websocket:
# 3. Request public RSA key.
await websocket.send("rsa-key-request")
publicKey = RSA.import_key(await websocket.recv()) | {
"domain": "codereview.stackexchange",
"id": 45288,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, websocket",
"url": null
} |
python, cryptography, websocket
# 4. Encrypt password using public key and send it to server.
encryptor = PKCS1_OAEP.new(publicKey)
encryptedPassword = encryptor.encrypt(password)
await websocket.send(binascii.hexlify(encryptedPassword).decode('utf-8'))
# 8. Client receives derivedKey and makes AES key
derivedKey = binascii.unhexlify(await websocket.recv())
aesKey = AES.new(derivedKey, AES.MODE_ECB)
# Finally: Send few messages as example
# Msg 1
encryptedMessage = aesKey.encrypt(pad(b'Hello', AES.block_size, style='pkcs7'))
await websocket.send(binascii.hexlify(encryptedMessage).decode('utf-8'))
answer = binascii.unhexlify(await websocket.recv())
decryptedAnswer = unpad(aesKey.decrypt(answer), AES.block_size, style='pkcs7').decode('utf-8')
print(decryptedAnswer)
# Msg 2
encryptedMessage = aesKey.encrypt(pad(b'Rofl 123', AES.block_size, style='pkcs7'))
await websocket.send(binascii.hexlify(encryptedMessage).decode('utf-8'))
answer = binascii.unhexlify(await websocket.recv())
decryptedAnswer = unpad(aesKey.decrypt(answer), AES.block_size, style='pkcs7').decode('utf-8')
print(decryptedAnswer)
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(connect())
Output:
# server.py
1a0dc63afa380c18190eed51a66d18a0
c85b61942e3115579cf4441a10020e20
# client.py
Hello
Rofl 123
Notes:
In real I'd use SSL for my websocket connections.
The simplified code does not support multiple clients.
Questions: | {
"domain": "codereview.stackexchange",
"id": 45288,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, websocket",
"url": null
} |
python, cryptography, websocket
Questions:
Is this a good implementation for encryption in a chat?
I used RSA because I read that RSA was a good way send the derived key from client to server. But I don't understand: The AES key is generated from the derived key. The password entered by the client is send encrypted to the server. But the derived key used for the AES is send unencrypted from the server to the client. Couldn't someone with bad intentions not just intercept this derived key and use that to generate the same AES-key?
I first thought it would make more sense to let the client generate a derived key and set it encrypted to the server. But each client would have a different salt?
If my implementation is wrong, what to change?
Other things to consider?
Answer:
Is this a good implementation for encryption in a chat?
No.
I'd argue that most chat implementations are not dependent on the server to decrypt / reencrypt the information (this is called a proxy in cryptography). This is not the end-to-end encryption that e.g. Signal or even WhatsApp uses.
Step 3 is insecure. There is a need to trust the public key of the server. This is why your browser contain a list of trusted (root) certificates. Although most users are unaware, we trust the CA's that issued those root certificates by trusting the producers of the browser (and this is how many browser manufacturers also try and get some money).
You have used the correct primitives such as PBKDF2, AES and RSA. However, you do use AES in ECB mode, which is known to be insecure for encrypting arbitrary messages.
I used RSA because I read that RSA was a good way send the derived key from client to server. But I don't understand: The AES key is generated from the derived key. The password entered by the client is send encrypted to the server. But the derived key used for the AES is send unencrypted from the server to the client. Couldn't someone with bad intentions not just intercept this derived key and use that to generate the same AES-key? | {
"domain": "codereview.stackexchange",
"id": 45288,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, websocket",
"url": null
} |
python, cryptography, websocket
Yes, they could and this is not a good protocol.
It is possible derive a master / session key using key agreement (DH). Generally it is best to only use the password for authentication.
It is said that in real life TLS is used, but I'd argue that in that case you might as well send the password unencrypted from client to server. That is what HTTP basic authentication does - as there is already an established secure channel where the server is trusted.
I first thought it would make more sense to let the client generate a derived key and set it encrypted to the server. But each client would have a different salt?
Salts can be send to the other side unencrypted; they don't need to be secret.
If my implementation is wrong, what to change?
I don't know, but if I read this text then I'm pretty sure that you are a novice at this. In that case you'd start by studying what is already out there.
Other things to consider?
Yeah, don't be proud and don't think you can create a secure chat from scratch. To do that it is important to first learn what is out there.
Crypto remarks
AES should be using an authenticated mode such as AES-GCM. Currently the protocol uses ECB which is not secure for a transport mode. Actually, it seems the implementation doesn't even protect the confidentiality of messages as it fails to protect against plaintext and particularly padding oracle attacks.
Salts are usually just 16 to 32 random bytes. There is no need to depend on code of bcrypt if PBKDF2 is used for the actual implementation. | {
"domain": "codereview.stackexchange",
"id": 45288,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, websocket",
"url": null
} |
python, cryptography, websocket
"With this implementation multiple clients can communicate in a chat. But they'll only be able to read the messages sent if they all entered the same password. Someone trying to join the chat with a different password will only see encrypted garbage. Also the server only sees encrypted garbage."
That's a claim that isn't true at all. I don't see how the server is supposed to authenticate & trust the clients. Nor do I see how the client is supposed to authenticate & trust the server. The protocol only partially protects against eavesdropping by an adversary, and that is not considered enough security by anyone.
It is always a good idea to create a good description of the protocol. Currently I don't see any way to e.g. update the iteration count, which is set at 600000 (using a literal, which is also not great).
Other remarks
Websockets are perfectly able to send out binary data. Funny enough we see that hexlify is used followed by a "decoding" to a string. If the HTTP protocol & API is followed then it is easy to see that binary can be send without converting to text.
Conclusion
Sorry to be a bit harsh here, but this protocol doesn't add much on top of TLS. The code is easy to read. It should however be considered a learning exercise and nothing more. | {
"domain": "codereview.stackexchange",
"id": 45288,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, websocket",
"url": null
} |
programming-challenge, rust
Title: Advent of Code 2023, Day 8 Part 1 - Beginner Rust Solution
Question: Context
I'm doing Advent of Code as a way of learning Rust, and have a working solution to Day 8, Part 1. This involves moving between nodes, starting at AAA and looking for ZZZ, where the next node is determined by the L/R instruction chain in the first line. We loop over the L/R instruction set until ZZZ is found. Some of the example input is given below.
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
I think the logic I used here is ok, but I expect my code to the solution does not take advantage of Rust's strengths. I know, for example, that I am being lazy by using .unwrap() instead of handling an Option.
My Code
use regex::Regex;
use std::collections::HashMap;
use std::fs;
const FILE: &str = "../inputs/day8_1.txt";
fn parse_inputs(filename: &str) -> (Vec<char>, HashMap<String, Vec<String>>) {
let mut node_map: HashMap<String, Vec<String>> = HashMap::new();
let file = fs::read_to_string(filename).expect("File read failure");
let (directions, nodes) = file.split_once("\n\n").unwrap();
let rgx = Regex::new(r"(\w{3})").unwrap();
for line in nodes.lines() {
let matches: Vec<String> = rgx
.find_iter(line)
.map(|x| x.as_str().to_string())
.collect();
node_map.insert(
matches[0].clone(),
vec![matches[1].clone(), matches[2].clone()],
);
}
(directions.chars().collect::<Vec<char>>(), node_map)
}
fn main () {
let mut step_count: u32 = 0;
let mut point = "AAA".to_string();
let (directions, data) = parse_inputs(FILE);
let direction_map = HashMap::from([('L', 0), ('R', 1)]);
let mut indexer: usize = 0;
let max_index = directions.len() - 1; | {
"domain": "codereview.stackexchange",
"id": 45289,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
while point != "ZZZ".to_string() {
let d: usize = direction_map[&directions[indexer]];
point = data[&point][d].clone();
if indexer < max_index {
indexer += 1;
} else {
indexer = 0;
}
step_count += 1
}
println!("Part One: {:?}", step_count)
}
Review Request
I'm looking for advice on how this code might follow a more idiomatic Rust style. I think I am probably brute forcing my way through the compiler here, as I'm having to clone values to get past the borrowing rules. I suspect that I could write the code in a more intelligent way to avoid cloning. I also know that I could (and should) actually handle errors and options, but I'm not sure how best to do that here.
Answer: I honed my Rust through Advent of Code as well, so welcome to the club. I can tell you with hindsight that trying to handle errors in a formal way for early days with relatively simple input structures and problems is not really worth the hassle. The errors that could arise here are almost exclusively from the input itself, which is an essentially completely theoretical possibility in the case of AoC. At this point, getting used to using the ? operator in general is more important. Later on, once you'll be doing more complex operations where errors can actually practically arise from your own code, you can worry about being more methodical1. In this case, you could simply make both parse_inputs and main return a Result<T, Box<dyn Error>> (where T is what they were returning before, or () in the case of nothing) and replace unwraps with ?.
With that out of the way, some more specific suggestions in no particular order: | {
"domain": "codereview.stackexchange",
"id": 45289,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
(directions.chars().collect::<Vec<char>>(), node_map) does not require an explicit type annotation (Vec<char>) because this is the return value and the type of the return value is explicitly specified already in the function's header. This also extends to node_map further up in the function for the same reason, and the definitions of step_count and indexer in the main function. Even more subtly, even when a type annotation is required, it may not need to be entirely explicit. For instance, when defining matches, you do need to specify that it is a Vec for collect. But the element types are already clear, so you can simply ask the compiler to infer it using an underscore: let matches: Vec<_>.
In general, explicit type annotations are actually fairly rare in Rust, and you should generally try removing them, even after a program compiles, just to see if they're necessary. Over time, you will intuit when they are likely to be needed and the friction will decrease.
The Iterator trait is extraordinarily useful, and it is worth looking through it any time you're trying to do anything to do with iterators (which is essentially all of the time). In this case, Iterator::cycle can help make your main loop more clear. Instead of keeping track of an indexer and max_index, you can simply:
for dir in directions.iter().cycle() {
let d: usize = direction_map[dir];
point = data[&point][d].clone();
step_count += 1
if point == "ZZZ".to_string() {
break;
}
}
Opinions may vary as to the extent of this improvement, but in my view it makes what you're doing with directions more clear as it eliminates the mental overhead of 2 variables.
Another general tip with Iterator is: don't collect too hastily. In the case of matches, you can avoid the overhead of a Vec by simply leaving the collect out and using .next().unwrap(). This is not just a matter of an altogether trivial optimization, as will hopefully be made clear. | {
"domain": "codereview.stackexchange",
"id": 45289,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
programming-challenge, rust
let matches = rgx
.find_iter(line)
.map(|x| x.as_str().to_string());
let node = matches.next().unwrap();
let left = matches.next().unwrap();
let right = matches.next().unwrap();
node_map.insert(node, vec![left, right]);
Now you may argue that this introduces unwraps where there previously were none, which is true. However, since Vec indexing panics on index out of bounds, this in fact only makes the risk more explicit. These can now be converted to ?. (though not directly: next returns an Option, not a Result, but it is simple to convert between the two: e.g ok_or and related methods) This also eliminates 3 clones, which while not terribly expensive, are a bit unsightly.2
Related to the above point is that since left and right always form 2 elements, you can simply contain them in a tuple instead of a Vec: (String, String) at no cost to simplicity at all.
The direction_map seems like a layer of unnecessary indirection to me where a simple if statement would be equivalent, but that is your choice to make, ultimately, it has little relevance to Rust idiomacity specifically.
The other clone in your code, point = data[&point][d].clone() can be eliminated simply by removing the to_string in the definition of point, which downgrades it from a String to an &str. You can still compare &strs to each other, so it works fine.
Footnotes
When you do eventually need or want to get more methodical, see the crates anyhow and thiserror for approaches to error handling. But don't get sucked in too early: the practical differences between them will seem esoteric and not clearly motivated.
If you're not clear on how those clones were necessary and why they're gone now, Vec<T> indexing returns values of type &T, but using next on an Iterator<Item = T> explicitly consumes part of the iterator and so returns a T. | {
"domain": "codereview.stackexchange",
"id": 45289,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, rust",
"url": null
} |
c++, c++20, sfml
Title: Basic foundation for a physics engine using SFML and Dear ImGui
Question: I want to create a very basic physics engine in SFML. I also want to be able to control objects using Dear ImGui. So I created this basic foundation. My main problem with it is how I handle rendering the GUI, because I couldn't find another way to implement it, either just drawing an object, or drawing object and a GUI. Mainly because the draw function must be const.
This is supposed to be able to handle both objects that have a GUI (IEntityWithGui) and those that don't (IEntity). But in this example there's just objects with a GUI.
main.cpp:
#include <iostream>
#include <SFML/Graphics.hpp>
#include "imgui/imgui.h"
#include "imgui/imgui-SFML.h"
#include "updater.h"
#include "renderer.h"
#include "shapeObj.h"
int main() {
sf::RenderWindow window(sf::VideoMode(200, 200), "PhysicsBox");
ImGui::SFML::Init(window);
sf::Clock clock;
std::atomic<bool> isRunning{ true };
ShapeObj shape{window};
Renderer render{ &window,isRunning };
render.queueSubmit(&shape);
Updater update{ &window,isRunning,std::ref(clock) };
update.queueSubmit(&shape);
window.setActive(false);
window.setKeyRepeatEnabled(false);
update.startThread();
render.startThread(); | {
"domain": "codereview.stackexchange",
"id": 45290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, sfml",
"url": null
} |
c++, c++20, sfml
update.startThread();
render.startThread();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
ImGui::SFML::ProcessEvent(event);
if (event.type == sf::Event::Closed) {
isRunning.store(false);
render.joinThread();
update.joinThread();
window.setActive(true);
window.close();
}
if (event.type == sf::Event::Resized)
{
// update the view to the new size of the window
sf::FloatRect visibleArea(0.f, 0.f, event.size.width, event.size.height);
window.setView(sf::View(visibleArea));
}
shape.eventProcess(event, clock.restart());
}
}
ImGui::SFML::Shutdown();
return 0;
}
IEntity.h:
#pragma once
#include <SFML/Graphics.hpp>
class IEntity : public sf::Drawable, public sf::Transformable
{
public:
virtual void update(sf::Time dt)=0;
virtual void eventProcess(sf::Event event,sf::Time dt)=0;
virtual ~IEntity(){}
};
IEntityWithGui:
#pragma once
#include "IEntity.h"
class IEntityWithGui : public IEntity
{
public:
virtual void processGui()=0;
virtual ~IEntityWithGui() {}
};
shapeObj.hpp:
#pragma once
#include "IEntityWithGui.h"
class ShapeObj : public IEntityWithGui
{
public:
ShapeObj(sf::RenderWindow &window);
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
virtual void update(sf::Time deltaTime) override ;
virtual void processGui() override;
virtual void eventProcess(sf::Event event, sf::Time time) override;
virtual ~ShapeObj()=default;
private:
sf::CircleShape m_shape{ 100.f,75 };
sf::RenderWindow& m_window;
bool m_show_gui = false;
bool m_mouse_captured = false;
};
ShapeObj.cpp:
#include "shapeObj.h"
#include "imgui/imgui.h"
#include "imgui/imgui-SFML.h" | {
"domain": "codereview.stackexchange",
"id": 45290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, sfml",
"url": null
} |
c++, c++20, sfml
ShapeObj.cpp:
#include "shapeObj.h"
#include "imgui/imgui.h"
#include "imgui/imgui-SFML.h"
ShapeObj::ShapeObj(sf::RenderWindow& window)
: m_window(window) {};
void ShapeObj::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform *= getTransform();
target.draw(m_shape, states);
}
void ShapeObj::update(sf::Time deltaTime)
{
//It will be used, just not now.
}
void ShapeObj::processGui()
{
if (!m_show_gui) return;
ImGuiIO io = ImGui::GetIO();
ImGui::SFML::Update(m_window, sf::seconds(1.f / 60.f));
ImGui::Begin("Grid");
if (io.WantCaptureMouse) {
m_mouse_captured = true;
}
else {
m_mouse_captured = false;
}
ImGui::Text("Mouse captured=%d\n",
m_mouse_captured);
ImGui::End();
ImGui::SFML::Render(m_window);
}
void ShapeObj::eventProcess(sf::Event event, sf::Time time)
{
auto mousePos= m_window.mapPixelToCoords(sf::Mouse::getPosition(m_window));
if (!m_mouse_captured) {
if(event.type==sf::Event::MouseButtonPressed &&
m_shape.getGlobalBounds().contains(mousePos))
{
m_show_gui = !m_show_gui;
}
//Whatever other events
}
}
threadWithQueue.h:
#pragma once
#pragma once
#include <SFML/Graphics.hpp>
#include <vector>
#include <thread>
template <class T>
class ThreadWithQueue {
public:
ThreadWithQueue<T>(sf::RenderWindow* window, std::atomic<bool>& isRunning);
void startThread();
void joinThread();
virtual void queueSubmit(T object);
protected:
virtual void queueThread()=0;
std::atomic<bool>& isRunning;
sf::RenderWindow* m_window;
std::thread mThreadObj;
std::vector<T> m_queue;
};
template <class T>
ThreadWithQueue<T>::ThreadWithQueue(sf::RenderWindow* window, std::atomic<bool>& isRunning)
: m_window{ window }, isRunning{ isRunning } {} | {
"domain": "codereview.stackexchange",
"id": 45290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, sfml",
"url": null
} |
c++, c++20, sfml
template <class T>
void ThreadWithQueue<T>::startThread() {
mThreadObj = std::thread{ &ThreadWithQueue::queueThread,this };
}
template <class T>
void ThreadWithQueue<T>::joinThread() {
if (mThreadObj.joinable()) {
mThreadObj.join();
}
}
template <class T>
void ThreadWithQueue<T>::queueSubmit(T object) {
m_queue.push_back(object);
}
updater.h:
#pragma once
#include "threadWithQueue.h"
#include "IEntity.h"
class Updater : public ThreadWithQueue<IEntity*> {
public:
Updater(sf::RenderWindow* window, std::atomic<bool>& isRunning, sf::Clock& global_clock);
~Updater() = default;
private:
virtual void queueThread();
sf::Clock& m_global_clock;
};
updater.cpp
#include "updater.h"
Updater::Updater(sf::RenderWindow* window, std::atomic<bool>& isRunning, sf::Clock& global_clock)
: ThreadWithQueue<IEntity*>(window, isRunning), m_global_clock(global_clock) {}
void Updater::queueThread() {
while (isRunning.load()) {
for (auto& i : m_queue) {
i->update(m_global_clock.restart());
}
}
}
renderer.h:
#include "updater.h"
Updater::Updater(sf::RenderWindow* window, std::atomic<bool>& isRunning, sf::Clock& global_clock)
: ThreadWithQueue<IEntity*>(window, isRunning), m_global_clock(global_clock) {}
void Updater::queueThread() {
while (isRunning.load()) {
for (auto& i : m_queue) {
i->update(m_global_clock.restart());
}
}
}
renderer.cpp:
#include <SFML/Graphics.hpp>
#include <atomic>
#include <thread>
#include <vector>
#include <iostream>
#include "renderer.h"
#include "imgui/imgui.h"
#include "imgui/imgui-SFML.h"
Renderer::Renderer(sf::RenderWindow* window, std::atomic<bool>& isRunning)
: ThreadWithQueue(window,isRunning) {}
void Renderer::queueThread() {
m_window->setActive(true);
while (isRunning.load()) {
m_window->clear();
for (auto& i: m_queue) {
m_window->draw(*i); | {
"domain": "codereview.stackexchange",
"id": 45290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, sfml",
"url": null
} |
c++, c++20, sfml
}
for (auto& i : m_queue_gui) {
m_window->draw(*i);
i->processGui();
}
m_window->display();
}
}
void Renderer::queueSubmit(IEntityWithGui* object)
{
m_queue_gui.push_back(object);
}
Answer: Since you are using C++20, consider using std::jthread instead of std::thread; it will remove the code for threadWithQueue. std::jthread automatically joins as part of its destruction. You can also get rid of the atomic variable(isRunning), using jthread::request_stop method.
Your m_queue is totally decoupled from the threading logic, so you may even totally drop the threadWithQueue and provide m_queue as a parameter to your thread functions.
Another important issue is using m_window in 3 different threads without proper synchronization. Adding mutexes can degrade your GUI performance and not synchronizing the threads just results in UB and surprising outputs. You need a lock-free mechanism in the rendering(soft realtime) thread to ensure smooth graphical experience. On the other hand, your event loop must actually initiate update actions in the updater thread. So you need another synchronization system(preferably lock-free) between event loop and updater thread. In short that means at least two atomic flags or other synchronization objects. I don't delve into detail now, because of the number of design decisions involved in determining them. | {
"domain": "codereview.stackexchange",
"id": 45290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20, sfml",
"url": null
} |
bash
Title: Script to automate testing solutions
Question: Here's a script I wrote to automate testing for multiple sample files across two solutions, aiming to streamline the process. The script, provided below, compares expected results with the output of the solutions.
#!/usr/bin/bash
test_results() {
expected=("${@}")
i=0
for file in *.txt
do
result=`./a.out $file`
if [ ${expected[$i]} != $result ]; then
echo "Test case $i: FAILED."
else
echo "Test case $i: PASSED."
fi
i=$((i + 1))
done
}
cc sol.c
expected_part1=("142" "209" "54605" "142")
echo "Testing part 1."
test_results "${expected_part1[@]}"
cc sol2.c
expected_part2=("142" "281" "55429" "142")
echo -e "\nTesting part 2."
test_results "${expected_part2[@]}"
How can it be written better, and more generically?
Answer: two names for two programs
result=`./a.out $file`
While this does hold a certain traditional charm to it,
this is probably not the best name for that program.
Prefer sol or sol2, in the interest of clarity.
Pass it in as a parameter:
test_results() {
cmd="$1"; shift
expected=("${@}")
...
result=`"${cmd}" "${file}"`
shellcheck
When authoring in any language, take advantage of the free advice
offered by a relevant linter, e.g. $ cc -Wall -pedantic *.c ....
In bash, run $ shellcheck my_script.sh, and heed its advice.
Perhaps the most common warning will be to "${quote}"
variable interpolations, in case the variable contains
embedded whitespace. I know, I know, it's annoying,
and you might believe that in this situation it will
never make a difference.
Follow the advice anyway, for several reasons: | {
"domain": "codereview.stackexchange",
"id": 45291,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash",
"url": null
} |
bash
Quoting issues really are a common source of latent bugs that bite folks.
It's good to get in the habit of writing code carefully the first time, so the linter never triggers.
As with all linters, it's worthwhile to make it run clean so the next (possibly serious) issue it reports will be noticed and addressed prior to a production run.
backtick
In modern usage we prefer
$(./a.out "${file}")
over
`./a.out "${file}"`
For one thing, after deep nesting it's easier to pair up
the matching punctuation.
Shellcheck will offer this advice.
Recommend you take it.
(Kudos, nice arithmetic when incrementing i BTW.)
TAP
expected_part1=("142" "209" "54605" "142")
...
test_results "${expected_part1[@]}"
Hmmm. That array notation, together with iterating within the function,
is a slightly complex approach to a simple problem.
Consider adopting the
Test Anything Protocol.
It is much like what you are doing,
very simple text output to stdout.
But it has the advantage of being well documented
and having libraries for interacting with it.
It tends to be less chatty in the boring "success" case.
Consider putting the "expected" figures into a text file,
and then ./a.out ${file} | diff -u expected.txt -
suffices. Whether or not the files exactly matched
can be read from the $? status variable.
Consider using a structured format for your numeric output,
such as .CSV or perhaps JSON (which jq can help with).
make
cc sol.c
...
cc sol2.c
Ok, we're back to the "two names" topic.
Recommend you create a short Makefile,
so these two become make sol and make sol2.
You could even go further,
writing a dependency rule so sol2_output.txt
depends on the sol2.c source code,
and will be regenerated whenever the source is edited.
And then sol2_diffs.txt could be generated
as the (hopefully zero byte!) differences
between expected and actual output.
printf
echo -e "\nTesting part 2." | {
"domain": "codereview.stackexchange",
"id": 45291,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash",
"url": null
} |
bash
printf
echo -e "\nTesting part 2."
Yeah, sometimes portable shell code is just painful,
as we see here. The -e switch has a long and sordid history.
In some environments it's not recognized and we will
literally see DASH e SPACE at the beginning of output.
The usual way to avoid such nonsense is to just give
up on echo and use /usr/bin/printf, which always
works as expected: printf "\nTesting part 2.\n"
This codebase achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45291,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash",
"url": null
} |
beginner, bash
Title: Start script for several Spring Boot services
Question: I have several Spring Boot and Angular applications/microservices that form together a whole application. As it is tedious to start them via the terminal, I've written the following script to perform the starting of all.
I've simplified the script a bit to remove some redundant parts. Note that I usally start this script from ~/Documents/git/ and the script itself is located in ~/Documents/git/start-services. That means, I usually do: $ ./start-services/services.sh start to start all services.
The standard out and standard error streams of the started services are redirected to files located in ~/Documents/git/start-services/logs/. For each service a separate log file.
#!/bin/bash
start_service_and_wait() {
is_running=$(nc -v -z localhost $3 2>&1 >/dev/null)
bold="\033[1m"
reset="\033[0m"
if [[ $is_running =~ "succeeded" ]]; then
echo -e "There is already a service running on port $3. Won't try to start service $bold\"$2\"$reset."
return
fi
waiting_time=60
cd $1
git_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"
echo -e "Start service $bold\"$2\"$reset on branch $bold$git_branch$reset..."
START_TIME=$SECONDS
nohup $4 > ../start-services/logs/$1.log 2>&1 &
cd ..
# TODO Maybe try to use the actuator port to check whether the service is available?
./start-services/wait-for-it.sh localhost:$3 -q -t $waiting_time
result=$?
ELAPSED_TIME=$(($SECONDS - $START_TIME))
if [[ $result != 0 ]]; then
echo -e " \U26A0\UFE0F Service $bold\"$2\"$reset has been started but did not become available at port $3 after $waiting_time s. Result is $result. Showing the last lines of the captured log file:"
tail ./start-services/logs/$1.log
else
echo -e " \U2705 Service $bold\"$2\"$reset is available at port $3 after $ELAPSED_TIME s. With result $result."
fi
} | {
"domain": "codereview.stackexchange",
"id": 45292,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
start_services() {
if [ -z $1 ] || [ $1 = "config-server" ]; then
start_service_and_wait "config-server" "Config Server" "8888" "mvn spring-boot:run"
fi
if [ -z $1 ] || [ $1 = "profile" ]; then
start_service_and_wait "profile" "Profile" "8082" "mvn spring-boot:run"
fi
if [ -z $1 ] || [ $1 = "security" ]; then
start_service_and_wait "security" "Security" "8080" "mvn spring-boot:run"
fi
if [ -z $1 ] || [ $1 = "analysis" ]; then
start_service_and_wait "analysis" "Analysis" "8092" "mvn spring-boot:run"
fi
if [ -z $1 ] || [ $1 = "frontend" ]; then
start_service_and_wait "frontend" "Frontend" "4200" "yarn start"
fi
}
stop_service() {
# check whether there is a *.pid file before trying to stop
pid=$(lsof -t -i:$3)
bold="\033[1m"
reset="\033[0m"
if [[ -n "${pid// /}" ]]; then
echo -e "Stopping service $bold\"$2\"$reset."
kill $pid
fi
}
stop_services() {
if [ -z $1 ] || [ $1 = "config-server" ]; then
stop_service "config-server" "Config Server" "8888"
fi
if [ -z $1 ] || [ $1 = "profile" ]; then
stop_service "profile" "Profile" "8082"
fi
if [ -z $1 ] || [ $1 = "security" ]; then
stop_service "security" "Security" "8080"
fi
if [ -z $1 ] || [ $1 = "analysis" ]; then
stop_service "analysis" "Analysis" "8092"
fi
if [ -z $1 ] || [ $1 = "frontend" ]; then
stop_service "frontend" "Frontend" "4200"
fi
}
status_service() {
if [ ! -d "$2" ]; then
return;
fi
RED="31"
REDBOLD="\e[1;${RED}m"
ENDCOLOR="\e[0m"
bold="\033[1m"
reset="\033[0m"
result=$(nc -v -z localhost $3 2>&1 >/dev/null)
if [[ $result =~ "Connection refused" ]]; then
echo -e " \U274C Service $bold\"$1\"$reset is ${REDBOLD}not availble${ENDCOLOR} on port $3."
else
echo -e " \U2705 Service $bold\"$1\"$reset is available on port $3."
fi
} | {
"domain": "codereview.stackexchange",
"id": 45292,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
status() {
echo "The following information is determined by net-catting on localhost and the corresponding host. Note that just because the port is used doesn't mean that the Service is running."
status_service "Config Server" "config-server" "8888"
status_service "Profile" "profile" "8082"
status_service "Security" "security" "8080"
status_service "Frontend" "frontend" "4200"
}
usage() {
echo "Commands:"
echo " services.sh start Starts all services"
echo " services.sh start <name> Starts only the service with the given name"
echo " services.sh stop Stops all services"
echo " services.sh status Shows the status of the services whether started or not"
echo ""
echo "Services that will be started and there key:"
echo " Config Server -> config-server"
echo " Profile -> profile"
echo " Security -> security"
echo " Analysis -> analysis"
echo " Frontend -> frontend"
}
case "$1" in
start)
start_service $2
;;
stop)
stop_service $2
;;
status)
status
;;
--help)
usage
;;
'')
status
;;
esac
Questions:
Is it good to assume a certain folder from which the script is started?
How to handle the formatting of the output better?
Is it better to migrate to printf to remove usage of echo?
Can we store the information about the services (i.e. name, directory, port) in some kind of global array? | {
"domain": "codereview.stackexchange",
"id": 45292,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
Answer: Give descriptive names to variables
start_service_and_wait is a bit hard to read because to understand what are $1, $2, and so on, I have to read the callers.
It would be better to create local variables with descriptive names at the start of the function.
The same goes for the other functions, and also at the top level in the program.
Add more error handling to make the program more robust
Most notably error checking of the cd $1 is strongly recommended, as failures of the cd command can be destructive. I recommend adding the following safeguard at the top of every Bash script:
set -euo pipefail
The effect of this will be, to put it simply, when the program encounters a failed command or undefined variable, it will immediately abort.
Avoid cd "$var"; ...; cd .. in scripts
This is fragile, and the cd .. might not land in the original directory.
One safer way is to use pushd "$var"; ...; popd instead.
Another safer way is to use a subshell: (cd "$var"; ...).
And sometimes you can write the program differently and avoid changing the directory. Instead of this:
cd $1
git_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null)"
echo -e "Start service $bold\"$2\"$reset on branch $bold$git_branch$reset..."
START_TIME=$SECONDS
nohup $4 > ../start-services/logs/$1.log 2>&1 &
cd ..
This is equivalent, without ever changing the directory:
git_branch="$(cd $1; git rev-parse --abbrev-ref HEAD 2>/dev/null)"
echo -e "Start service $bold\"$2\"$reset on branch $bold$git_branch$reset..."
START_TIME=$SECONDS
nohup $4 > start-services/logs/$1.log 2>&1 & | {
"domain": "codereview.stackexchange",
"id": 45292,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
beginner, bash
Enclose variables in double-quotes
For example write cd "$1" instead of cd $1.
Unquoted expressions are subject to globbing and word splitting by the shell,
and can lead to difficult to debug failures.
Avoid ALL_CAPS variable names
ALL_CAPS names may clash with system environment variables, therefore they are not recommended for user-defined variables.
Use arrays
Many values are used in many functions, and if something has to change, it will have to be changed in multiple places, for example the service port numbers. I think associative arrays could be practical to define these values in one place, and also reduce some duplicated logic.
Consider for example this pattern:
declare -A service_names
service_names=(
[config-server]="Config Server"
[profile]="Profile"
# ... and so on
)
declare -A ports
ports=(
[config-server]=8888
[profile]=8082
# ... and so on
)
stop_services() {
for key in "${!service_names[@]}"; do
if [ -z "$1" ] || [ "$1" = "$key" ]; then
stop_service "$key" "${service_names[$key]}" "${ports[$key]}"
fi
done
} | {
"domain": "codereview.stackexchange",
"id": 45292,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, bash",
"url": null
} |
python, cryptography, aes, websocket
Title: Encrypted websocket chat using AES (EAX) and RSA for signing
Question: For learning purposes and because it really interests me I am trying to get a better understanding of cryptography by trying to make my own basic secure chat-application. I posted a first version of my attempt here. There were a few flaws in my implementation:
My implementation was not E2EE because my server acted as a proxy to generate the derived key.
The server had to much knowledge about keys (generating derived key for AES, containing public RSA key,...).
I used AES mode ECB (which is less safe).
The clients had no verification to trust each other.
In this follow-up question I made a new (hopefully) improved version. I will explain the context again: Alice, Bob and Charlie want a safe way to communicate with each other. So they made a Python script server.py which only function is to echo the incoming messages back to all connected clients, besides also generating a salt unique for each session. They put this server-script on a simple VPS.
They also made a script chat.py. It can be called like this python3 chat.py --user=alice --password=abc123.
The idea is Alice, Bob and Charlie agree on a password to use for their chat session. They can only read each other's messages if they all use the same password.
In this improved version all sent messages are also verified using a RSA signature. To achieve this they generated RSA Keypairs:
Alice manually generates a RSA-keypair. Saves her private key next to chat.py and shares the public key with Bob and Charlie.
Bob manually generates a RSA-keypair. Saves his private key next to chat.py and shares the public key with Alice and Charlie.
Charlie manually generates a RSA-keypair. Saves his private key next to chat.py and shares the public key with Alice and Bob. | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
python, cryptography, aes, websocket
This results in each of them having e.g a flash drive with the following structure. For Alice:
├── alice.pem #private key
├── chat.py
├── public_keys
├── alice.pem
├── bob.pem
└── charlie.pem
This is how the implementation works.
A user initiates a chat executing python3 chat.py --user=alice --password=pass123.
The server generates a unique salt for each session This salt will be used later in Argon2 and PBKDF2_HMAC.
The client retrieves this salt.
The client generates a Argon2-hash with the password pass123 and the retrieved salt.
This hash is because of it's length not usable as AES-key. So we use PBKDF2_HMAC as KDF with the Argon2-hash and the previously retrieved salt.
When a user sends a message we generate a AES-cipher and encrypt the text of the message. Because we use MODE_EAX this message also gets a tag and the cipher gets a nonce.
The message gets also signed using the private key of the user using pkcs1_15. We pass the encrypted version of the message as parameter to get signed and NOT the plain-text version.
Now we send the encrypted message, RSA signature, AES nonce, and AES tag to the server.
The only thing the server does is echoing the request to all connected clients.
When a client receives a message the first thing it does is verifying the RSA-signature. It does this by checking if there is a public_key who can verify the signature.
If that's the case a AES-cipher is generated using the nonce which came with the request.
The message gets decrypted and we check if the tag of the message can be verified.
If that's the case, we print the message to chat.
server.py
import asyncio
import websockets
import binascii
import secrets
import json
# Clients connected to chat server.
clients = set()
# Generate salt unique to this session.
salt = secrets.token_hex(16) | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
python, cryptography, aes, websocket
# Generate salt unique to this session.
salt = secrets.token_hex(16)
# Function to handle connection (Only one connection and one client in this simplified code).
async def handle_connection(websocket, url):
# Add client.
clients.add(websocket)
async for request in websocket:
print(request)
jsonRequest = json_decode_request(request)
if "action" in jsonRequest:
# There are a few special request 'actions' the app
# of the client automatically does. E.g to retrieve
# the used salt.
match jsonRequest["action"]:
case "retrieve-salt":
await websocket.send(salt.encode('utf-8'))
case other:
pass
else:
# Receiving messages as example
# The only thing the server does is echoing the incoming
# request back to all clients. It has no idea of any keys.
await asyncio.gather(*[client.send(request) for client in clients])
await websocket.send(request)
# (ignore) Decode potentially hexified values from
# the request into JSON.
def json_decode_request(request):
jsonReq = json.loads(request)
for key, value in jsonReq.items():
try:
jsonReq[key] = binascii.unhexlify(value)
except:
continue
return jsonReq
start = websockets.serve(handle_connection, "localhost", 1234)
asyncio.get_event_loop().run_until_complete(start)
asyncio.get_event_loop().run_forever()
chat.py
import os
import asyncio
import websockets
import hashlib
import json
import argparse
import binascii
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from argon2 import PasswordHasher | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
python, cryptography, aes, websocket
# Run this example with different users as explained in question.
parser = argparse.ArgumentParser()
parser.add_argument('--user', '-user', help = "Choose a user.", type = str)
parser.add_argument('--password', '-password', help = "Choose a password.", type = str)
args=parser.parse_args()
# Load RSA private key.
def import_key_from_file(path):
with open(path, "r") as keyFile:
key = keyFile.read()
return RSA.import_key(key)
# Note!
# In this example all private keys of the users are present in the folder.
# In real each user would only have their own private key.
privateKey = import_key_from_file(args.user + ".pem")
# Client enters a password.
password = args.password.encode('utf-8')
async def connect():
url = "ws://localhost:1234"
async with websockets.connect(url) as websocket:
# Receive salt from server
salt = await retrieve_salt(websocket)
# Generate secure hash of password using Argom2
hasher = PasswordHasher(
hash_len=100,
salt_len=len(salt)
)
hash = hasher.hash(password, salt = salt).encode('utf-8')
# Generate derived key using PBKDF2_HMAC
derivedKey = hashlib.pbkdf2_hmac('sha256', hash, salt, 60000)
# --- Sending message ---
sendingMsg = f"Hello. I am {args.user}.".encode('utf-8')
await send_message(websocket, derivedKey, sendingMsg)
# -- Receiving message ---
await receive_message(websocket, derivedKey)
async def send_message(websocket, derivedKey, text):
# AES.new() must be called for each message. Because:
# A cipher object is stateful: once you have decrypted a message
# you cannot decrypt (or encrypt) another message with the same
# object.
aesCipher = AES.new(derivedKey, AES.MODE_EAX)
# Encrypt message.
sendingMsgEncrypted, sendingTag = aesCipher.encrypt_and_digest(pad(text, AES.block_size, style='pkcs7')) | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
python, cryptography, aes, websocket
# Sign encrypted message using private key (RSA).
sendingMsgSignature = sign_message(sendingMsgEncrypted)
# Send.
await websocket.send(message_to_json(sendingMsgEncrypted, sendingMsgSignature, aesCipher.nonce, sendingTag))
async def receive_message(websocket, derivedKey):
while True:
incomingMsg = json_decode_request(await websocket.recv())
# Verify message using public RSA key.
verification = verify_message(incomingMsg["message"], incomingMsg["signature"])
if not verification:
print("This message could not be verified!")
return
# AES.new() must be called for each message. Because:
# A cipher object is stateful: once you have decrypted a message
# you cannot decrypt (or encrypt) another message with the same
# object.
aesCipher = AES.new(derivedKey, AES.MODE_EAX, nonce = incomingMsg["aes-nonce"])
# Decrypt.
decryptedMessage = unpad(aesCipher.decrypt(incomingMsg["message"]), AES.block_size, style='pkcs7').decode('utf-8')
# Verify AES tag.
try:
aesCipher.verify(incomingMsg["aes-tag"])
# Print to chat.
print(decryptedMessage)
except:
print("This message could not be verified.")
return
# Retrieve salt from server.
async def retrieve_salt(websocket):
await websocket.send(json.dumps({"action": "retrieve-salt"}))
return await websocket.recv()
# Sign a message using RSA private key.
def sign_message(message):
messageHash = SHA256.new(message)
return pkcs1_15.new(privateKey).sign(messageHash) | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
python, cryptography, aes, websocket
# Verify message signature using RSA public key.
def verify_message(message, signature):
messageHash = SHA256.new(message)
# A incoming message can come from Alice, Bob or Charlie.
# We have all these persons public keys and loop over them
# to check if a message is signed by one of them.
for filename in os.listdir("public_keys"):
path = "public_keys/" + filename
publicKey = import_key_from_file(path)
try:
pkcs1_15.new(publicKey).verify(messageHash, signature)
except:
continue
return True
return False
# (ignore) Helper function required because:
# TypeError: Object of type bytes is not JSON serializable.
def message_to_json(message, signature, aes_nonce, aes_tag):
return json.dumps({
"message": binascii.hexlify(message).decode('utf-8'),
"signature": binascii.hexlify(signature).decode('utf-8'),
"aes-nonce": binascii.hexlify(aes_nonce).decode('utf-8'),
"aes-tag": binascii.hexlify(aes_tag).decode('utf-8')
})
# (ignore)
def json_decode_request(request):
jsonReq = json.loads(request)
return {
"message": binascii.unhexlify(jsonReq["message"]),
"signature": binascii.unhexlify(jsonReq["signature"]),
"aes-nonce": binascii.unhexlify(jsonReq["aes-nonce"]),
"aes-tag": binascii.unhexlify(jsonReq["aes-tag"])
}
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(connect())
Notes:
So it is not intended to be a chat-app for a large user-base. Only for a very limited amount of people who agreed to use this app.
In real, all connections will go over SSL.
Questions:
Is this implementation better then my previous attempt?
Is this a relatively good implementation?
Is this considered E2EE? Because only the clients know the AES-key?
Other comments? | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
python, cryptography, aes, websocket
Answer: The protocol is already much better than the previous version where the server knew about all the keys. However, there are some weird things happening:
both a private key and a password is used; this is not necessarily bad, but in general you need only the key pair
the symmetric key is derived from the password using two PBKDF's (Argon & PBKDF2)
the key derivation seems to be performed for each message
although the salt is indicated to be "unique per connection" this isn't actually implemented, the salt seems to be the same
it isn't clear how the salt would be handled if multiple clients are sending messages to the server
the password seems to be unique per connection rather than per user
there doesn't seem to be any protection against replay attacks
the signature seems to be calculated for each message while signature generation is relatively expensive
the messages are now protected using the authentication part of EAX mode and a signature, which is too much
we'll have to assume that the public keys are distributed securely
worse, we have to assume that the password (secrets) are distributed securely
state handling is enough for a single connection between two clients, but the protocol probably needs extension to be able to handle more message better
although sending all messages to all people helps against guessing who is talking to who (as long as the TLS connection is created first) it would be relatively expensive
the protocol cannot be extended as there is no version number or similar within the messages
EAX mode doesn't require padding
There are also some good things: | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
python, cryptography, aes, websocket
There are also some good things:
the use of TLS to the server makes it very hard to get any information directly from the connections
the use of JSON makes it possible to more clearly separate different elements in the request & responses
the use of reasonably secure algorithms such as AES in EAX mode and RSA in PKCS#1 mode
the use of the secrets module to create the salt
the use of a random nonce with EAX mode, included with the message
little wrong with the code itself in my opinion | {
"domain": "codereview.stackexchange",
"id": 45293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, cryptography, aes, websocket",
"url": null
} |
c++, c++17, template
Title: Given a type, search for an item of that type in a std::tuple
Question: In my project, I want to search for an item of a given type in a std::tuple at compile time. The given type might not be present in the tuple at all, in which case some invalid value should be returned to signal that. I'm using c++17 by the way.
template<typename Arg, typename... Args>
struct contains {
static constexpr bool value = std::disjunction_v<std::is_same<Arg, Args>...>;
};
template<typename... Args>
struct Stuffs {
std::tuple<Args...> data;
template<typename Arg>
std::enable_if_t<contains<Arg, Args...>::value, Arg*>
constexpr search() {
auto& ref = std::get<Arg>(data);
return &ref;
}
template<typename Arg>
std::enable_if_t<!contains<Arg, Args...>::value, Arg*>
constexpr search() {
return nullptr;
}
};
int main() {
struct A { int val = 100; };
struct B {};
struct C {};
struct D {};
struct E {};
if constexpr (Stuffs<A, B, C, D>{}.search<A>()->val == 100) {
std::cout << "A found" << std::endl;
}
if constexpr (Stuffs<A, B, C, D>{}.search<E>()) {
std::cout << "should not happen" << std::endl;
}
if constexpr (Stuffs<A, B, C, D>{}.search<int>()) {
std::cout << "should not happen" << std::endl;
}
}
This code seems to work fine in terms of searching in a tuple at compile time. Initially, I tried to use std::variant and void* but their operations are mostly prohibited in a constexpr setting. Then I arrived at this approach. I'm new to C++ template programming, so I'm wondering if there are any potential issues with this code and how I may improve it? | {
"domain": "codereview.stackexchange",
"id": 45294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template",
"url": null
} |
c++, c++17, template
Answer: This is a great idea, and is pretty well-done. Not bad for someone new to metaprogramming!
I have only two major suggestions for improving contains.
The first is to either have it inherit from std::bool_constant, or to-reimplement all the stuff in bool_constant.
That’s because bool_constant is more than just its value. There are other handy conversions baked in. This is (roughly) what bool constant looks like:
template <bool V>
struct bool_constant
{
using type = bool_constant;
using value_type = bool;
static constexpr bool value = V;
constexpr auto operator()() const noexcept { return V; }
constexpr operator auto() const noexcept { return V; }
};
You’ve got the value, but none of the other features. They are not often used, sure, but since you get them for free, you might as well do:
template <typename Arg, typename... Args>
struct contains
: std::bool_constant<std::disjunction_v<std::is_same<Arg, Args>...>>
{};
You could also do:
template <typename Arg, typename... Args>
struct contains
: std::disjunction<std::is_same<Arg, Args>...>
{};
But I don’t recommend that, because a std::disjunction can boil down to a random type that may not support the full interface. And the whole point is you want the full interface.
The second major suggestion is to change the interface slightly to make it easier to use.
What I would like to do is write:
using my_tuple = std::tuple<int, float, std::string>
if (contains<my_tuple, int>::value)
// ...
// Or:
if (contains<std::tuple<int, float, std::string>, int>::value)
// ... | {
"domain": "codereview.stackexchange",
"id": 45294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template",
"url": null
} |
c++, c++17, template
// Or:
if (contains<std::tuple<int, float, std::string>, int>::value)
// ...
But I can’t write that. In fact, I can’t use contains at all without additional boilerplate to hoist the tuple’s types out of the tuple. contains itself is like three lines, but you need more than double that (in the Stuffs class) to be able to actually use it meaningfully.
What you should do is use partial specialization to extract the types automatically, like so:
// Primary template. Leave undefined, so it only works with tuples or
// tuple-like stuff.
template <typename Haystack, typename Needle>
struct contains;
// Specialization for std::tuple:
template <typename Needle, typename... Args>
struct contains<std::tuple<Args...>, Needle>
: std::bool_constant<std::disjunction_v<std::is_same<Needle, Args>...>>
{};
// Or, better: specialization for any kind of type list or anything tuple-like:
template <template <typename...> typename Haystack, typename Needle, typename... Args>
struct contains<Haystack<Args...>, Needle>
: std::bool_constant<std::disjunction_v<std::is_same<Needle, Args>...>>
{};
Now you no longer need Stuffs to use the contains metafunction… though you could still do it if you want:
template <typename... Args>
struct Stuffs
{
std::tuple<Args...> data;
// Don't really need enable_if for this.
template <typename Arg>
constexpr auto search() -> Arg*
{
if constexpr (contains<std::tuple<Args...>, Arg>::value)
return &std::get<Arg>(data);
else
return nullptr;
}
}; | {
"domain": "codereview.stackexchange",
"id": 45294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template",
"url": null
} |
c++, c++17, template
Now, all that being said, I suggest that you may have solved the wrong problem.
If all you want is to test whether some type is in a tuple, then fine, nailed it.
However… is that all you want?
Because even in your sample code, you want more. You not only want to know whether a type is in a tuple… you want to access that type.
And since you want that, you end up doing the work twice. First you search the tuple to find the type. Then you search it again (via std::get<Arg>()) to get the type. That’s a waste of effort. You already found it… why forget about it then search for it again?
You may argue that the efficiency waste doesn’t matter, because all this is happening at compile time, and that is true. However, there is another problem. Try this code:
auto main() -> int
{
if (Stuffs<int, int>{}.search<int>() != nullptr)
std::cout << "found!\n";
else
std::cout << "not found\n";
}
The problem isn’t your code, it’s std::get<T>(). That fails if you use a type that exists more than once in the tuple. You know there’s in an int in there… but you can’t access it.
So I would suggest that the problem that you really want to solve is not whether Arg is in tuple<Args...>, but where Arg is in tuple<Args...>.
So instead of just a contains function which returns a bool, what you actually want is a find function that returns an index.
Suppose you did have this find metafunction:
template <typename Haystack, typename Needle>
struct find;
// Returns the index of the first occurence of Needle, or size_t{-1}.
template <template <typename...> typename Haystack, typename Needle, typename... Args>
struct find<Haystack<Args...>, Needle>
: std::integral_constant<std::size_t, /* magic! */>
{};
Now your Stuffs operation becomes:
template <typename... Args>
struct Stuffs
{
std::tuple<Args...> data; | {
"domain": "codereview.stackexchange",
"id": 45294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template",
"url": null
} |
c++, c++17, template
// Don't really need enable_if for this.
template <typename Arg>
constexpr auto search() -> Arg*
{
constexpr auto index = find<tuple<Args...>, Arg>::value;
if constexpr (index != std::size_t{-1})
return &std::get<index>(data);
else
return nullptr;
}
};
And this will always work, even for tuples with duplicate types. And you’re only searching the tuple once.
In fact, the find operation is fundamental, so you can even write contains in terms of it:
template <typename Haystack, typename Needle>
struct contains
: std::bool_constant<find<Haystack, Needle>::value != std::size_t{-1}>
{};
In fact, you could go even further, and have a metafunction find_all that returns a std::index_sequence with the indices of every occurrence of a needle. So:
find_all<tuple<int, float, char, int, int, double, int>, int>
// value_type is index_sequence<0, 3, 4, 6>
find_all<tuple<int, float, char, int, int, double, int>, double>
// value_type is index_sequence<5>
find_all<tuple<int, float, char, int, int, double, int>, short>
// value_type is index_sequence<>
And then make find in terms of that (whenever the length of the index sequence is non-zero, take the first index). And contains would still be in terms of find. Plus you could also write another metafunction count that counts the number of times a type is in a tuple… that could be in terms of find_all too. Plus you could easily write a find_last. And a unique. And so on.
Have fun! | {
"domain": "codereview.stackexchange",
"id": 45294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, template",
"url": null
} |
python, programming-challenge
Title: Advent of Code 2023 - Day 2: Cube Conundrum
Question: Part 1:
The challenge involves analyzing recorded games where an Elf reveals subsets of cubes in a bag, each identified by a game ID. The goal is to determine which games would be possible if the bag contained specific quantities of red, green, and blue cubes.
For example, the record of a few games might look like this:
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
In game 1, three sets of cubes are revealed from the bag (and then put back again). The first set is 3 blue cubes and 4 red cubes; the second set is 1 red cube, 2 green cubes, and 6 blue cubes; the third set is only 2 green cubes.
The Elf would first like to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes?
In the example above, games 1, 2, and 5 would have been possible if the bag had been loaded with that configuration. The solution involves summing up the IDs of these possible games. In the provided example, the answer was 8, corresponding to games 1, 2, and 5.
#!/usr/bin/env python3
import sys
from typing import Iterable
MAX_RED = 12
MAX_GREEN = 13
MAX_BLUE = 14
GID_SEP = ": "
DRAW_SEP = "; "
PICK_SEP = ", "
def parse_cubes(cubes: str) -> dict:
counts = {"green": 0, "red": 0, "blue": 0}
for cube in cubes:
count, name = cube.split()
counts[name] += int(count)
return counts
def is_eligible_game(counts: dict) -> bool:
return (
counts["red"] <= MAX_RED
and counts["blue"] <= MAX_BLUE
and counts["green"] <= MAX_GREEN
) | {
"domain": "codereview.stackexchange",
"id": 45295,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
def play_game(line: str) -> int:
# Game N: 3 X, 4 Y; .... ; ..
round_num, round_sets = map(str.strip, line.split(GID_SEP))
round_num = round_num.split()[-1]
round_sets = round_sets.split(DRAW_SEP)
if all(
is_eligible_game(parse_cubes(turns.split(PICK_SEP))) for turns in round_sets
):
return int(round_num)
return 0
def total_eligible_games(lines: Iterable[str]) -> int:
return sum(map(play_game, lines))
def main():
if len(sys.argv) != 2:
sys.exit("Error - No file provided.")
with open(sys.argv[1], "r") as f:
total = total_eligible_games(f)
print(f"Total: {total}")
if __name__ == "__main__":
main()
Part 2:
In Part Two, the Elf poses a second question: finding the fewest number of cubes for each color to make a game possible. The power of a set of cubes is calculated by multiplying the numbers of red, green, and blue cubes together.
Again consider the example games from earlier:
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
The power of a set of cubes is equal to the numbers of red, green, and blue cubes multiplied together. The power of the minimum set of cubes in game 1 is 48. In games 2-5 it was 12, 1560, 630, and 36, respectively. The solution involves summing up the power of the minimum set of cubes of these possible games. In the provided example, the answer was 2286.
#!/usr/bin/env python3
import sys
from typing import Iterable
GID_SEP = ": "
DRAW_SEP = "; "
PICK_SEP = ", "
def parse_cubes(cubes: str) -> dict:
counts = {"green": 0, "red": 0, "blue": 0}
for cube in cubes:
count, name = cube.split()
counts[name] += int(count)
return counts | {
"domain": "codereview.stackexchange",
"id": 45295,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
def play_game(line: str) -> int:
# Game N: 3 X, 4 Y; .... ; ..
round_num, round_sets = map(str.strip, line.split(GID_SEP))
round_num = round_num.split()[-1]
round_sets = round_sets.split(DRAW_SEP)
max_counts = {"green": 0, "red": 0, "blue": 0}
for round_set in round_sets:
cur_counts = parse_cubes(round_set.split(PICK_SEP))
for color in ["green", "red", "blue"]:
max_counts[color] = max(max_counts[color], cur_counts[color])
return max_counts["green"] * max_counts["red"] * max_counts["blue"]
def total_powers(lines: Iterable[str]) -> int:
return sum(map(play_game, lines))
def main():
if len(sys.argv) != 2:
sys.exit("Error - No file provided.")
with open(sys.argv[1], "r") as f:
total = total_powers(f)
print(f"Total: {total}")
if __name__ == "__main__":
main()
Review Goals:
General coding comments, style, etc.
What are some possible simplifications? What would you do differently?
Answer: three variables for one concept
MAX_RED = 12
MAX_GREEN = 13
MAX_BLUE = 14
My first impression is that this will likely turn out to be inconvenient,
with three if statements.
Consider throwing these magic numbers into a single dict:
MAX_CUBES = {
'red': 12,
'green': 13,
'blue': 14,
}
Oh, now I see in is_eligible_game
that it didn't turn out so bad at all, nevermind.
The conjuncts could have been an all() expression,
but the OP code is perfectly clear as-is.
Down in the part-2 play_game we might prefer
product *= max_counts[color],
but three is such a small number that it makes little difference.
cracking argv
Kudos, nice __main__ guard, and nice CLI error checking.
And mapping play_game across the input lines is lovely.
Consider making things easier on yourself with
typer:
from pathlib import Path
import typer
def main(games_input_file: Path) -> None:
with open(games_input_file, "r") as f:
total = ...
if __name__ == "__main__":
typer.run(main) | {
"domain": "codereview.stackexchange",
"id": 45295,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
if __name__ == "__main__":
typer.run(main)
You get --help "for free"!
line parsing
def play_game(line: str) -> int:
# Game N: 3 X, 4 Y; .... ; ..
Thank you kindly for that comment. It is quite helpful.
In general the tuple unpack, the mapping,
the consistent split() on some delimiter,
all work smoothly.
round_num = round_num.split()[-1]
That seemed slightly off for two reasons.
Maybe [1] would have been more natural than
asking for last element, given that this is always a pair?
Maybe a re.compile(r'^Game (\d+)') would have been slightly clearer?
IDK, it's all six vs. half-dozen.
But then it would be preferable to immediately store an int( ... ) expression
into something that you're claiming is a round number,
rather than deferring that until the return.
Maybe spell out that GID_SEP is GAME_ID_SEP?
Again, these are all tiny nits.
summary
Two things impressed me as I was reading this code:
small helper functions that do a single thing
very clear and helpful identifier names
Good job. Keep it up!
This code achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45295,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
Title: Advent of Code 2023 Day 3, Part 2 in Python
Question: Part 2
I'm not sure if my solution covers all edge cases. The puzzle goes as follows: Given some input like this:
467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..
We're looking for * symbols ("gears") that are adjacent to precisely two integers, and compute the sum of the product of adjacent integers. In the above example this would be 467 * 35 + 755 * 598 = 16345 + 451490 = 467835.
import re
PATTERN = r"\d+"
def go_forwards(line, start=0):
part_number = ""
for c in line[start:]:
if c.isdigit():
part_number = part_number + c
else:
break
return part_number
def go_backwards(line, end=0):
part_number = ""
for c in reversed(line[:end]):
if c.isdigit():
part_number = part_number + c
else:
break
return part_number[::-1]
with open("input.txt") as f:
lines = f.readlines()
sum = 0
for line_index, curr_line in enumerate(lines):
curr_line = "".join(curr_line.strip())
if line_index == 0:
prev_line = curr_line
if line_index >= len(lines) - 1:
next_line = curr_line
else:
next_line = lines[line_index + 1]
for pos, c in enumerate(curr_line):
if c == "*":
adjacents = 0
# check number of adjacents before doing anything
if curr_line[pos - 1].isdigit():
adjacents += 1
if curr_line[pos + 1].isdigit():
adjacents += 1
adjacents += len(re.findall(PATTERN, prev_line[pos - 1:pos + 2]))
adjacents += len(re.findall(PATTERN, next_line[pos - 1:pos + 2]))
if adjacents != 2:
continue
part_numbers = list() | {
"domain": "codereview.stackexchange",
"id": 45296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
part_numbers = list()
# part numbers next to *
if curr_line[pos - 1].isdigit():
part_numbers.append(go_backwards(curr_line, end=pos))
if curr_line[pos + 1].isdigit():
part_numbers.append(go_forwards(curr_line, start=pos + 1))
# part number in prev line at * position
if prev_line[pos].isdigit():
part_numbers.append(
go_backwards(prev_line, end=pos + 1)
+ go_forwards(prev_line, start=pos + 1)
)
# part number in prev line at position -1 or +1 of *
else:
if prev_line[pos - 1].isdigit():
part_numbers.append(go_backwards(prev_line, end=pos))
if prev_line[pos + 1].isdigit():
part_numbers.append(go_forwards(prev_line, start=pos + 1))
# part number in next line at * position
if next_line[pos].isdigit():
part_numbers.append(
go_backwards(next_line, end=pos + 1)
+ go_forwards(next_line, start=pos + 1)
)
# part number in next line at position -1 or +1 of *
else:
if next_line[pos - 1].isdigit():
part_numbers.append(go_backwards(next_line, end=pos))
if next_line[pos + 1].isdigit():
part_numbers.append(go_forwards(next_line, start=pos + 1))
sum += int(part_numbers[0]) * int(part_numbers[1])
prev_line = curr_line
print(sum) | {
"domain": "codereview.stackexchange",
"id": 45296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
prev_line = curr_line
print(sum)
Review request
The idea was to run through each character in an input line and search for the symbol *. If it is found, the number of adjacent digits is checked. If there are not exactly two, the program simply moves on to the next character. Otherwise, the program scrolls either forwards or backwards depending on the position of the digit found. If a digit is found exactly at the position of the * symbol in the previous or next line, the program moves both forwards and backwards. The corresponding functions go_backwards and go_forwards return a character string with the adjacent digits.
This code works for both the example input and my real input. However, I'm not sure if my code covers all edge cases.
Do you see any weaknesses here that you would replace?
Does your input contain edge cases that break my code?
What would you do differently?
Answer: representation
What would you do differently? | {
"domain": "codereview.stackexchange",
"id": 45296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
Answer: representation
What would you do differently?
You used many immutable strings to represent the schematic diagram.
Given that this spatially-oriented problem is asking us to examine
Moore neighborhoods,
I feel an array of (x, y) grid locations would be the most
natural representation.
And, to facilitate bookkeeping, I would find it convenient to
have a mutable array
(or ndarray)
so we can mark part numbers as "done" on the diagram.
This emulates a human pen-and-paper approach to solving this puzzle,
where we scan for gears and use a pen to cross out adjacent part numbers
we have found.
Consider part 123 surrounded by three vertically stacked gears
as both left- and right- bookends, plus one or two gears above and below.
Any of those gears could also touch 456.
Upon finding the first winning gear, I would want to scan left to locate 1.
Then erase each digit as we scan rightward toward 3, for no "double counting".
In the course of constructing our array it would be convenient to tack on
{top, bottom, left, right} blank borders which definitely don't have gears.
Then the Moore neighborhood check needn't worry about going out of bounds.
forward scan
def go_forwards(line, start=0):
...
return part_number
This is beautifully clear, thank you.
I am skeptical that defaulting to zero is helpful.
It seems to invite caller to accidentally misuse this helper --
we probably always want to specify an x-coordinate.
A type annotation which explains we return str
(rather than e.g. an int part number) would be helpful,
though we are saved by the brevity and simplicity of the function.
Similarly, a """docstring""" isn't necessary but it wouldn't hurt.
backward scan
def go_backwards(line, end=0): | {
"domain": "codereview.stackexchange",
"id": 45296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
backward scan
def go_backwards(line, end=0):
I found this Public API a little surprising.
As mentioned, I initially envisioned the "find a part number!" task
as scanning left followed by a rightward scan readout.
It's something that works for any part number,
no matter which side of it touches gear(s).
Here, we seem to be talking about more than just the part number,
as the spatial relationship to (one of) its gears also matters.
I understand, from viewing the implementation, why you chose
the identifier end. But to put that in the Public API
is a bit jarring to the caller, who of course only has
a start location in hand.
This seems to be fallout from the decision to represent the
diagram as many strings rather than as a grid of (x, y) locations.
use a function
with open("input.txt") as f:
lines = f.readlines()
sum = 0
...
This is nice enough.
Thank you for using a with context handler to close f.
Once we have lines it will stick around, even if we exdent
the sum assignment four spaces to the left.
This (longish) block of code belongs within def main(): or similar function.
And then we might break out small helper functions.
Avoid shadowing
builtins like
sum().
The conventional name would be sum_, or perhaps prefer total.
strip whitespace
curr_line = "".join(curr_line.strip())
That's weird.
I understand you wanted at least .rstrip() to trim
the trailing newline. But the .join is quite odd,
recommend you delete it.
prev / next
if line_index == 0:
prev_line = curr_line
if line_index >= len(lines) - 1:
next_line = curr_line
else:
next_line = lines[line_index + 1]
...
prev_line = curr_line | {
"domain": "codereview.stackexchange",
"id": 45296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
We always have prev_line defined, good.
But some automated code analyzers will tend to make
a false report that a .findall on prev_line[pos - 1:pos + 2]
may use an uninitialized variable.
So don't be surprised when code like OP is edited
by some future maintenance engineer to start
with a "useless" initialization assignment of, say, empty string.
This is perhaps slightly tricky logic.
It relies on an (easily proved) theorem from the problem domain:
Pretending that gears in current line were also part of the
previous line won't change the result.
This is partly due to our neighborhood definition (currently
the symmetric Moore neighborhood), and partly due to
digit characters and gear characters forming disjoint sets.
I continue to feel that random access to (x, y) locations
would be a more natural fit to the business domain.
We strive to write functions (or "blocks" of main code)
that can be visually taken in as a single screenfull,
with no scrolling, to facilitate Local Analysis.
That (buried) final assignment line illustrates why writing "short"
functions is so important.
two techniques with same meaning
# check number of adjacents before doing anything
if curr_line[pos - 1].isdigit():
adjacents += 1
if curr_line[pos + 1].isdigit():
adjacents += 1
adjacents += len(re.findall(PATTERN, prev_line[pos - 1:pos + 2]))
adjacents += len(re.findall(PATTERN, next_line[pos - 1:pos + 2]))
Thank you for the helpful comment, and for vertically setting this code apart.
As usual, when you feel the need to write a comment, that often
suggests the need to write a helper function.
Here, we might name it def get_number_of_adjacents....
The name PATTERN is not very helpful.
Better to mention that it matches digits.
I find it sad that we have two different approaches for
accomplishing the same thing:
test character .is_digit()
regex digit pattern match | {
"domain": "codereview.stackexchange",
"id": 45296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
python, programming-challenge
test character .is_digit()
regex digit pattern match
The current code could at least unify them by eschewing .is_digit
in favor of a regex pattern match.
But better to eschew regexes entirely, and use .is_digit everywhere.
In the requirements we see:
any number adjacent to a symbol ... is a "part number"
if adjacents != 2:
continue
I have no idea what that means.
Are we seeking just multi-digit part numbers and ruling out 7 as a valid part?
No.
Maybe it is restricting us to the (smaller)
Von Neumann neighborhood?
I am at a loss to explain the motivation behind the
magic number 2.
You might have written a # comment to help me out.
This diagram should explain my confusion:
...378..
..*.....
........
3 is adjacent to a gear.
I only come up with adjacents == 1 in this situation.
Seems like a bug.
part_numbers = list()
Standard idiom here is to assign ... = [].
Larry Wall says there's more than one way to skin a cat.
GvR says there should be one obvious way to do it.
delta coords
My goodness, what a lot of code to express the "is adjacent" concept!
# part numbers next to *
...
# part number in prev line at * position
...
# part number in prev line at position -1 or +1 of *
...
# part number in next line at * position
...
# part number in next line at position -1 or +1 of *
...
Prefer these simpler (delta_x, delta_y) offsets:
nbrhd = [
(-1, -1),
(0, -1),
(1, -1),
(-1, 0),
(1, 0),
(-1, 1),
(0, 1),
(1, 1),
]
for dx, dy in nbrhd:
examine x+dx, y+dy
Some folks prefer a pair of ranges,
with the special case of ignoring the (0, 0) "self" cell.
This code appears to achieve its design goals.
I would not be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, programming-challenge",
"url": null
} |
game, c++17, logging
Title: Logger with a Core and Client side
Question: This logger is for a game engine I'm writing it has a core side which is the game itself and a client side which is the engine. The architecture of the code I feel like is messy it has the main log files which is a .h and a cpp and each client and core has its own .h and cpp file. Is there any way I can improve this logger?
LOG.H
#pragma once
#include <iostream>
#include <mutex>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <string>
enum class LogLevel { TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL };
class Logger {
public:
explicit Logger(LogLevel level = LogLevel::INFO);
virtual void log(LogLevel level, const std::string& message);
void setLogLevel(LogLevel level);
protected:
std::mutex mutex;
LogLevel logLevel;
std::string getTimestamp();
virtual std::string logLevelToString(LogLevel level);
virtual std::string formatMessage(LogLevel level, const std::string& message);
virtual void outputLog(const std::string& formattedMessage);
std::string getColorCode(LogLevel level);
};
#define LOG_TRACE(logger, msg) (logger).log(LogLevel::TRACE, "Walnut: " + std::string(msg))
#define LOG_DEBUG(logger, msg) (logger).log(LogLevel::DEBUG, "Walnut: " + std::string(msg))
#define LOG_INFO(logger, msg) (logger).log(LogLevel::INFO, "Walnut: " + std::string(msg))
#define LOG_WARN(logger, msg) (logger).log(LogLevel::WARN, "Walnut: " + std::string(msg))
#define LOG_ERROR(logger, msg) (logger).log(LogLevel::ERROR, "Walnut: " + std::string(msg))
#define LOG_CRITICAL(logger, msg) (logger).log(LogLevel::CRITICAL, "Walnut: " + std::string(msg)) | {
"domain": "codereview.stackexchange",
"id": 45297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "game, c++17, logging",
"url": null
} |
game, c++17, logging
#define LOG_CORE_TRACE(logger, msg) (logger).log(LogLevel::TRACE, "Walnut: " + std::string(msg))
#define LOG_CORE_DEBUG(logger, msg) (logger).log(LogLevel::DEBUG, "Walnut: " + std::string(msg))
#define LOG_CORE_INFO(logger, msg) (logger).log(LogLevel::INFO, "Walnut: " + std::string(msg))
#define LOG_CORE_WARN(logger, msg) (logger).log(LogLevel::WARN, "Walnut: " + std::string(msg))
#define LOG_CORE_ERROR(logger, msg) (logger).log(LogLevel::ERROR, "Walnut: " + std::string(msg))
#define LOG_CORE_CRITICAL(logger, msg) (logger).log(LogLevel::CRITICAL, "Walnut: " + std::string(msg))
LOG.CPP
#include "Log.h"
Logger::Logger(LogLevel level) : logLevel(level) {}
void Logger::log(LogLevel level, const std::string& message) {
if (static_cast<int>(level) < static_cast<int>(logLevel)) {
return;
}
std::lock_guard<std::mutex> lock(mutex);
auto timestamp = getTimestamp();
auto formattedMessage = formatMessage(level, message);
outputLog(getColorCode(level) + "[" + timestamp + "] " + formattedMessage);
}
void Logger::setLogLevel(LogLevel level) {
logLevel = level;
}
std::string Logger::getTimestamp() {
auto now = std::chrono::system_clock::now();
auto now_c = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&now_c), "%F %T");
return ss.str();
}
std::string Logger::logLevelToString(LogLevel level) {
// Implement log level to string conversion if needed
return "";
}
std::string Logger::formatMessage(LogLevel level, const std::string& message) {
// Modify as needed based on the required format
return logLevelToString(level) + "" + message;
}
void Logger::outputLog(const std::string& formattedMessage) {
std::cout << formattedMessage << "\x1b[0m" << std::endl << std::flush; // Reset color
} | {
"domain": "codereview.stackexchange",
"id": 45297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "game, c++17, logging",
"url": null
} |
game, c++17, logging
std::string Logger::getColorCode(LogLevel level) {
switch (level) {
case LogLevel::TRACE:
return "\x1b[90m"; // Grey
case LogLevel::DEBUG:
return "\x1b[34m"; // Blue
case LogLevel::INFO:
return "\x1b[32m"; // Green
case LogLevel::WARN:
return "\x1b[93m"; // Yellow
case LogLevel::ERROR:
return "\x1b[38;2;255;165;0m"; // Orange
case LogLevel::CRITICAL:
return "\x1b[31m"; // Red
default:
return "";
}
}
Main.cpp
#include <iostream>
#include "CoreLogger.h"
#include "ClientLogger.h"
int main() {
Logger logger(LogLevel::TRACE);
while (true) {
// Logging using Client identifier
LOG_TRACE(logger, "This is a trace message from Client.");
LOG_DEBUG(logger, "This is a debug message from Client.");
LOG_INFO(logger, "This is an info message from Client.");
LOG_WARN(logger, "This is a warning message from Client.");
LOG_ERROR(logger, "This is an error message from Client.");
LOG_CRITICAL(logger, "This is a critical message from Client.");
// Logging using Core identifier
LOG_CORE_TRACE(logger, "This is a trace message from Core.");
LOG_CORE_DEBUG(logger, "This is a debug message from Core.");
LOG_CORE_INFO(logger, "This is an info message from Core.");
LOG_CORE_WARN(logger, "This is a warning message from Core.");
LOG_CORE_ERROR(logger, "This is an error message from Core.");
LOG_CORE_CRITICAL(logger, "This is a critical message from Core.");
}
return 0;
}
Answer: This assumes that you are using C++17 based on previous discussions. | {
"domain": "codereview.stackexchange",
"id": 45297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "game, c++17, logging",
"url": null
} |
game, c++17, logging
Answer: This assumes that you are using C++17 based on previous discussions.
Prefer composition over inheretance. Here, you can create a single non-virtual logger class. Then create an interface for IO and a formatter classes. That way you dont have to override all the methods if you want to customize a logger. It also seperate concerns by confining IO operations to IO class and formatting operations to format class. Checkout spdlog's sink class. It is a good example.
You dont need the mutex in logger class if you seperate the concerns like i described. This way non threaded loggers will not have to pay for the mutex. Makes it easier to reason too.
For functions returning hardcoded strings like logLevelToString() and getColorCode(). Use std::string_view. std::string is expensive and involves memory allocation followed by a copy operation. You already have the string literal in memory so there is no point creating a string.
logLevel member in Logger has a bit of a confusing name call it maxLogLevel
If you are going to arithematic with enum classes define a underlying type and then use std::underlying_type_t to retrive it. Dont just cast to int. Doing the former may lead to undefined behavior. It is rare since int on most platform is very large.
std::flush is redudant
LOG_CORE_* macros are redudant remove them.
Use __LINE__, __FILE__ to log the filename and line number. Without that a log is much more difficult to use.
Provide a streaming interface for people who like that. | {
"domain": "codereview.stackexchange",
"id": 45297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "game, c++17, logging",
"url": null
} |
c, floating-point
Title: A function to convert 0-2000 milliseconds to a double representing a fraction of a second
Question: // ms is expected to be between 0 and 2000
// fakeDouble is expected to be {0, 0}
// uint64_t isn't used because it doesn't work with /NODEFAULTLIB when compiling 32-bit
void msToDouble(uint32_t ms, uint32_t* fakeDouble) {
if (ms == 0) {
return;
} else if (ms >= 2000) {
fakeDouble[1] = 0x40000000;
return;
}
int exponent = 0;
while (ms < 1000) {
ms *= 2;
exponent += 1;
}
fakeDouble[1] = (1023 - exponent) << 20;
for (int bitPlace = 51; ms != 1000 && bitPlace >= 0; bitPlace--) {
ms -= 1000 * (ms > 1000);
ms *= 2;
fakeDouble[bitPlace >= 32] |= (ms >= 1000) << (bitPlace - (32 * (bitPlace >= 32)));
}
}
I read about compiling with the /NODEFAULTLIB option, and I'm planning on doing that with a small program I'm working on since it doesn't use much standard library stuff. This is a function I'll need to use due to not having access to atof or similar functions.
Answer: random garbage in initial word
// fakeDouble is expected to be {0, 0}
This is insanity.
The code needs to implement this comment.
Either assert that caller supplied 64 zero bits,
or assign zeros upon entry.
fakeDouble[1] = 0x40000000;
Relying on the [0] element to be zero is far too adventurous.
As written it is indeterminate what double value this function returns.
We strive to avoid Undefined Behavior. | {
"domain": "codereview.stackexchange",
"id": 45298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, floating-point",
"url": null
} |
algorithm, ruby, fizzbuzz
Title: Ruby FizzBuzz using the ternary operator two times
Question: Task: Implement a function which loops from 1 to 100 and prints "Fizz" if the counter is divisible by 3. Prints "Buzz" if the counter is divisible by 5 and "FizzBuzz", when the counter is divisible by 3 and 5.
The instructor gave me the hint, that it's solvable using the ternary operator. Otherwise I would have used an if-then-else approach.
My solution:
def fizz_buzz
for i in 1...100
puts i % 3 == 0 ? i % 5 == 0 ? "FizzBuzz" : "Fizz" : i % 5 == 0 ? "Buzz" : i
end
end
What's your opinion about the approach? Would you still consider it as readable?
I personally consider the readability hard on the border.
Which approach would you prefer and why?
Answer: Ternary statement is cleaner and often faster to comprehend than if/else; especially true for languages with ceremony syntax, such as curly braces. And I like nested ternary statements (or is it singular?) but it's important to format to help the reader with logic flow. Assume the reader knows the operator structure and resist over-indentation resulting eye boggling pseudo if/else.
def fizz_buzz
for i in 1...100
puts i % 3 == 0 ? i % 5 == 0 ? "FizzBuzz" : "Fizz" :
i % 5 == 0 ? "Buzz" : i
end
end | {
"domain": "codereview.stackexchange",
"id": 45299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, ruby, fizzbuzz",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.