text stringlengths 1 2.12k | source dict |
|---|---|
beginner, console, go, concurrency, ssl
Say the niche and danger packages should only be called in very, very special situations, in particular our danger module could contain some CGO stuff, or make use of reflection and unsafe stuff. We need to provide it with some values to work on, but we have to ensure that this only happens in one place in the code. We can protect ourselves from accidentally using these packages in the wrong place like this:
func DoStuff(niche args.Niche, danger args.Danger) {
// this function can't call function on niche and danger imports, because the variables mask the package name
// niche.SomeFuncFromPackage will look for a method on args.Niche. Same for danger.Foo()
// these variable names mask the import, but...
// some code
// we have determined we need the niche/danger packages:
ch := make(chan args.DangerRet) // unbuffered
defer close(ch)
go func(narg args.Niche, darg args.Danger) {
nRet := niche.ProcessArgs(nargs)
ch <- danger.DoStuff(darg, nRet) // call danger package and push to channel
}(niche, danger)
return <- ch // wait for routine and return
} | {
"domain": "codereview.stackexchange",
"id": 44127,
"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, console, go, concurrency, ssl",
"url": null
} |
beginner, console, go, concurrency, ssl
Situations like these are extremely rare, but sometimes you want to make sure some object isn't being used, not even read access, in any other routine (of course, you'd have to implement a bunch of other code for that), so you can then use it in a very specific way that goes beyond the normal framework the go runtime provides for safe, concurrent code. I am still using a fairly simple setup, because the point here is not the use of a go routine. I'm leveraging the routine mostly to ensure that I'm doing everything in as contained a way as possible. The overall function is still blocking, because I am using an unbuffered channel, so the routine and the return statement sync up. You could just use an anonymous function here, but considering that this is, as I said repeatedly, a very rare thing to do, chances are you'll still use a routine that will first do everything it needs to do to ensure the values you're about to operate on are not being used anywhere else, etc... | {
"domain": "codereview.stackexchange",
"id": 44127,
"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, console, go, concurrency, ssl",
"url": null
} |
performance, swift, mathematics, factors
Title: Finding Highly Composite Numbers in Swift
Question: This code finds highly composite numbers (numbers with more factors than any smaller number) in Swift. I'm not too familiar with Swift, I did this in python but it was too slow so I decided to try it. I made some optimizations, such as only evaluating factors up to \$\sqrt{n}\$, but I would like to improve performance more. In particular, I'm not entirely sure about correcting for square numbers. Is checking whether sqrt(n) == Int(sqrt(n)) the fastest method, or is there something else that would work better? Is there anything else in the factoring that could be improved?
Edit: I don't really care about memory usage. Also, some general style advice would be appreciated, considering I don't use swift much.
#!/usr/bin/swift
func factors(_ n: Int) -> Int {
let root = Double(n).squareRoot()
let iroot = Int(root)
return 2 * (1...iroot).map({n % $0}).filter({$0 == 0}).count - (Double(iroot) == root ? 1 : 0)
}
var max = 2
for i in 1...(Int(CommandLine.arguments[1]) ?? 100000) {
let f = factors(i)
if f > max {
max = f
print(i, f)
}
}
Answer: The “main” function
for i in 1...(Int(CommandLine.arguments[1]) ?? 100000)
is both difficult to read and problematic:
If no arguments are given to the program then it just crashes.
If a non-integer argument is given then an upper bound of \$ 100,000 \$ is assumed.
If zero or a negative number is given as the upper bound then the program also crashes.
Additional arguments are silently ignored. | {
"domain": "codereview.stackexchange",
"id": 44128,
"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, swift, mathematics, factors",
"url": null
} |
performance, swift, mathematics, factors
Better check the number of arguments and their validity explicitly, even if it is more code. Print an informative message if wrong arguments are given. It is also common usage to exit with a non-zero exit status if a command line program failed.
Use more descriptive variable names.
I would suggest something like this
if CommandLine.arguments.count != 2 {
print("Usage: \(CommandLine.arguments[0]) upper_bound");
exit(EXIT_FAILURE)
}
guard let upperBound = Int(CommandLine.arguments[1]), upperBound > 0 else {
print("upper bound must be a positive integer");
exit(EXIT_FAILURE)
}
var currentMax = 0
for i in 1...upperBound {
let numFactors = factors(i)
if numFactors > currentMax {
currentMax = numFactors
print(i, numFactors)
}
}
(For command line programs with more parameters you might consider to use the Swift ArgumentParser package.)
Improving your factors function
Your factors() function seems works correctly, as far as I can see. There is a theoretical risk of rounding errors since a 64-bit IEEE floating point number with its 53-bit significant cannot represent all large integers precisely. But as long as your numbers are below \$2^{53} = 9007199254740992\$, you are on the safe side.
The name is a bit misleading: The function does not determine the factors of a numbers but the count of factors, better names might be countFactors or countDivisors.
The function is very inefficient however. It can be improved a bit with small effort, but there are much better algorithms (more below).
First note that
(1...iroot).map({n % $0})
creates an array of length iroot with all the remainders. Then
.filter({$0 == 0}) | {
"domain": "codereview.stackexchange",
"id": 44128,
"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, swift, mathematics, factors",
"url": null
} |
performance, swift, mathematics, factors
creates an array of length iroot with all the remainders. Then
.filter({$0 == 0})
creates another array with all remainders which are zero. Creating (and disposing of) these arrays takes time (and memory), but all you are interested is the final count. Therefore an explicit loop is more efficient:
func factors(_ n: Int) -> Int {
let root = Double(n).squareRoot()
let iroot = Int(root)
var count = 0
for i in 1...iroot {
if n.isMultiple(of: i) {
count += 2
}
}
if Double(iroot) == root {
count -= 1
}
return count
}
A better algorithm
An efficient method to determine the number of divisors of an integer (and I'm repeating arguments from Getting all divisors from an integer now) is to use the prime factorization: If
$$
n = p_1^{e_1} \, p_2^{e_2} \cdots p_k^{e_k}
$$
is the factorization of \$ n \$ into prime numbers \$ p_i \$
with exponents \$ e_i \$, then
$$
\sigma_0(n) = (e_1+1)(e_2+1) \cdots (e_k+1)
$$
is the number of divisors of \$ n \$, see for example
Wikipedia: Divisor function. Example:
$$
720 = 2^4 \cdot 3^2 \cdot 5^1 \Longrightarrow
\sigma_0(720) = (4+1)(2+1)(1+1) = 30 \, .
$$
A possible implementation (taken from Project Euler #12 in Swift - Highly divisible triangular number and updated for Swift 4+) is
func countDivisors(_ n : Int) -> Int {
var n = n
var numDivisors = 1
var factor = 2
while factor * factor <= n {
if n % factor == 0 {
var exponent = 0
repeat {
exponent += 1
n /= factor
} while n % factor == 0
numDivisors *= exponent + 1
}
factor = factor == 2 ? 3 : factor + 2
}
if n > 1 {
numDivisors *= 2
}
return numDivisors
}
Benchmarks
Running the code with an upper bound of \$10,000,000\$ (on a MacBook Air, compiled in Release configuration): | {
"domain": "codereview.stackexchange",
"id": 44128,
"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, swift, mathematics, factors",
"url": null
} |
performance, swift, mathematics, factors
With your original factors function: 49 seconds.
With the improved factors function: 13 seconds.
With the countDivisors function: 3 seconds.
Further suggestions
I may be advantageous to compute all prime numbers (up to the square root of the upper bound) in advance, for example with the Sieve of Eratosthenes.
Then you can use these prime numbers as trial divisors in the countDivisors function instead of trying all odd numbers. | {
"domain": "codereview.stackexchange",
"id": 44128,
"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, swift, mathematics, factors",
"url": null
} |
c#, bloom-filter
Title: Bloom Filter C#
Question: Here is a bloom filter I made in C#:
public class BloomFilter
{
private BitArray PosValues = new BitArray(int.MaxValue);
private BitArray NegValues = new BitArray(int.MaxValue);
public void AddValue(int HashCode)
{
if (HashCode > 0)
{
PosValues[HashCode - 1] = true;
}
else if (HashCode < 0)
{
NegValues[-HashCode - 1] = true;
}
}
public bool ValueUsed(int HashCode)
{
if (HashCode > 0)
{
return PosValues[HashCode - 1];
}
else if (HashCode < 0)
{
return NegValues[-HashCode - 1];
}
return true;
}
}
And here is an example of how I use it:
public void Test()
{
BloomFilter bloomFilter = new BloomFilter();
MessageBox.Show(bloomFilter.ValueUsed("Test".GetHashCode()).ToString()); //Return false.
bloomFilter.AddValue("Test".GetHashCode()); //Add the string to the bloom filter.
MessageBox.Show(bloomFilter.ValueUsed("Test".GetHashCode()).ToString()); //Returns true.
}
Is this a good implementation of a bloom filter?
Answer: Naming
Please try to follow the C# standard naming, like
private members should use camel casing
method parameters should use camel casing (except positional records)
etc.
Please try to avoid short names / abbreviation when possible
PosValues >> positiveValues
BitArray
I haven't used this structure before so I had to read about it :D
You can also mark them as readonly
AddValue
Based on the provided example it might make sense to expect a string as a parameter and call the GetHashCode inside this method
[-HashCode - 1]: It is pretty easy to miss the - operator at the beginning
I would suggest to use HashCode * -1 instead to make your intent more visible
I would also suggest a bit of restructuring to avoid using guard expressions | {
"domain": "codereview.stackexchange",
"id": 44129,
"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#, bloom-filter",
"url": null
} |
c#, bloom-filter
I would also suggest a bit of restructuring to avoid using guard expressions
if (HashCode = 0) return;
var isHashCodePositive = HashCode > 0;
BitArray toBeUpdatedArray = isHashCodePositive ? PosValues : NegValues;
int index = isHashCodePositive ? HashCode : HashCode * -1;
toBeUpdatedArray[index - 1] = true;
ValueUsed
In case of C# we usually have the following naming convention for bool returning members:
If it is a property then prefix it with is >> IsValueUsed
If it is a method then prefix it with has >> HasValueUsed
I've worked at a company where only is prefix was used everywhere
I have the same advices here as I've listed at AddValue
For the sake of completeness here is the revised version of your BloomFilter class
public class BloomFilter
{
private readonly BitArray positiveValues = new BitArray(int.MaxValue);
private readonly BitArray negativeValues = new BitArray(int.MaxValue);
public void AddValue(string value)
{
int hashCode = value?.GetHashCode() ?? 0;
if (hashCode == 0) return;
var isHashCodePositive = hashCode > 0;
BitArray toBeUpdatedArray = isHashCodePositive ? positiveValues : negativeValues;
int index = isHashCodePositive ? hashCode : hashCode * -1;
toBeUpdatedArray[index - 1] = true;
}
public bool HasValueUsed(string value)
{
int hashCode = value?.GetHashCode() ?? 0;
if (hashCode == 0) return true;
var isHashCodePositive = hashCode > 0;
BitArray toBeLookedUpArray = isHashCodePositive ? positiveValues : negativeValues;
int index = isHashCodePositive ? hashCode : hashCode * -1;
return toBeLookedUpArray[index - 1];
}
}
Of course the common part could be extracted to reduce redundancy
public class BloomFilter
{
private readonly BitArray positiveValues = new (int.MaxValue);
private readonly BitArray negativeValues = new (int.MaxValue); | {
"domain": "codereview.stackexchange",
"id": 44129,
"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#, bloom-filter",
"url": null
} |
c#, bloom-filter
public void AddValue(string value)
{
var (hashCode, isPositive) = GetHashCode(value);
if (hashCode == 0) return;
var (array, index) = GetArrayAndIndex(hashCode, isPositive);
array[index] = true;
}
public bool HasValueUsed(string value)
{
var (hashCode, isPositive) = GetHashCode(value);
if (hashCode == 0) return true;
var (array, index) = GetArrayAndIndex(hashCode, isPositive);
return array[index];
}
private static (int HashCode, bool IsPositive) GetHashCode(string value)
{
int hashCode = value?.GetHashCode() ?? 0;
bool isPositive = hashCode > 0;
return (hashCode, isPositive);
}
private (BitArray Array, Index) GetArrayAndIndex(int hashCode, bool isPositive)
{
BitArray array = isPositive ? positiveValues : negativeValues;
int index = isPositive ? hashCode : hashCode * -1;
return (array, index - 1);
}
} | {
"domain": "codereview.stackexchange",
"id": 44129,
"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#, bloom-filter",
"url": null
} |
performance, c, multithreading, http
Title: Multi-threaded web server serving HTML, images, etc
Question: I have a web server that can send websites, images, mp3 and other things and I was wondering how I could improve the code and make the server more efficient.
//this is where you enter the default file directories
char *defaultDir1 = "/Users/rowan/Desktop/webServer(Mac)/website/displaySite/";
char *defaultDir2 = "/Users/rowan/Desktop/webServer(Mac)/";
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>
struct sockaddr_in sockaddr;
char webFileDir[9000];
char servFileDir[9000];
#define THREAD_POOL_SIZE 200
#define BACKLOG 200
pthread_t thread_pool[THREAD_POOL_SIZE];
//creates a lock and unlock system for enqueue and dequeue
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//creates a sleep timer for the threads/does something until given a signal or condition.
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
struct node {
int client_socket;
struct node *next;
};
typedef struct node node_t;
node_t *head = NULL;
node_t *tail = NULL;
void enqueue(int client_socket) {
node_t *newnode = malloc(sizeof(node_t)); //create node
newnode->client_socket = client_socket; //assign client socket
newnode->next = NULL; //add node to the end of the list
if (tail == NULL) { //checks if there is nothing on the tail and if so adds a head
head = newnode;
} else {
//if there is a tail then add a new node onto the tail
tail->next = newnode;
}
tail = newnode;
//this all basically creates a new node then moves it over over and over again until stopped
}
int dequeue() {
if (head == NULL) return -1;//if the head is empty or nothing has been enqueued then return null | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
if (head != NULL) { //else...
int result = head->client_socket;
node_t *temp = head;
head = head->next;
if (head == NULL) {tail = NULL;}
free(temp);
return result;
}
//this function removes everything off of the queue and returns the socket
return 0;
}
int *handleClient(int pclientSock) {
FILE *fpointer;
char *findExtention;
char *clientIP;
char *endDir;
int freadErr;
int fsize;
int bin;
int readSock;
char recvLine[2];
char fileDir[9000];
char recvLineGET[60];
char httpResponseReport[1000];
char *fileLine;
char httpResponse[1000];
char *endOfPost;
char fullResp[100000];
int checkSend;
char *startDir;
char *getEnd;
int responseCode = 200;
bzero(fileDir, sizeof(fileDir));
bzero(recvLineGET, sizeof(recvLineGET));
//get client ip
int acceptSock = pclientSock;
socklen_t addrSize = sizeof(struct sockaddr_in);
getpeername(acceptSock, (struct sockaddr *)&sockaddr, &addrSize);
clientIP = inet_ntoa(sockaddr.sin_addr);
fullResp[0] = '\0';
//handles reading client http request
while (1) {
if ((readSock = read(acceptSock, recvLine, 1)) != 1) {
perror("error reading from socket");
//error 500: internal server error
send(acceptSock, "HTTP/1.1 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(recvLine, sizeof(recvLine));
bzero(fullResp, sizeof(fullResp));
close(acceptSock);
return 0;
}
recvLine[1] = '\0';
strcat(fullResp, recvLine);
if ((endOfPost = strstr(fullResp, "\n")) != NULL) {
break;
} else if (readSock < 0) {
//perror("endOfHttpBody error");
bzero(fullResp, sizeof(fullResp));
close(acceptSock);
return 0;
}
bzero(recvLine, sizeof(recvLine));
} | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
strcpy(fileDir, webFileDir);
if ((getEnd = strstr(fullResp, "HTTP")) == NULL) {
perror("error reading from socket");
bzero(fullResp, sizeof(fullResp));
//error 400: bad request
send(acceptSock, "HTTP/1.0 400\r\n\r\n", 16, MSG_NOSIGNAL);
close(acceptSock);
return 0;
}
strcpy(getEnd, "");
if ((startDir = strchr(fullResp, '/')) == NULL) {
perror("this shouldnt happen .-.");
printf("startDir: %s\n", startDir);
//error 400: bad request
send(acceptSock, "HTTP/1.0 400\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fullResp, sizeof(fullResp));
close(acceptSock);
return 0;
}
//handles the file retrieving
if ((endDir = strchr(startDir, ' ')) == NULL) {
perror("endDir error");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fileDir, sizeof(fileDir));
bzero(fullResp, sizeof(fullResp));
close(acceptSock);
return 0;
}
strcpy(endDir, "");
//checks for requested directory
if (strcmp(startDir, "/") == 0) {
findExtention = ".html";
strcpy(fileDir, webFileDir);
strcat(fileDir, "index.html");
responseCode = 200;
} else {
if ((findExtention = strchr(startDir, '.')) == NULL) {
perror("invalid webpage");
findExtention = ".html";
strcpy(fileDir, servFileDir);
strcat(fileDir, "err404.html");
responseCode = 404;
}
strcat(fileDir, startDir);
}
if ((fpointer = fopen(fileDir, "rb")) != NULL) {
fseek(fpointer, 0L, SEEK_END);
fsize = ftell(fpointer);
} else if (strcmp(startDir-1, "/favicon.ico") == 0 && access(fileDir, F_OK) != 0) {
strcpy(fileDir, servFileDir);
strcat(fileDir, "favicon.ico"); | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
if (access(fileDir, F_OK) != 0) {
printf("\n\n\nERROR: please do not delete the default favicon.ico file. the program will not work properly if it is deleted\n\n\n");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
exit(1);
}
if ((fpointer = fopen(fileDir, "rb")) == NULL) {
perror("fopen error");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fullResp, sizeof(fullResp));
close(acceptSock);
return 0;
}
fseek(fpointer, 0L, SEEK_END);
fsize = ftell(fpointer);
} else if (access(fileDir, F_OK) != 0) {
perror("webpage doesnt exist");
findExtention = ".html";
strcpy(fileDir, servFileDir);
strcat(fileDir, "err404.html");
responseCode = 404;
if ((fpointer = fopen(fileDir, "r")) == NULL) {
perror("fopen error");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fullResp, sizeof(fullResp));
close(acceptSock);
return 0;
}
fseek(fpointer, 0L, SEEK_END);
fsize = ftell(fpointer);
}
fclose(fpointer); | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
fclose(fpointer);
//sets the server http response
if ((strcmp(findExtention, ".jpeg")) == 0 || (strcmp(findExtention, ".jpg")) == 0) {
bin = 1;
sprintf(httpResponse, "HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: image/jpeg\r\nContent-Length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n", responseCode, fsize);
} else if ((strcmp(findExtention, ".png")) == 0) {
bin = 1;
sprintf(httpResponse, "HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: image/png\r\nContent-Length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n", responseCode, fsize);
} else if ((strcmp(findExtention, ".ico")) == 0) {
bin = 1;
sprintf(httpResponse, "HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: image/x-icon\r\nContent-Length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n", responseCode, fsize);
} else if ((strcmp(findExtention, ".mp3")) == 0) {
bin = 1;
sprintf(httpResponse, "HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: audio/mpeg\r\nContent-length: %d\r\nContent-Transfer-Encoding: binary\r\n\r\n", responseCode, fsize);
} else if ((strcmp(findExtention, ".html")) == 0) {
bin = 0;
sprintf(httpResponse, "HTTP/1.0 %d\r\nConnection: close\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", responseCode, fsize);
} else {
strcpy(fileDir, "err404.html");
if ((fpointer = fopen(fileDir, "r")) == NULL) {
perror("fopen error");
bzero(fullResp, sizeof(fullResp));
close(acceptSock);
return 0;
}
fseek(fpointer, 0L, SEEK_END);
fsize = ftell(fpointer);
fclose(fpointer);
bin = 0;
sprintf(httpResponse, "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n", fsize);
}
strcpy(httpResponseReport, httpResponse);
if (readSock < 0) {
perror("readsock is less than 0"); | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
if (readSock < 0) {
perror("readsock is less than 0");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fullResp, sizeof(fullResp));
bzero(fileDir, sizeof(fileDir));
bzero(httpResponseReport, sizeof(httpResponseReport));
bzero(httpResponse, sizeof(httpResponse));
close(acceptSock);
return 0;
}
//checks if i need to read plaintext or binary
if (bin == 0) {
fpointer = fopen(fileDir, "r");
} else if (bin == 1) {
fpointer = fopen(fileDir, "rb");
}
if (fpointer == NULL) {
perror("file open error");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fullResp, sizeof(fullResp));
bzero(fileDir, sizeof(fileDir));
bzero(httpResponseReport, sizeof(httpResponseReport));
bzero(httpResponse, sizeof(httpResponse));
close(acceptSock);
return 0;
}
//sends server http response to client
fseek(fpointer, 0L, SEEK_END);
fsize = ftell(fpointer);
fclose(fpointer);
//checks if i need to read plaintext or binary (again)
if (bin == 0) {
fpointer = fopen(fileDir, "r");
} else if (bin == 1) {
fpointer = fopen(fileDir, "rb");
}
if (fpointer == NULL) {
perror("fopen error");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fullResp, sizeof(fullResp));
bzero(fileDir, sizeof(fileDir));
bzero(httpResponse, sizeof(httpResponse));
bzero(httpResponseReport, sizeof(httpResponseReport));
close(acceptSock);
return 0;
}
fileLine = malloc(fsize * sizeof(char));
while ((freadErr = fread(fileLine, fsize, fsize, fpointer)) > 0);
if (feof(fpointer) < 0) {
perror("fread error"); | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
bzero(fullResp, sizeof(fullResp));
bzero(fileDir, sizeof(fileDir));
bzero(httpResponseReport, sizeof(httpResponseReport));
bzero(httpResponse, sizeof(httpResponse));
close(acceptSock);
return 0;
}
//set 5 second socket timeout
struct timeval timeout;
timeout.tv_sec = 15;
timeout.tv_usec = 0;
if (setsockopt(acceptSock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0) {
perror("setsockopt error");
//error 500: internal server error
send(acceptSock, "HTTP/1.0 500\r\n\r\n", 16, MSG_NOSIGNAL);
close(acceptSock);
return 0;
}
while (1) {
if ((checkSend = send(acceptSock, httpResponse, strlen(httpResponse), MSG_NOSIGNAL)) == -1) {
break;
}
//send full response
if ((checkSend = send(acceptSock, fileLine, fsize, MSG_NOSIGNAL)) == -1) {
break;
}
sleep(1);
}
bzero(httpResponse, sizeof(httpResponse));
bzero(fullResp, sizeof(fullResp));
fclose(fpointer);
close(acceptSock);
free(fileLine);
//handles the clearing of variables and logs client ip and requested directory
printf("\nclient with the ip: %s has requested %s.\n", clientIP, fileDir);//added server response but i don't think i need it anymore
bzero(fileDir, sizeof(fileDir));
bzero(httpResponseReport, sizeof(httpResponseReport));
return 0;
}
//assign work to each thread
void *giveThreadWork() {
while (1) {
int pclient;
pthread_mutex_lock(&mutex);
//makes thread wait until signaled
while ((pclient = dequeue()) == -1) {
pthread_cond_wait(&condition_var, &mutex);
}
pthread_mutex_unlock(&mutex);
handleClient(pclient);
}
} | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
int main() {
int clientSock;
int sock;
int portNum;
int defaultOrNo;
printf("\n\n\nWeb Server\nBy: Rowan Rothe\n\n\n");
printf("would you like to use default directories (1 = yes, 0 = no): ");
scanf("%d", &defaultOrNo);
if (defaultOrNo == 0) {
printf("enter the directory of the files to be served (with '/' at the end): ");
scanf("%s", webFileDir);
printf("enter the directory of the web server folder (with '/' at the end): ");
scanf("%s", servFileDir);
} else if (defaultOrNo == 1) {
strcpy(webFileDir, defaultDir1);
strcpy(servFileDir, defaultDir2);
}
printf("what port would you like to host the site on?: ");
scanf("%d", &portNum);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("sock error");
}
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
sockaddr.sin_port = htons(portNum);
if ((bind(sock, (struct sockaddr *) &sockaddr, sizeof(sockaddr))) < 0) {
perror("bind error");
exit(1);
}
printf("socket bind success\n");
//create all the threads for the thread pool
for (int i = 0; i < THREAD_POOL_SIZE; i++) {
pthread_create(&thread_pool[i], NULL, giveThreadWork, NULL);
}
printf("created thread pool of size %d successfully\n", THREAD_POOL_SIZE);
if ((listen(sock, BACKLOG)) < 0) {
perror("listen error");
}
printf("listen success\n");
while (1) {
//checks for client connection
if ((clientSock = accept(sock, NULL, NULL)) < 0) {
perror("accept error");
} else {
pthread_mutex_lock(&mutex);
enqueue(clientSock);
pthread_cond_signal(&condition_var);
pthread_mutex_unlock(&mutex);
}
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
Answer: Calling strcat in a loop is inefficient
The function strcat works the following way:
It must first search the entire destination string until it finds the terminating null character at the end. It then appends the source string.
Therefore, calling the function strcat in a loop in order to append one character at a time is highly inefficient. This is because whenever you append a single character, it must search the entire destination string again for the terminating null character. (See Schlemiel the Painter's Algorithm for more information.)
If you want to add a single character at a time, then you should not use the function strcat, but should rather remember the position of the end of the string (for example using a pointer or by remembering the length of the string) and add the new character yourself, by overwriting the terminating null character with that character. You can add a new terminating null character at the end of the string after you have finished adding all characters. Or, if you need the character sequence to be a valid null-terminated string after every intermediate step, then you can add a new null-terminating character after every character added.
System calls are expensive
The function read is not a simple function call. It is a system call which must be handled by the operating system's kernel. The overhead of this system call is probably somewhere between 1000 and 3000 CPU cycles. See this question for more information. Also, see the comments section of my answer for some further comments regarding recent increase in system call overhead due to Meltdown/Spectre mitigations.
Therefore, it is a big waste of CPU resources to call this function once for every single character, instead of attempting to read as much as you can at once, using a single system call.
Zeroing large amounts of memory is inefficient | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
Zeroing large amounts of memory is inefficient
You are using the function bzero to zero out large amounts of memory in several places in your program. It seems that you are zeroing out more than 100 KB of memory for every HTTP request.
While it is not much of a problem to do this once at program startup, doing this for every HTTP request seems excessive.
Also, it is unclear why you are zeroing out memory, in particular whether you are doing this | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
to ensure that all strings are null-terminated, or
to erase sensitive data, such as passwords.
If it is #1, then there are other more efficient ways to ensure that strings are always null-terminated.
If it is #2, then you should be using explicit_bzero instead of bzero, because it is possible that bzero will be optimized away by the compiler.
Not guarding against buffer overflows
You don't seem to be guarding against buffer overflows in your program. This means that a malicious client could crash your server by sending a request in which the first line is larger than 100 KB.
This loop is inefficient
For the reasons stated in the previous 4 sections, this loop is inefficient and prone to a buffer overflow:
fullResp[0] = '\0';
//handles reading client http request
while (1) {
if ((readSock = read(acceptSock, recvLine, 1)) != 1) {
//handle error (code omitted)
}
recvLine[1] = '\0';
strcat(fullResp, recvLine);
if ((endOfPost = strstr(fullResp, "\n")) != NULL) {
break;
} else if (readSock < 0) {
//handle error (code omitted)
}
bzero(recvLine, sizeof(recvLine));
}
Also, after every character added, you are searching the entire string again for the newline character, although it would only be necessary to check the last character added.
However, since you are only processing a single line with this inefficient loop, it probably won't matter much. But if a (possibly malicious) client sends you a very long line, your server will spend a significant amount of time processing this line. This vulnerability could be used in a DoS attack against your server.
Also, the variable readSock does not seem appropriately named, as it implies that it contains the value of a socket file descriptor.
An efficient version of the loop, which also protects against buffer overflow, would look like this:
//fullResp[0] = '\0'; //this line is no longer needed
size_t offset = 0; | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
do {
char *p_read_buf = fullResp + offset;
size_t to_read = sizeof fullResp - offset - 1;
if ( to_read == 0 ) {
//handle error (code omitted)
}
if ( ( readSock = read( acceptSock, p_read_buf, to_read ) ) <= 0 ) {
//handle error (code omitted)
}
offset += readSock;
} while ( ( endOfPost = memchr( p_read_buf, '\n', readSock ) ) == NULL );
//add null terminating character
fullResp[offset] = '\0';
Rewind files instead of closing and reopening them
You seem to be opening files, in order to determine their length, and then closing them again, only to reopen them again shortly afterwards. This does not seem meaningful. You can use the function rewind to reset the file position indicator to the start of the file.
This loop seems to be buggy
The following loop appears to be buggy:
while (1) {
if ((checkSend = send(acceptSock, httpResponse, strlen(httpResponse), MSG_NOSIGNAL)) == -1) {
break;
}
//send full response
if ((checkSend = send(acceptSock, fileLine, fsize, MSG_NOSIGNAL)) == -1) {
break;
}
sleep(1);
} | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
sleep(1);
}
It is unclear what this loop is attempting to accomplish.
You seem to be first sending the HTTP response header, then the HTTP response body. However, it is unclear why you are doing this in an infinite loop.
Also, it should not be necessary to call sleep(1) in this loop. If your program does not behave properly without that call, then this is a sign of a bug in your program.
My guess is that you need this wait in order to give the client time to close the connection, so that the first call to send in the second iteration of the loop fails, which causes the loop to break. Otherwise, if the client does not close the connection, you will send the HTTP response to the client in an infinite loop. However, this is not the proper way of solving the problem.
The proper way to solve this is to not use an infinite loop:
//send HTTP response header
size_t len = strlen( httpReponse );
if ( ( checkSend = send( acceptSock, httpResponse, len, MSG_NOSIGNAL) ) != len ) {
//handle error (code omitted)
}
//send HTTP response body
if ( ( checkSend = send(acceptSock, fileLine, fsize, MSG_NOSIGNAL ) ) != fsize ) {
//handle error (code omitted)
}
Your usage of fread is wrong
The line
while ((freadErr = fread(fileLine, fsize, fsize, fpointer)) > 0);
is wrong. You are instructing fread to attempt to read fsize items each of size fsize bytes, i.e. a total of fsize*fsize bytes. Also, the while loop does not make sense.
You should write either
if ( ( freadErr = fread( fileLine, fsize, 1, fpointer ) ) != 1 )
{
//handle error (code omitted)
}
or this:
if ( ( freadErr = fread( fileLine, 1, fsize, fpointer ) ) != fsize )
{
//handle error (code omitted)
}
Your usage of feof is wrong
The line
if (feof(fpointer) < 0) { | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
performance, c, multithreading, http
Your usage of feof is wrong
The line
if (feof(fpointer) < 0) {
does not make sense.
The function feof will return a nonzero value (i.e. true) if the end-of-file indicator has been set on the stream, otherwise zero (i.e. false). Therefore, comparing the returned value with < 0 does not make sense.
Also, the function feof does not check the file position indicator itself. Instead, it merely checks whether the end-of-file indicator on the stream has been set. This end-of-file indicator will only be set if a previous I/O function attempted to read past the end of the file. The end-of-file indicator will not be set if the file position indicator has merely reached the end of the file, so that the next input operation will fail.
For this reason, it does not make sense to call feof. You should check the return value of the previous I/O operation instead (which you are already doing). Only if that I/O operation reports an error or does not read all of the requested input, will it make sense to call feof or ferror to determine the cause.
Redundant if statement
In the function
int dequeue() {
if (head == NULL) return -1;//if the head is empty or nothing has been enqueued then return null
if (head != NULL) { //else...
int result = head->client_socket;
node_t *temp = head;
head = head->next;
if (head == NULL) {tail = NULL;}
free(temp);
return result;
}
//this function removes everything off of the queue and returns the socket
return 0;
}
the second if statement is redundant and the return 0 in the last line is unreachable. You can simply write:
int dequeue() {
if (head == NULL) return -1;//if the head is empty or nothing has been enqueued then return null
int result = head->client_socket;
node_t *temp = head;
head = head->next;
if (head == NULL) {tail = NULL;}
free(temp);
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44130,
"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, c, multithreading, http",
"url": null
} |
java, performance
Title: Speeding up recursive iteration over array in Java
Question: I have a function that needs to compute a system response y in response to an input time series defined by x. In practice, x will be determined by an external process. y is then exposed to external processes as class member timeArray. Computing y entails two levels of recursion.
The function I need to optimize in the class below is update() which has potential to become a process bottleneck at current runtime: ~72 ms on first cycle, ~21ms after a couple dozen iterations. An additional consideration is that in production, this function will be called as a small step in a much larger application, so I'm guessing the cache hits that benefit subsequent runs may have less success when competing with other threads and processes in the JVM.
Pulling the step response calculation requiring a call to exp() out of the inner loop provided the greatest time savings so far, but I'm running out of ideas to further tune. Are there any optimizations I can make to improve execution speed of update()?
import static java.lang.Math.exp;
import static java.lang.Math.sin;
public class Looper {
private static final int MAX_PROPAGATION_TIME = 7200;
private static final int SIM_TIME = 100;
public double[] timeArray = new double[MAX_PROPAGATION_TIME]; | {
"domain": "codereview.stackexchange",
"id": 44131,
"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, performance",
"url": null
} |
java, performance
public static void main(String []args) {
Looper go = new Looper();
go.run();
}
public void run() {
double x[] = new double[MAX_PROPAGATION_TIME];
double tau = 3;
double scale = 1;
double start = 0;
double end = 0;
for (int i = 0; i < SIM_TIME - 1; i++){
for (int j = 0; j < MAX_PROPAGATION_TIME - 1; j++){
x[j] = sin(i) * (1 - exp(-j / 10));
}
start = System.currentTimeMillis();
// update() is the primary function of interest
update(x,tau,scale);
end = System.currentTimeMillis();
System.out.println(String.format("Run %3d: %.0f ms",i,end - start));
//System.out.println(String.format("timeArray[i + 10]: %.2f",this.timeArray[i + 10]));
}
}
public void update(
double[] x,
double tau,
double scale) {
if(tau < 1e-12 / 3) tau = 1e-12 / 3;
double dx;
double y[] = new double[MAX_PROPAGATION_TIME];
// Pre-compute a unit step response for efficiency
double stepResponse[] = new double[MAX_PROPAGATION_TIME];
for (int i = 0; i < MAX_PROPAGATION_TIME - 1; i++){
stepResponse[i] = scale * (1 - exp(-i / tau));
}
// Loop over the full time array and antipated change in x at each time
for (int i = 0; i < MAX_PROPAGATION_TIME - 1; i++){;
dx = x[i+1] - x[i];
// For each element subsequent to time i, evaluate change in y as an
// exponential decay type response and accumulate incremental changes over time
for (int j = i; j < MAX_PROPAGATION_TIME - 1; j++){
y[j] += dx * stepResponse[j - i + 1];
}
}
this.timeArray = y;
}
} | {
"domain": "codereview.stackexchange",
"id": 44131,
"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, performance",
"url": null
} |
java, performance
In response to @harold's question: step response of y in response to a a single unit step in x at t = 0, with tau = 10 would look as follows. Over the full simulation time, each change in x at a given time can be treated as an additional step change to be accumulated over time.
Update:
As suspected, I had been paying too much attention in all the wrong places. Eliminating the inner loop to turn this back to an O(n) problem saves 1-2 orders of magnitude on computation time, thanks Harold!
Answer: Speed
dx * scale * (1 - exp(-i / tau)) can be split up into two parts:
A part that is accumulated without decay, dx * scale
And an exponentially decreasing part, dx * scale * exp(-i / tau), which is subtracted from that.
Both of these can be written in an incremental form, keeping track of a couple of extra values across the loop to influence the elements at higher indices that way, instead of using an extra loop to "spread out" the influence explicitly.
double decayFactor = exp(-1.0 / tau);
double decaying = 0.0;
double accumulate = 0.0;
for (int i = 0; i < MAX_PROPAGATION_TIME - 1; i++){;
dx = x[i+1] - x[i];
accumulate += dx;
decaying = (decaying + dx) * decayFactor;
y[i] = (accumulate - decaying) * scale;
}
As far as I've tested it, the results are the same (close enough, apart from the usual floating point stuff), and it is very fast.
Miscellaneous
It is not necessary to "pre-declare" dx, you can put double dx = x[i+1] - x[i] right there in the loop.
Thanks to the way the faster implementation works, it also allows the computation to be done in-place (without allocating a new array y), of course you may have other reasons not to do that. | {
"domain": "codereview.stackexchange",
"id": 44131,
"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, performance",
"url": null
} |
javascript
Title: Javascipt non stackable level generator
Question: My task was to create a function that returns the level of a user.
A user has a certain amount of XP. Each level is level * 10 xp
so for example
level 1 would be 10 xp
level 2 would be 20 xp
level 3 would be 30 xp
and so on
however your XP doesn't stack
so if you have 30 XP you would fill the requirements for level 1 and 2 but you wouldn't achieve level 3.
I'd love to know if there was anything else I could have improved
function get_level(xp, level = 0) {
if (xp == 0) return level
if (level > 0) {
var generated_xp = level * 10
} else {
var generated_xp = 10
}
var letover = xp - generated_xp
if (letover == 0) return level
if (letover < 0) return level
if (letover > 0) return get_level(xp - generated_xp, level + 1)
}
Answer: A few comments:
// I assume this is meant to be called with only one argument initially?
function get_level(xp, level = 0) {
// This is redundant, the rest of the code will take care of it
if (xp == 0) return level
// So does it require 10 LP to get from level 0 to 1, then 10 again to get from 1 to 2? That seems odd.
if (level > 0) {
// Generated XP is a confusing variable name. Maybe name it something like "required_xp" or "xp_to_next_level"
var generated_xp = level * 10
} else {
var generated_xp = 10
}
// typo: letover, should probably be left over. Again this variable name could be clearer
var letover = xp - generated_xp
if (letover == 0) return level
if (letover < 0) return level
if (letover > 0) return get_level(xp - generated_xp, level + 1)
} | {
"domain": "codereview.stackexchange",
"id": 44132,
"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
If I fixed a few issues but left the structure in tact, you would get something like this:
function get_level(xp, level=0) {
// Reduce the complexity by removing this if statement
let xp_to_next_level = Math.max(10, level*10);
// Remove one arm from the condition
if (xp > xp_to_next_level) {
return get_level(xp - generated_xp, level + 1);
} else {
return level;
}
}
However, I usually try to avoid recursion since I think it makes code hard to read, so I'd prefer something like this:
function get_level(xp) { // can remove second argument now
let level=0;
while (xp > Math.max(level * 10, 10)) {
level++;
}
return level;
}
Or even shorter using the formula of triangle numbers: a*(a+1)/2:
function get_level(xp) {
if (xp<10) {
return 0;
}
return 1 + Math.floor((Math.sqrt(8*(xp-10)/10 + 1) - 1)/2);
} | {
"domain": "codereview.stackexchange",
"id": 44132,
"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
} |
c#, entity-framework
Title: EF 6.0.0.0 include linked table delete with reordering of data
Question: I have this ef 6 delete method where I build <List> the related entities that will need to be deleted. Then I use RemoveRange to remove then. Once its deleted I will need to re-order the data and update the SequenceOrder field.
public ResultStatus DeleteMeetingPollingQuestion(int MeetingPollingQuestionId)
{
using (var db = new NccnEcommerceEntities())
{
using (DbContextTransaction dbTran = db.Database.BeginTransaction())
{
ResultStatus result = new ResultStatus();
try
{
var MeetingPollingQuestions = db.MeetingPollingQuestions.Find(MeetingPollingQuestionId);
if (MeetingPollingQuestions != null)
{
int? reorderinMeetingPollingId = MeetingPollingQuestions.MeetingPollingId;
var deleteMeetingPollingParts = db.MeetingPollingParts
.Where(task => task.MeetingPollingQuestionId == MeetingPollingQuestionId)
.ToList();
List<MeetingPollingPartsValue> deleteMeetingPollingPartsValues = new List<MeetingPollingPartsValue>();
foreach (var MeetingPollingParts in deleteMeetingPollingParts)
{
int MeetingPollingPartsId = MeetingPollingParts.MeetingPollingPartsId;
var MeetingPollingPartsValue = db.MeetingPollingPartsValues.Where(x => x.MeetingPollingPartsId == MeetingPollingPartsId).ToList();
deleteMeetingPollingPartsValues.AddRange(MeetingPollingPartsValue);
} | {
"domain": "codereview.stackexchange",
"id": 44133,
"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#, entity-framework",
"url": null
} |
c#, entity-framework
List<EFModel.MeetingPollingPartsValuesImage> deleteMeetingPollingPartsValuesImages = new List<EFModel.MeetingPollingPartsValuesImage>();
foreach (var MeetingPollingPartsValue in deleteMeetingPollingPartsValues)
{
int MeetingPollingPartsValueId = MeetingPollingPartsValue.MeetingPollingPartsValuesId;
var MeetingPollingPartsValuesImage = db.MeetingPollingPartsValuesImages.Where(x => x.MeetingPollingPartsValuesId == MeetingPollingPartsValueId).ToList();
deleteMeetingPollingPartsValuesImages.AddRange(MeetingPollingPartsValuesImage);
}
db.MeetingPollingPartsValuesImages.RemoveRange(deleteMeetingPollingPartsValuesImages);
db.MeetingPollingPartsValues.RemoveRange(deleteMeetingPollingPartsValues);
db.MeetingPollingParts.RemoveRange(deleteMeetingPollingParts);
db.MeetingPollingQuestions.Remove(MeetingPollingQuestions);
int? positionSequenceOrder = 1;
var reorderingmeetingpollingQuestions = db.MeetingPollingQuestions.Where(w=>w.MeetingPollingId == reorderinMeetingPollingId).OrderBy(x=>x.SequenceOrder).ToList();
foreach (var updatereorderingQuestion in reorderingmeetingpollingQuestions.Where(w=>w.MeetingPollingQuestionId != MeetingPollingQuestionId))
{
updatereorderingQuestion.SequenceOrder = positionSequenceOrder;
db.Entry(updatereorderingQuestion).State = System.Data.Entity.EntityState.Modified;
positionSequenceOrder ++;
}
db.SaveChanges();
dbTran.Commit();
} | {
"domain": "codereview.stackexchange",
"id": 44133,
"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#, entity-framework",
"url": null
} |
c#, entity-framework
db.SaveChanges();
dbTran.Commit();
}
result.ResultCode = Convert.ToInt32(Enums.Result.Code.Success);
result.Message = "Successfully uploaded.";
}
catch (Exception e)
{
dbTran.Rollback();
result.Message = "Error Save Meeting Polling Question" + e.Message;
result.ResultCode = Convert.ToInt32(Enums.Result.Code.Error);
}
return result;
}
}
}
Answer: If I understood the relations between your entities correctly, the code can be greatly simplified by making a single query using Include. This method load all related entities.
However, this single sql-query will be very complex, with multiple Joins.
After that, the Remove method will delete the entire hierarchy of objects in the cascade.
using (var db = new NccnEcommerceEntities())
{
var meetingPollingQuestions = db.MeetingPollingQuestions
.Include(x => x.MeetingPollingParts.Select(y => y.MeetingPollingPartsValues.Select(z => z.MeetingPollingPartsValuesImages)))
.FirstOrDefault(x => x.MeetingPollingQuestionId == MeetingPollingQuestionId);
if (meetingPollingQuestions != null)
{
int? reorderinMeetingPollingId = meetingPollingQuestions.MeetingPollingId;
db.MeetingPollingQuestions.Remove(meetingPollingQuestions);
int? positionSequenceOrder = 1;
var reorderingMeetingpollingQuestions = db.MeetingPollingQuestions.Where(w => w.MeetingPollingId == reorderinMeetingPollingId).OrderBy(x => x.SequenceOrder).ToList();
foreach (var updateReorderingQuestion in reorderingMeetingpollingQuestions.Where(w => w.MeetingPollingQuestionId != MeetingPollingQuestionId))
{
updateReorderingQuestion.SequenceOrder = positionSequenceOrder;
positionSequenceOrder++;
}
db.SaveChanges();
}
} | {
"domain": "codereview.stackexchange",
"id": 44133,
"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#, entity-framework",
"url": null
} |
c#, entity-framework
db.SaveChanges();
}
}
There is no need to manually set the entity State property. It will be marked as modified by itself.
It is very wasteful to download data from the database only to immediately remove it.
In pure SQL, your task can be solved with a single query directly in the database.
But Entity Framework is not able to generate such an efficient SQL.
You can look for extensions for EF that have Bulk Update and Remove operations. There are such extensions for EF Core.
Also, such amazing features have appeared in the newest EF Core 7 version. I advise you to take a closer look at it. | {
"domain": "codereview.stackexchange",
"id": 44133,
"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#, entity-framework",
"url": null
} |
python, beginner, game
Title: A Text-Based Game
Question: The following code is a simple text-based RPG game where you can move between rooms and fight with monsters until you defeat the boss.
import random
import sys
class player(object):
name = "Hero Arius"
hp = 200
power = 20
armor = 20
class gnome(object):
name = "Flimp the Gnome"
hp = 10
power = 1
armor = 3
loot = random.randint(0, 2)
class strongerGnome(object):
name = "Flimp+ the Gnome"
hp = 20
power = 2
armor = 6
loot = random.randint(0, 2)
class goblin(object):
name = "Driekol the Goblin"
hp = 30
power = 4
armor = 4
loot = random.randint(0, 2)
class strongerGoblin(object):
name = "Driekol+ the Goblin"
hp = 60
power = 8
armor = 8
loot = random.randint(0, 2)
class minotaurus(object):
name = "Gratus the Minotaurus"
hp = 120
power = 10
armor = 3
loot = random.randint(0, 2)
class strongerMinotaurus(object):
name = "Gratus+ the Minotaurus"
hp = 240
power = 20
armor = 6
loot = random.randint(0, 2)
class wizard(object):
name = "Gandalf the Wizard"
hp = 480
power = 40
armor = 2
loot = random.randint(0, 2)
hero = player()
flimp = gnome()
strongerFlimp = strongerGnome()
driekol = goblin()
strongerDriekol= strongerGoblin()
gratus = minotaurus()
strongerGratus = strongerMinotaurus()
gandalf = wizard()
class boss(object):
name = "Leoric the Skeletonking"
hp = 960
power = 60
armor = 60
def gameOver(character, points):
if character.hp <= 0:
print(f"\n You are dead!")
print(f"\n Thanks for playing!")
print(f"\n Points: {points}")
writeScore(points)
quit()
def gameWin(points):
print(f"\n You defeated Leoric the Skeletonking!")
print(f"\n You successfully rescued the world! Congrats!")
print(f"\n Points: {points}")
writeScore(points)
exit() | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
writeScore(points)
exit()
def writeScore(points):
f = open("score.txt", "a")
name = input("Enter your name: ")
print(f"Player name: {name}\nPlayer points: {points}\n", file=f)
f.close()
def loot():
loots = ["Sword", "Armor"]
lootChance = random.randint(0, 2)
lootDrop = loots[lootChance]
return lootDrop
def lootEffect(lootDrop, character):
if lootDrop == "Sword":
character.power = character.power + 10
print("You got a new sword!")
print("Power increased by 10.")
print(f"Your power is now: {character.power}")
return character
elif lootDrop == "Armor":
character.armor = character.armor + 10
print("You got a new shield!")
print("Armor increased by 10.")
print(f"Your armor is now: {character.armor}")
return character | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
def battle(points: int) -> int:
global enemy
if current_room == "Terrifying Mine":
enemy = flimp
elif current_room == "Tunnel of Hell":
enemy = strongerFlimp
elif current_room == "Deceptive Cave":
enemy = driekol
elif current_room == "Illusion Cave":
enemy = strongerDriekol
elif current_room == "Unstable Vortex":
enemy = gratus
elif current_room == "Imaginary Labyrinth":
enemy = strongerGratus
else:
enemy = gandalf
print(f"{enemy.name} showed up!")
print("You have two options:")
while enemy.hp >= 0:
choice = input("\n [1] - Attack\n [2] - Retreat\n ")
if choice == "1":
print(f"\n{'-' * 27}")
print(f"{hero.name} swung his sword, attacking {enemy.name}!")
hitchance = random.randint(0, 10)
if hitchance > 3:
enemy.hp = enemy.hp - hero.power
print(f"You wound the enemy, the enemy's life: {enemy.hp} hp")
if enemy.hp > 1:
hero.hp = round(hero.hp - (enemy.power / hero.armor))
print(f"{enemy.name} is striking back, it has wounded you! Health: {hero.hp} hp")
print(f"{'-' * 27}")
gameOver(hero, points)
else:
if enemy.name == "Flimp the Gnome":
points += 5
elif enemy.name == "Flimp+ the Gnome":
points += 10
elif enemy.name == "Driekol the Goblin":
points += 15
elif enemy.name == "Driekol+ the Goblin":
points += 30
elif enemy.name == "Gratus the Minotaurus":
points += 60
elif enemy.name == "Gratus+ the Minotaurus":
points += 120
elif enemy.name == "Gandalf the Wizard": | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
points += 120
elif enemy.name == "Gandalf the Wizard":
points += 240
print(f"You have defeated the enemy: {enemy.name}")
print(f"{'-' * 27}")
lootDrop = loot()
print(f"\n{'-' * 27}")
print(f"You have acquired an item: {lootDrop}")
lootEffect(lootDrop, hero)
print(f"{'-' * 27}")
return points
else:
print("Your sword slips from your hand, you missed the attack!")
print(f"{enemy.name} takes this opportunity and seriously injures you!")
hero.hp = hero.hp - enemy.power
print(f"Health: {hero.hp} hp")
print(f"{'-' * 27}")
gameOver(hero, points)
elif choice == "2":
print(f"\n{'-' * 27}")
runchance = random.randint(1, 10)
if runchance > 4:
print("You have successfully escaped!")
print(f"{'-' * 27}")
sys.exit()
else:
print("You try to run away, but you slip and fall!")
print("You try to defend yourself, but fail, so the enemy wounds you badly!")
hero.hp -= enemy.power
print(f"Health: {hero.hp} hp")
print(f"{'-' * 27}")
else:
print(f"\n{'-' * 27}")
print("The number is not allowed! Please enter only 1 or 2!")
print(f"{'-' * 27}") | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
def boss_battle(points: int) -> int:
enemy = boss()
print("The arch-enemy of the world,", enemy.name, "showed up!")
print("You have two options:")
while enemy.hp > 0:
choice = input("\n [1] - Attack\n [2] - Retreat\n ")
if choice == "1":
print(f"\n{'-' * 27}")
print(f"{hero.name} swung his sword, attacking {enemy.name}-t!")
hitchance = random.randint(0, 10)
if hitchance > 3:
enemy.hp = enemy.hp - hero.power
print(f"You wound the enemy, the enemy's life: {enemy.hp} hp")
if enemy.hp > 1:
hero.hp = round(hero.hp - (enemy.power / hero.armor))
print(f"{enemy.name} is striking back, it has wounded you! Health: {hero.hp} hp")
print(f"{'-' * 27}")
gameOver(hero, points)
else:
if enemy.name == "Leoric the Skeletonking":
points += 480
print(f"You have defeated the enemy: {enemy.name}\n{'-' * 27}")
print(f"\n{'-' * 27}")
gameWin(hero)
return points
else:
print("Your sword slips from your hand, you missed the attack!")
print(f"{enemy.name} takes this opportunity and seriously injures you!")
hero.hp -= enemy.power
print(f"Health: {hero.hp} hp")
print(f"{'-' * 27}")
gameOver(hero, points)
elif choice == "2":
print(f"\n{'-' * 27}")
runchance = random.randint(1, 10)
if runchance > 4:
print("You have successfully escaped!")
print("Everyone is disappointed in you! You have run away from your duty and, therefore, the people continue to fear the terrible reign of Skeleton King Leoric!") | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
print("The world is infested with the Skeleton King and his followers! Leonic is on his way to take over the next world!\n The End!\n")
print(f"{'-' * 27}")
break
else:
print("You try to run away, but you slip and fall!")
print("You try to defend yourself, but fail, so the enemy wounds you badly!")
hero.hp -= enemy.power
print(f"Health: {hero.hp} hp")
print(f"{'-' * 27}")
gameOver(hero, points)
else:
print(f"\n{'-' * 27}")
print("The number is not allowed! Please enter only 1 or 2!")
print(f"{'-' * 27}") | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
def introduction():
print("\t\tWelcome chosen one, Hero Arius!\n\
Fate has chosen you as the hero to free the world from the terrible reign of Skeleton King Leoric!\n\
Get stronger through obstacles, defeat the evil's allies, and fight evil at the very end!\n\
Command: move [direction] (move north, east, west, south)\n")
input("Press ENTER to continue.")
rooms = {
'Start': {'North': 'Terrifying Mine'},
'Terrifying Mine': {'North': 'Tunnel of Hell'},
'Tunnel of Hell': {'East': 'Deceptive Cave'},
'Deceptive Cave': {'East': 'Illusion Cave'},
'Illusion Cave': {'East': 'Unstable Vortex'},
'Unstable Vortex': {'South': 'Imaginary Labyrinth'},
'Imaginary Labyrinth': {'South': 'Garden of the Wizard'},
'Garden of the Wizard': {'South': 'Bone Crusher Castle'},
'Bone Crusher Castle': {'Boss': 'Leoric the Skeletonking'}
}
current_room = "Start"
msg = ""
introduction()
totalpoints = 0
print(f"\n{'=' * 27}\nYou are here now: {current_room}\n{'=' * 27}") | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
introduction()
totalpoints = 0
print(f"\n{'=' * 27}\nYou are here now: {current_room}\n{'=' * 27}")
while True:
user_input = input("Enter your move:\n")
next_move = user_input.split(' ')
action = next_move[0].title()
item = "Item"
direction = "null"
if len(next_move) > 1:
item = next_move[1:]
direction = next_move[1].title()
item = " ".join(item).title()
if action == "Move" or "M":
try:
current_room = rooms[current_room][direction]
msg = f"\n{'=' * 27}\n{hero.name} is heading to {direction}!\n{'=' * 27}"
print(msg)
print(f"\n{'=' * 27}\nYou are here now: {current_room}\n{'=' * 27}")
if "Boss" in rooms[current_room].keys():
totalpoints = boss_battle(totalpoints)
print(totalpoints)
break
else:
totalpoints = battle(totalpoints)
print(totalpoints)
except:
msg = f"\n{'=' * 27}\nYou can't go that way!\n{'=' * 27}"
print(msg)
elif action == "Exit":
break
else:
msg = "Invalid command!"
The code is working. I'm looking for tips in terms of coding styles, readability, and perhaps optimizations if any. | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
Answer: Character Classes
Okay, let's start at the top. You are using classes poorly. You declare a class, create a single instance of that class, and then modify the class variables of that class in that single instance. This works okay for you, because you only ever use one instance of each class, but if you were to ever create (for example) two minotaurus objects, you would discover that subtracting health from one of them would deduct health from both. Which is not desired behavior.
The correct way to make a class like this would be
class Minotaurus:
def __init__(self):
self.name = "Gratus the Minotaurus"
self.hp = 120
self.power = 10
self.armor = 3
self.loot = random.randint(0, 2)
This way the variables are defined when the instance is created and is individual to that instance.
Also, I removed the (object) part - all python classes automatically inherit from object unless otherwise stated.
But this brings up another point - all of the character classes you created are doing the same thing, just with different initial values. This means that they make more sense as instances of a single character class, like so:
class Character:
def __init__(self, name, hp, power, armor, loot=None):
self.name = name
self.hp = hp
self.power = power
self.armor = armor
self.loot = loot
player = Character('Hero Arius', 200, 20, 20)
minotaurus = Character('Gratus the Minotaurus', 120, 10, 3, random.randint(0,2))
#etc
If you want to be fancy, you could use dataclasses to make the class look more like your original class format:
from dataclasses import dataclass
@dataclass
class Character:
""" Characters in the game """
name: str
hp: int
power: int
armor: int
loot: int|None = None | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
But since all your monsters have the same loot, I'd actually do it a little differently
@dataclass
class Character:
""" Characters in the game """
name: str
hp: int
power: int
armor: int
class Monster(Character):
""" Characters that drop loot when defeated """
def __init__(self, *args, **kwargs):
super.__init__(*args, **kwargs)
self.loot = random.randint(0,2)
Note that I'm also including a docstring here. Always include a docstring for your classes and functions. There isn't really much need for one here, because the classes are self-explanatory, but include one anyways.
And of course, with this code the creation of instances would look like this:
hero = Character("Hero Arius", 200, 20, 20)
flimp = Monster("Flimp the Gnome", 10, 1, 3)
stronger_flimp = Monster("Flimp+ the Gnome", 20, 2, 6)
driekol = Monster("Driekol the Goblin", 30, 4, 4)
stronger_driekol= Monster("Driekol+ the Goblin", 60, 8, 8)
gratus = Monster("Gratus the Minotaurus", 120, 10, 3)
stronger_gratus = Monster("Gratus+ the Minotaurus", 240, 20, 6)
gandalf = Monster("Gandalf the Wizard", 480, 40, 2)
boss = Character("Leoric the Skeletonking", 960, 60, 60) | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
This is a lot better, but you're still creating the characters in the global scope, which means that they're still effectively one use. Now again, I know that you're only using them once, but it's still good practice to avoid mutable global variables unless they need to be in the global scope.
What I would do would be to define the stats for each character in a dictionary and the access the dictionary whenever you need to create a character object.
STATS = {
'hero':("Hero Arius", 200, 20, 20),
'flimp':("Flimp the Gnome", 10, 1, 3),
'stronger_flimp':("Flimp+ the Gnome", 20, 2, 6),
'driekol':("Driekol the Goblin", 30, 4, 4),
'stronger_driekol':("Driekol+ the Goblin", 60, 8, 8),
'gratus':("Gratus the Minotaurus", 120, 10, 3),
'stronger_gratus':("Gratus+ the Minotaurus", 240, 20, 6),
'gandalf':("Gandalf the Wizard", 480, 40, 2),
'boss':("Leoric the Skeletonking", 960, 60, 60)
}
and then when you need to create an instance you'd call it like so:
hero = Character(*STATS['hero'])
enemy = Monster(*STATS['flimp']) | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
python, beginner, game
General Formatting and Style
You will notice I capitalized the name of my classes in the previous section. The standard convention for Python (PEP 8) is to use TitleCase for class names, where the first letter is capitalized, instead of camelCase like you used). Variables are lowercase_with_underscores, and constants (like ROOMS) are in ALL_CAPS.
Also, the part of your code that is actually running (starting with current_room = "Start") should be wrapped in if __name__ == '__main__': block. Again it's not strictly relevant for your code since it's entirely in a single file, but it prevents code from running unexpectedly if you have multiple files. It's also a good marker separating the code that defines things from the code that does things.
Miscellaneous
The number of points earned for defeating an enemy is tied to that specific enemy, so rather than including an if/elif block, I'd include points as a variable in the Character class.
@dataclass
class Character:
""" Characters in the game """
name: str
hp: int
power: int
armor: int
points: int = 0
You also assign enemies to rooms using an if/elif block. That could be done with a dictionary
ENEMIES = {"Terrifying Mine":'flimp',
"Tunnel of Hell":'stronger_flimp',
"Deceptive Cave":'driekol',
"Illusion Cave":'stronger_driekol',
"Unstable Vortex":'gratus',
"Imaginary Labyrinth":'stronger_gratus'}
enemy_name = ENEMIES.get(current_room, 'gandalf')
enemy = Monster(*STATS[enemy_name])
I'm not sure why you declared enemy to be global in the battle() function - it doesn't look like it needs to be (and if it doesn't need to be, it definitely shouldn't be). | {
"domain": "codereview.stackexchange",
"id": 44134,
"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, beginner, game",
"url": null
} |
c#, inheritance, composition
Title: Reversing a type converter with minimal redundancies
Question: The objective is to implement the reversed version of StringToDoubleConverter but without writing too many redundancies. I love DRY (Don't Repeat Yourself) design principle.
public class StringToDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return double.TryParse(value as string, out var x) ? x : double.NaN;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is double x ? x.ToString("f3") : string.Empty;
}
}
Here are my approaches. Any suggestions or comments are welcome.
Version A: Inheritance
public class DoubleToStringConverter : StringToDoubleConverter, IValueConverter
{
public new object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return base.ConvertBack(value, targetType, parameter, culture);
}
public new object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return base.Convert(value, targetType, parameter, culture);
}
}
Version B: Composition
public class DoubleToStringConverter : IValueConverter
{
private static readonly StringToDoubleConverter std = new();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return std.ConvertBack(value, targetType, parameter, culture);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return std.Convert(value, targetType, parameter, culture);
}
}
Answer: Why don't you define an abstract class with the following two methods:
One which can convert an object to string
Another which can convert an object to double | {
"domain": "codereview.stackexchange",
"id": 44135,
"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#, inheritance, composition",
"url": null
} |
c#, inheritance, composition
One which can convert an object to string
Another which can convert an object to double
public abstract class FromObjectConverter
{
protected double ToDouble(object value)
=> double.TryParse(value as string, out var x) ? x : double.NaN;
protected string ToString(object value)
=> value is double x ? x.ToString("f3") : string.Empty;
}
With this class in our hand the two concrete converter classes are just simple wrappers
public sealed class StringToDoubleConverter : FromObjectConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> ToDouble(value);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> ToString(value);
}
public sealed class DoubleToStringConverter : FromObjectConverter, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
=> ToString(value);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
=> ToDouble(value);
}
Or if you want to avoid inheritance then define the FromObjectConverter class and its methods as static. | {
"domain": "codereview.stackexchange",
"id": 44135,
"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#, inheritance, composition",
"url": null
} |
python, hash-map
Title: Write a function that takes a list of dicts and combine them
Question: There is an exercise in the book Python Workout: 50 Ten-minute Exercises that asks to write a function to do the following:
Write a function that takes a list of dicts and returns a single dict that combines
all of the keys and values. If a key appears in more than one argument, the
value should be a list containing all of the values from the arguments.
Here is my code:
def combine_dicts(dict_list):
combined = {}
for dict_ in dict_list:
for key, value in dict_.items():
if key not in combined.keys():
combined[key] = [value]
else:
combined[key] = combined[key] + [value]
return dict([((key, value[0]) if len(value) == 1 else (key, value)) \
for key, value in combined.items()])
what are some ideas that I can use to improve my code, make it more pythonic?
Example input and outputs:
>>> combine_dicts([{'a': [1, 2]}, {'a':[3]}, {'a': [4, 5]}])
{'a': [[1, 2], [3], [4, 5]]}
>>> combine_dicts([{'a': 1, 'b':2}, {'c':2, 'a':3}])
{'a': [1, 3], 'b': 2, 'c': 2}
Answer: At first glance your code looks pretty pythonic to me. I would suggest the following changes:
when you are adding a new value to an existing key's list, you use list concatenation to create a new list: combined[key] = combined[key] + [value]. What you should do instead is append the new value to the existing list: combined[key].append(value)
in the return statement you create a list of tuples using list comprehension which is then converted to a dictionary. Instead you can directly use a dictionary comprehension to create the dictionary more elegantly: return {key : (value[0] if len(value) == 1 else value) for key, value in combined.items()} | {
"domain": "codereview.stackexchange",
"id": 44136,
"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, hash-map",
"url": null
} |
python, hash-map
The resulting code looks as follows:
def combine_dicts(dict_list):
combined = {}
for dict_ in dict_list:
for key, value in dict_.items():
if key not in combined.keys():
combined[key] = [value]
else:
combined[key].append(value)
return {
key : (value[0] if len(value) == 1 else value)
for key, value in combined.items()
} | {
"domain": "codereview.stackexchange",
"id": 44136,
"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, hash-map",
"url": null
} |
java
Title: Refactoring count Lines of Java code
Question: My task is:
In this challenge, write a function CountLOC.count to count the lines
of code in a Java source file. A line of code is defined as any line
in the source which contains at least one character of executable
code. This excludes comments and whitespace. All input will be valid
Java code in string format.
CountLOC.count(text) Parameters text: String - A stringified valid
Java source file
Return Value int - A count of the number of lines of executable code
in the source file
I need help to refactor the logic for the program as:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CountLOC {
public static void main(String[] args) {
// write your code here
System.out.println("Hello world");
}
public static int count(String text) {
boolean currentlyInComment = false;
int lines = 0;
try (BufferedReader reader = new BufferedReader(new FileReader(text))) {
while (reader.readLine() != null) lines++;
text = text.replace(" ", "");
String line = reader.readLine();
if (line.trim().startsWith("/*")) {
currentlyInComment = true;
}
if (!currentlyInComment && !line.trim().startsWith("//")) {
// Do your algorithmic stuff with line
System.out.println(line);
}
if (line.trim().startsWith("*/") && currentlyInComment) {
currentlyInComment = false;
}
if (line.trim().startsWith("/**") && currentlyInComment) {
currentlyInComment = false;
}
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
} | {
"domain": "codereview.stackexchange",
"id": 44137,
"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",
"url": null
} |
java
Specifically for passing tests below:
import java.io.*;
import java.nio.file.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class ExampleTest {
@Test
public void shouldHandleBasicCode() throws IOException {
String path = "./java_src_files/Example1.java";
String code = new String(Files.readAllBytes(Paths.get(path)));
assertEquals(5, CountLOC.count(code));
}
@Test
public void shouldHandleABlankLineWIthOneLineComment() throws IOException {
String path = "./java_src_files/Example2.java";
String code = new String(Files.readAllBytes(Paths.get(path)));
assertEquals(5, CountLOC.count(code));
}
@Test
public void shouldHandleAnInlineComment() throws IOException {
String path = "./java_src_files/Example3.java";
String code = new String(Files.readAllBytes(Paths.get(path)));
assertEquals(5, CountLOC.count(code));
}
@Test
public void shouldHandleMultilineCommentsAndQuotes() throws IOException {
String path = "./java_src_files/Example4.java";
String code = new String(Files.readAllBytes(Paths.get(path)));
assertEquals(5, CountLOC.count(code));
}
@Test
public void shouldHandleAComplexExample() throws IOException {
String path = "./java_src_files/Example5.java";
String code = new String(Files.readAllBytes(Paths.get(path)));
assertEquals(6, CountLOC.count(code));
}
}
I've tried to combine several snippets of the code based on:
https://mkyong.com/java/how-to-get-the-total-number-of-lines-of-a-file-in-java/
https://stackoverflow.com/a/47243579/8370915
https://stackoverflow.com/a/64959634/8370915
But I need to improve it if it possible.
Can someone help me with it, please?
Thank you a lot in advance.
UPD #1:
import java.io.*;
public class CountLOC {
public static void main(String[] args) {
// write your code here
System.out.println("Hello world");
} | {
"domain": "codereview.stackexchange",
"id": 44137,
"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",
"url": null
} |
java
public static int count(String text) {
int codeLineCount = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(text));
String line = reader.readLine();
while (line != null) {
if (!isCommentLine(line)) {
codeLineCount++;
}
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
return codeLineCount;
}
public static boolean isCommentLine(String line) {
line = line.trim();
return line.isEmpty() || line.startsWith("//") || line.startsWith("/*")
|| line.startsWith("*") || line.startsWith("*/");
}
}
I'm trying to understand how to split the input at the newLine character to get the individual lines and rewrite code to use a string and a loop instead of a reader.
UPD #2:
public class CountLOC {
public static int count(String text) {
String[] lines = text.split(System.lineSeparator());
return Arrays.stream(lines).filter(CountLOC::isCode).count();
}
public static boolean isCode(String line) {
line = line.trim();
return !line.isEmpty() && !line.startsWith("//") && !line.startsWith("/*")
&& !line.startsWith("*") && !line.startsWith("*/");
}
}
Answer: Prefer try-with-resources
You switched from
try (BufferedReader reader = new BufferedReader(new FileReader(text))) {
to
try {
BufferedReader reader = new BufferedReader(new FileReader(text));
This seems like a mistake. The try-with-resources (first form) is superior. It ensures that the BufferedReader gets closed properly regardless of whether there is an exception or not. The second form doesn't close it at all, so you're guaranteed it won't get closed until the method ends and garbage collection runs. Still consistent, but consistently wrong.
Comments are hard | {
"domain": "codereview.stackexchange",
"id": 44137,
"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",
"url": null
} |
java
return line.isEmpty() || line.startsWith("//") || line.startsWith("/*")
|| line.startsWith("*") || line.startsWith("*/");
This is incorrect. Consider the following input
int product = 5
* 3;
or
/*
This is a comment.
*/
The first should be two lines of code (by the definition in the problem). The second should be zero lines of code. But you'd count both as one line of code. Or
/* Comment followed by code */ int product = 5 * 3;
That should be one line of code, but you'd count it as zero lines of code.
If you allow /* */ style comments, then you have to do a lot more parsing and maintain state across lines. Because such comments can appear on lines with executable code or prevent execution of what otherwise would be executable code. You need something like
if (commentOpenFromPreviousLine) {
int location = line.indexOf("*/");
if (location >= 0) {
line = line.substring(location + "*/".length());
commentOpenFromPreviousLine = false;
}
}
Note that this is an incomplete solution. For example, it never sets commentOpenFromPreviousLine to true.
Another test case to handle:
String s = """
/* This is a string, not a comment */
""";
That should count as three lines of code.
Also
int product = 5 * 3; /*
This is a comment
*/
One line of code.
int product /* Comment */ = 5 * 3;
One line of code.
int product /* Comment */ = 5 * 3; /*
Comment
*/ int sum = 5 + 3;
Two lines of code.
Note: please don't use comments like this in real programs. They're horrible. But they're syntactically allowed. | {
"domain": "codereview.stackexchange",
"id": 44137,
"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",
"url": null
} |
python
Title: Automate the Boring Stuff Chapter 13 - Text Files to Spreadsheet
Question: The project outline:
Write a program to read in the contents of several text files (you can
make the text files yourself) and insert those contents into a
spreadsheet, with one line of text per row. The lines of the first
text file will be in the cells of column A, the lines of the second
text file will be in the cells of column B, and so on.
Use the readlines() File object method to return a list of strings,
one string per line in the file. For the first file, output the first
line to column 1, row 1. The second line should be written to column
1, row 2, and so on. The next file that is read with readlines() will
be written to column 2, the next file to column 3, and so on.
My solution:
# A program to read text files and write it to an Excel file with one line per row
# Usage: python text_to_spreadsheet.py "folder to search for text files" "save location for spreadsheet"
import sys, openpyxl
from pathlib import Path
def main(search_folder, save_path):
workbook = openpyxl.Workbook()
sheet = workbook.active
for column_index, filename in enumerate(search_folder.glob("*.txt")):
with open(filename, "r", encoding="utf-8") as text_file:
for row_index, line in enumerate(text_file.readlines()):
sheet.cell(row=row_index + 1, column=column_index + 1).value = line.strip()
workbook.save(save_path)
if __name__ == "__main__":
search_folder = Path(sys.argv[1]) # the folder with text files to search
save_path = Path(sys.argv[2]) # the path of the new spreadsheet (must end in .xlsx)
main(search_folder, save_path)
Answer: You have not stated any review goals so I will share my thoughts and ideas about your code:
General
Overall your code looks clean, follows pythonic style and is readable. You are using descriptive variable names and the structure is easy to follow.
Formatting / PEP8
There are two minor PEP8 violations I spotted: | {
"domain": "codereview.stackexchange",
"id": 44138,
"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",
"url": null
} |
python
Imports should be on separate lines, i.e. sys and openpyxl should be imported using separate import statements
There should be two blank lines before and after a top level function definition
Using Argparse
I like the comments describing the command line arguments and the usage of the program. This is also the area in which I think you could improve it the most, because with very little effort you could turn these comments into argparse help texts. This does not negatively impact the readability of the program (in my opinion) but helps the user of the program.
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser(
description="A program to read text files and write it to an Excel file with one line per row"
)
parser.add_argument(
"search_folder",
help="the folder with text files to search",
)
parser.add_argument(
"save_path",
help="the path of the new spreadsheet (must end in .xlsx)",
)
args = parser.parse_args()
main(Path(args.search_folder), Path(args.save_path))
When the new code is called with the --help flag it outputs the folloing message:
usage: test.py [-h] search_folder save_path
A program to read text files and write it to an Excel file with one line per row
positional arguments:
search_folder the folder with text files to search
save_path the path of the new spreadsheet (must end in .xlsx)
options:
-h, --help show this help message and exit
Additionally a usefull error message is generated if not enough or too many arguments are provided. | {
"domain": "codereview.stackexchange",
"id": 44138,
"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",
"url": null
} |
java, array
Title: Robust input for lottery tickets
Question: I've made a method that provides a robust way for a user to fill out a lottery ticket. During this process I found out that Java also provides syntax for labels. That was very astounding for me. But I also was told that using goto-like code can be a bad smell. But I've not found a way to make my code "more beautiful".
What do you think? Is it tolerable to use a label to solve this problem? Are there other aspects that have to be improved?
The following things are checked:
Is the entered number really a valid number?
Is the number in a valid range?
Was this number already entered?
Main.java
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class Main {
private static final int DRAW_SIZE = 6;
private static final int LOWER_RANGE = 1;
private static final int UPPER_RANGE = 49;
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int numbers[] = saveIntArrayFromUserInput();
System.out.println(Arrays.toString(numbers));
}
// lets the user create an int array
// assures that all values are unique numbers between lower and upper range
private static int[] saveIntArrayFromUserInput() {
List<Integer> numbers = new ArrayList<>();
main_loop:
while (numbers.size() < DRAW_SIZE) {
int number = 0;
System.out.print("Enter a number: ");
String input = scanner.nextLine();
// check if input is a number
try {
number = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Enter a valid number.");
continue;
} | {
"domain": "codereview.stackexchange",
"id": 44139,
"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, array",
"url": null
} |
java, array
// check if input is in range
if (number > UPPER_RANGE || number < LOWER_RANGE) {
System.out.println("Your number isn't between " + LOWER_RANGE + " and "
+ UPPER_RANGE);
continue;
}
// check if input is unique
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) == number) {
System.out.println("You've entered this number already.");
continue main_loop;
}
}
numbers.add(number);
}
int[] numbersArray = new int[numbers.size()];
for (int i = 0; i < numbers.size(); i++) numbersArray[i] = numbers.get(i);
Arrays.sort(numbersArray);
return numbersArray;
}
}
Example Output
Enter a number: 6
Enter a number: 6
You've entered this number already.
Enter a number: 600
Your number isn't between 1 and 49
Enter a number: bla
Enter a valid number.
Enter a number: 5
Enter a number: 4
Enter a number: 3
Enter a number: 3
You've entered this number already.
Enter a number: 2
Enter a number: 1
[1, 2, 3, 4, 5, 6]
Answer: In most lotteries, order doesn't matter, so consider using a Set instead of an array of numbers.
That means that your check for already present becomes a simple method call, so no need to break out of two levels of loops.
Java's continue LABEL and break LABEL aren't as dangerous as C's goto, (they are constrained to work with structured programming, and object cleanup is performed when leaving scope, as normal) but I still recommend that they should be used sparingly, due to the cognitive load imposed. | {
"domain": "codereview.stackexchange",
"id": 44139,
"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, array",
"url": null
} |
python, beginner, python-3.x, selenium
Title: To automate scheduling at the Italian Consulate
Question: I'm a beginner developer in Python and I need some tips to improve my code, in performance (speed) and hardware usage. Is it possible to improve?
And I have a question: is it possible to keep the browser (chrome/chromedriver) open after execution?
The objective: to automate scheduling at the Italian Consulate, through the website prenot@mi.
Booking on the Prenot@mi system is "simple", but it's very busy, so I have to be quicker than others to get a reservation. Within seconds, a booking is "lost" as another scheduler was able to book faster.
Dates are available on Mondays and Wednesdays at 11:00 am.
My repository: https://github.com/skynorreply/prenot-mi_script
import datetime
import time
import os
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.alert import Alert
def esta_na_hora(hora, minuto, segundos, data_atual):
if data_atual.hour == hora and data_atual.minute == minuto and data_atual.second == segundos:
return True
return False
def processa_dias_da_semana(dias_da_semana):
dias_da_semana_int = []
for dia in dias_da_semana:
if dia == "seg":
dias_da_semana_int.append(0)
if dia == "ter":
dias_da_semana_int.append(1)
if dia == "qua":
dias_da_semana_int.append(2)
if dia == "qui":
dias_da_semana_int.append(3)
if dia == "sex":
dias_da_semana_int.append(4)
if dia == "sab":
dias_da_semana_int.append(5)
if dia == "dom":
dias_da_semana_int.append(6)
return dias_da_semana_int
def esta_no_dia_da_semana(dias_da_semana, data_atual):
if data_atual.weekday() in dias_da_semana:
return True | {
"domain": "codereview.stackexchange",
"id": 44140,
"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, beginner, python-3.x, selenium",
"url": null
} |
python, beginner, python-3.x, selenium
return False
hora_string = input("Que horas quer agendar? (hh:mm:sg): ")
dia_da_semana_string = input(
"Quais dias da semana? (seg ter qua qui sex sab dom): ")
hora = int(hora_string.split(':')[0])
minuto = int(hora_string.split(':')[1])
segundos = int(hora_string.split(':')[2]) | {
"domain": "codereview.stackexchange",
"id": 44140,
"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, beginner, python-3.x, selenium",
"url": null
} |
python, beginner, python-3.x, selenium
dias_da_semana = dia_da_semana_string.split(' ')
dias_da_semana_int = processa_dias_da_semana(dias_da_semana)
ativo = True
while ativo:
agora = datetime.datetime.now()
print(agora)
if esta_na_hora(hora, minuto, segundos, agora) and esta_no_dia_da_semana(dias_da_semana_int, agora):
ativo = False
chrome_options = webdriver.ChromeOptions() #here begins to configure chrome not to load the images
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_experimental_option("prefs", prefs)
navegador = webdriver.Chrome(chrome_options=chrome_options) #here finish configuring chrome to not load the images
navegador.get("https://prenotami.esteri.it") #access the site
time.sleep(3) #to wait the loading, only by safety
navegador.find_element(
By.ID, "login-email").send_keys("email@email.com") #REMEMBER TO PUT THE EMAIL
navegador.find_element(
By.ID, "login-password").send_keys("password") #REMEMBER TO PUT THE PASSWORD
navegador.find_element(
By.XPATH, '//*[@id="login-form"]/button').click() #will click on the button to login
time.sleep(3) #this time is important!!! You run the risk of failing.
navegador.find_element(By.ID, "advanced").click() #click on the book section
time.sleep(2)
navegador.find_element(
By.XPATH, '//*[@id="dataTableServices"]/tbody/tr[2]/td[4]/a/button').click() #here the system will click on the option Reserve Citizenship
time.sleep(2)
i = 1
while navegador.find_element(By.XPATH, '/html/body/div[2]/div[2]/div/div/div/div/div/div/div/div[4]/button') == navegador.find_element(By.XPATH, '/html/body/div[2]/div[2]/div/div/div/div/div/div/div/div[4]/button'):
print("Tentativa Nº - " + str(i))
navegador.find_element(
By.XPATH, '/html/body/div[2]/div[2]/div/div/div/div/div/div/div/div[4]/button').click() | {
"domain": "codereview.stackexchange",
"id": 44140,
"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, beginner, python-3.x, selenium",
"url": null
} |
python, beginner, python-3.x, selenium
delay = 10 #seconds
try:
elemento = WebDriverWait(navegador, delay).until(EC.presence_of_element_located(
(By.XPATH, '//*[@id="dataTableServices"]/tbody/tr[2]/td[4]/a/button')))
elemento.click()
except TimeoutException:
print("elemento nao encontrado")
i = i + 1
time.sleep(1)
navegador.find_element(By.ID, 'File_0').send_keys(os.path.abspath("/Users/compCOPEL.pdf")) #proof of address
navegador.find_element(By.ID, 'PrivacyCheck').click() #accept the privacy term
navegador.find_element(By.ID, 'btnAvanti').click() #forward button to calendar view
alert = Alert(navegador) #here is to identify the window that opens to confirm the appointment
alert.accept() #here will accept confirmation window | {
"domain": "codereview.stackexchange",
"id": 44140,
"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, beginner, python-3.x, selenium",
"url": null
} |
python, beginner, python-3.x, selenium
Thank you in advance!
Answer: I know nothing about selenium, so I'm going to focus on general streamlining tips. And some of my tips can probably be supplanted by good use of the datetime module that Felix Ogg recommended, but I'll leave those for you to discover.
The expression
if <condition>:
return True
return False
Can be shortened to
return <condition>
This works in both esta_na_hora() and esta_no_dia_da_semana().
processa_dias_da_semana() is very wasteful. If dia == 'seg', then it will not fulfill any of the other conditions, yet the program checks them anyways. The subsequent checks should use elif instead of if, like so:
if dia == "seg":
dias_da_semana_int.append(0)
elif dia == "ter":
dias_da_semana_int.append(1)
elif dia == "qua":
dias_da_semana_int.append(2)
elif dia == "qui":
dias_da_semana_int.append(3)
elif dia == "sex":
dias_da_semana_int.append(4)
elif dia == "sab":
dias_da_semana_int.append(5)
elif dia == "dom":
dias_da_semana_int.append(6)
However, you may notice that this is rather repetitive. We can do better still. In Python, an if/elif block where the conditions are all checking the equivalence of a single variable to a series of constants and then assigning a single value as a result can be shortened using a dictionary, like so:
WEEK = {'seg':0, 'ter':1, 'qua':2, 'qui':3, 'sex':4, 'sab':5, 'dom':6}
for dia in dias_da_semana:
dias_da_semana_int.append(WEEK[dia])
Because the values being assigned are integers from 0 to n, we can also write this using a list:
WEEK = ['seg', 'ter', 'qua', 'qui', 'sex', 'sab', 'dom']
for dia in dias_da_semana:
dias_da_semana_int.append(WEEK.index(dia)) | {
"domain": "codereview.stackexchange",
"id": 44140,
"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, beginner, python-3.x, selenium",
"url": null
} |
python, beginner, python-3.x, selenium
This is technically less efficient (O(n) time complexity to access a list vs O(1) to access a dict), but for a seven item list the difference is negligible.
Notably, neither of these solutions have the same behavior as your original if dia is not one of the listed possibilities. In your code, the unknown value would be silently ignored, resulting in a final dias_da_semana_int which is shorter than dias_da_semana with no indication as to which values were skipped. My code will instead throw an KeyError or an ValueError depending on which version you chose. Use try/except if you prefer the original behavior, or if you're using a dict you can use WEEK.get(dia, None) to use None (or whatever value you choose) as a default value.
Speaking of which, you make no allowances for different ways the user might enter their text. Your code accepts "seg", but will break on "Seg" or "seg,". It's probably not worth your time to do heavy input normalization if you're going to be the primary user, but you should at least normalize your strings with dia_da_semana_string.lower() to remove capitalization. It's easy to add and eliminates the most common source of input variability.
Finally, your for loop can be replaced by list comprehension. In total, here's a shorter version of processa_dias_da_semana():
WEEK = {'seg':0, 'ter':1, 'qua':2, 'qui':3, 'sex':4, 'sab':5, 'dom':6}
def processa_dias_da_semana(dias_da_semana):
return [WEEK[dia] for dia in dias_da_semana]
You can also use list comprehensions to efficiently split hora_string
hora, minuto, segundos = [int(ss) for ss in hora_string.split(':')]
Instead of:
ativo = True
while ativo:
if <condition>:
ativo = False
# do stuff
It is cleaner to write this as:
while True:
if <condition>:
# do stuff
break
You can replace i = i+1 with i += 1 | {
"domain": "codereview.stackexchange",
"id": 44140,
"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, beginner, python-3.x, selenium",
"url": null
} |
python, beginner
Title: Read 10 integers from user input and print the largest odd number entered
Question: I implemented the finger exercise from chapter 2.4 of the book called Intro to Computation Programming using Python by John Guttag.
The task is:
Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.
Is the code without any holes? How can I avoid repeating the same line 10 times?
a = int(input('Enter the number: '))
b = int(input('Enter the number: '))
c = int(input('Enter the number: '))
d = int(input('Enter the number: '))
e = int(input('Enter the number: '))
f = int(input('Enter the number: '))
g = int(input('Enter the number: '))
h = int(input('Enter the number: '))
i = int(input('Enter the number: '))
j = int(input('Enter the number: '))
A = [a,b,c,d,e,f,g,h,i,j]
A.sort()
while True:
if A[len(A)-2]<A[len(A)-1]:
if A[len(A)-1]%2==1:
break
A[len(A)-2]=A[(len(A)-2)-1]
A[len(A)-1]=A[(len(A)-1)-1]
print(A[len(A)-1],'is the largest odd')
Answer: If you find yourself typing the same line over and over, that's a good indicator that a loop might be a good idea.
A = []
while len(A) < 10:
A.append(int(input("Enter a number: ")))
I'm going to stop here to ask an important question: why are we storing all of the entered numbers? The problem asks only for the largest odd number, so we can ignore all other numbers. Storing every number that was entered only complicates the code.
biggest_odd = None # The value None represents no odd number has been entered yet.
for _ in range(10): # The name _ indicates we are not going to use this variable.
n = int(input("Enter a number: "))
if n % 2 == 1 and (biggest_odd is None or n > biggest_odd):
biggest_odd = n
print(biggest_odd, "is the biggest odd.") | {
"domain": "codereview.stackexchange",
"id": 44141,
"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, beginner",
"url": null
} |
python, beginner
One final comment on your original code. I don't really understand what your while True: loop is doing, but if the last number entered is even then it loops forever. It only looks at or modifies the last three numbers entered. | {
"domain": "codereview.stackexchange",
"id": 44141,
"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, beginner",
"url": null
} |
c++, c++11, vectors
Title: Growable vector on the stack with fixed capacity
Question:
Implements most (if not all) applicable member functions from std::vector and std::array
Compatible with C++11, C++14, C++17, C++20
[] operator allows unchecked access, all other member functions throw
#ifndef STAT_VEC_H
#define STAT_VEC_H
#include <memory>
#include <cstddef>
#include <cstring>
#include <iterator>
#include <stdexcept>
#include <type_traits>
// A growable, stack based vector
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || __cplusplus >= 201703L)
#define STAT_VEC_HAS_CXX17 1
#endif
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) || __cplusplus >= 202002L)
#define STAT_VEC_HAS_CXX20 1
#endif
#ifdef STAT_VEC_HAS_CXX20
#define STAT_VEC_CONSTEXPR_CXX20 constexpr
#else
#define STAT_VEC_CONSTEXPR_CXX20 inline
#endif
#ifdef STAT_VEC_HAS_CXX17
#define STAT_VEC_NODISCARD [[nodiscard]]
#define STAT_VEC_BYTE_T std::byte
#else
#define STAT_VEC_NODISCARD
#define STAT_VEC_BYTE_T unsigned char
#endif
template <typename StaticVectorT>
class static_vec_const_iter {
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = typename StaticVectorT::value_type;
using difference_type = ptrdiff_t;
using pointer = const value_type*;
using reference = const value_type&;
private:
using arr_pointer = const StaticVectorT*;
arr_pointer m_arr;
size_t m_idx;
void check_compat(const static_vec_const_iter& other) const
{
if (m_arr != other.m_arr) {
throw std::logic_error("Non-compatible iterators");
}
}
template <typename T, size_t Capacity>
friend class static_vec;
public:
STAT_VEC_CONSTEXPR_CXX20 explicit static_vec_const_iter(arr_pointer arr, size_t idx) noexcept : m_arr{ arr }, m_idx{ idx } {}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 reference operator*() const
{
return *operator->();
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 pointer operator->() const
{
if (m_idx >= m_arr->size()) {
throw std::out_of_range("Cannot dereference out of range iterator");
}
return m_arr->data() + m_idx;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter& operator++()
{
if (m_idx >= m_arr->size()) {
throw std::out_of_range("Cannot increment iterator past end");
}
++m_idx;
return *this;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter operator++(int)
{
static_vec_const_iter ret = *this;
++* this;
return ret;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter& operator--()
{
if (m_idx == 0) {
throw std::out_of_range("Cannot decrement iterator before end");
}
--m_idx;
return *this;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter operator--(int)
{
static_vec_const_iter ret = *this;
--* this;
return ret;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter& operator+=(const ptrdiff_t offset)
{
if (offset < 0 && size_t{ ptrdiff_t{0} - offset } > m_idx) {
throw std::out_of_range("Cannot decrement iterator before end");
}
if (offset > 0 && static_cast<size_t>(offset) > m_arr->size() - m_idx) {
throw std::out_of_range("Cannot increment iterator past end");
}
m_idx += static_cast<size_t>(offset);
return *this;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter operator+(const ptrdiff_t offset)
{
static_vec_const_iter ret = *this;
return ret += offset;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter& operator-=(const ptrdiff_t offset)
{
return *this += -offset;
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 static_vec_const_iter operator-(const ptrdiff_t offset)
{
static_vec_const_iter ret = *this;
return ret -= offset;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 ptrdiff_t operator-(const static_vec_const_iter& other) const
{
check_compat(other);
return static_cast<ptrdiff_t>(m_idx - other.m_idx);
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 reference operator[](const ptrdiff_t offset) const
{
return *(*this + offset);
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator==(const static_vec_const_iter& other) const
{
check_compat(other);
return m_idx = other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator!=(const static_vec_const_iter& other) const
{
check_compat(other);
return m_idx != other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator<(const static_vec_const_iter& other) const
{
check_compat(other);
return m_idx < other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator>(const static_vec_const_iter& other) const
{
check_compat(other);
return m_idx < other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator<=(const static_vec_const_iter& other) const
{
check_compat(other);
return m_idx <= other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator>=(const static_vec_const_iter& other) const
{
check_compat(other);
return m_idx >= other.m_idx;
}
};
template <typename StaticVectorT>
class static_vec_iter {
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = typename StaticVectorT::value_type;
using difference_type = ptrdiff_t;
using pointer = value_type*;
using reference = value_type&;
private:
using arr_pointer = StaticVectorT*; | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
private:
using arr_pointer = StaticVectorT*;
arr_pointer m_arr;
size_t m_idx;
void check_compat(const static_vec_iter& other) const
{
if (m_arr != other.m_arr) {
throw std::logic_error("Non-compatible iterators");
}
}
template <typename T, size_t Capacity>
friend class static_vec;
public:
STAT_VEC_CONSTEXPR_CXX20 explicit static_vec_iter(arr_pointer arr, size_t idx) noexcept : m_arr{ arr }, m_idx{ idx } {}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 reference operator*() const
{
return *operator->();
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 pointer operator->() const
{
if (m_idx >= m_arr->size()) {
throw std::out_of_range("Cannot dereference out of range iterator");
}
return m_arr->data() + m_idx;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_iter& operator++()
{
if (m_idx >= m_arr->size()) {
throw std::out_of_range("Cannot increment iterator past end");
}
++m_idx;
return *this;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_iter operator++(int)
{
static_vec_iter ret = *this;
++* this;
return ret;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_iter& operator--()
{
if (m_idx == 0) {
throw std::out_of_range("Cannot decrement iterator before end");
}
--m_idx;
return *this;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_iter operator--(int)
{
static_vec_iter ret = *this;
--* this;
return ret;
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_CONSTEXPR_CXX20 static_vec_iter& operator+=(const ptrdiff_t offset)
{
if (offset < 0 && size_t{ ptrdiff_t{0} - offset } > m_idx) {
throw std::out_of_range("Cannot decrement iterator before end");
}
if (offset > 0 && static_cast<size_t>(offset) > m_arr->size() - m_idx) {
throw std::out_of_range("Cannot increment iterator past end");
}
m_idx += static_cast<size_t>(offset);
return *this;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 static_vec_iter operator+(const ptrdiff_t offset)
{
static_vec_iter ret = *this;
return ret += offset;
}
STAT_VEC_CONSTEXPR_CXX20 static_vec_iter& operator-=(const ptrdiff_t offset)
{
return *this += -offset;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 static_vec_iter operator-(const ptrdiff_t offset)
{
static_vec_iter ret = *this;
return ret -= offset;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 ptrdiff_t operator-(const static_vec_iter& other) const
{
check_compat(other);
return static_cast<ptrdiff_t>(m_idx - other.m_idx);
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 reference operator[](const ptrdiff_t offset) const
{
return *(*this + offset);
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator==(const static_vec_iter& other) const
{
check_compat(other);
return m_idx == other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator!=(const static_vec_iter& other) const
{
check_compat(other);
return m_idx != other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator<(const static_vec_iter& other) const
{
check_compat(other);
return m_idx < other.m_idx;
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator>(const static_vec_iter& other) const
{
check_compat(other);
return m_idx < other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator<=(const static_vec_iter& other) const
{
check_compat(other);
return m_idx <= other.m_idx;
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool operator>=(const static_vec_iter& other) const
{
check_compat(other);
return m_idx >= other.m_idx;
}
operator static_vec_const_iter<StaticVectorT>() const
{
return static_vec_const_iter<StaticVectorT>(m_arr, m_idx);
}
};
template <typename T, size_t Capacity>
class static_vec {
public:
using value_type = T;
using pointer = T*;
using const_pointer = const T*;
using reference = T&;
using const_reference = const T&;
using size_type = size_t;
using difference_type = ptrdiff_t;
using iterator = static_vec_iter<static_vec>;
using const_iterator = static_vec_const_iter<static_vec>;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
private:
size_type m_size;
alignas(T) STAT_VEC_BYTE_T m_data[sizeof(T) * Capacity];
inline void check_not_full()
{
if (m_size >= Capacity) {
throw std::out_of_range("Buffer is full");
}
}
inline void check_not_empty()
{
if (m_size == 0) {
throw std::out_of_range("Buffer is empty");
}
}
inline void check_in_bounds(size_type idx)
{
if (idx >= m_size) {
throw std::out_of_range("Out of bounds");
}
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
inline void check_insert(size_type idx, size_type count)
{
if ((m_size + count) > Capacity) {
throw std::out_of_range("Not enough room in buffer");
}
if (idx > m_size) {
throw std::out_of_range("Out of bounds");
}
}
inline void check_erase(size_type idx, size_type count)
{
if (m_size == 0) {
throw std::out_of_range("Buffer is empty");
}
if (idx + count > m_size) {
throw std::out_of_range("Out of bounds");
}
}
template <class iterT>
inline void check_iters(iterT first, iterT last)
{
if (std::distance(first, last) < 0) {
throw std::out_of_range("Last iterator at or after first iterator");
}
}
inline pointer unchecked_ptr_at(size_type idx)
{
return reinterpret_cast<T*>(&m_data[idx * sizeof(T)]);
}
inline const_pointer unchecked_ptr_at(size_type idx) const
{
return reinterpret_cast<const T*>(&m_data[idx * sizeof(T)]);
}
inline reference unchecked_at(size_type idx)
{
return *unchecked_ptr_at(idx);
}
inline const_reference unchecked_at(size_type idx) const
{
return *unchecked_ptr_at(idx);
}
template <class... U>
using void_t = void;
template <class U, class = void>
struct is_input_iterator : std::false_type {
}; | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
template <class U, class = void>
struct is_input_iterator : std::false_type {
};
template <class U>
struct is_input_iterator<U, static_vec::void_t<
typename std::iterator_traits<U>::iterator_category,
typename std::iterator_traits<U>::value_type,
typename std::iterator_traits<U>::reference,
typename std::iterator_traits<U>::difference_type,
decltype(++std::declval<U&>()), // prefix incrementable,
decltype(std::declval<U&>()++), // postfix incrementable,
decltype(*std::declval<U&>()), // dereferencable via *,
decltype(std::declval<U&>().operator->()), // dereferencable via ->,
decltype(std::declval<U&>() == std::declval<U&>()) // comparable
> > : std::true_type {
};
template <class U>
using is_input_iterator_t = typename is_input_iterator<U>::type;
public:
static_vec()
: m_size{ 0 }
, m_data{}
{
}
~static_vec()
{
clear();
}
STAT_VEC_CONSTEXPR_CXX20 reference at(size_type idx)
{
check_in_bounds(idx);
return unchecked_at(idx);
}
STAT_VEC_CONSTEXPR_CXX20 const_reference at(size_type idx) const
{
check_in_bounds(idx);
return unchecked_at(idx);
}
STAT_VEC_CONSTEXPR_CXX20 reference operator[](size_type idx)
{
return unchecked_at(idx);
}
STAT_VEC_CONSTEXPR_CXX20 const_reference operator[](size_type idx) const
{
return unchecked_at(idx);
}
STAT_VEC_CONSTEXPR_CXX20 reference front()
{
check_not_empty();
return unchecked_at(0);
}
STAT_VEC_CONSTEXPR_CXX20 const_reference front() const
{
check_not_empty();
return unchecked_at(0);
}
STAT_VEC_CONSTEXPR_CXX20 reference back()
{
check_not_empty();
return unchecked_at(m_size - 1);
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_CONSTEXPR_CXX20 const_reference back() const
{
check_not_empty();
return unchecked_at(m_size - 1);
}
STAT_VEC_CONSTEXPR_CXX20 pointer data() noexcept
{
return reinterpret_cast<T*>(m_data);
}
STAT_VEC_CONSTEXPR_CXX20 const_pointer data() const noexcept
{
return reinterpret_cast<const T*>(m_data);
}
STAT_VEC_CONSTEXPR_CXX20 iterator begin() noexcept
{
return iterator(this, 0);
}
STAT_VEC_CONSTEXPR_CXX20 const_iterator begin() const noexcept
{
return const_iterator(this, 0);
}
STAT_VEC_CONSTEXPR_CXX20 const_iterator cbegin() const noexcept
{
return const_iterator(this, 0);
}
STAT_VEC_CONSTEXPR_CXX20 iterator end() noexcept
{
return iterator(this, m_size);
}
STAT_VEC_CONSTEXPR_CXX20 const_iterator end() const noexcept
{
return const_iterator(this, m_size);
}
STAT_VEC_CONSTEXPR_CXX20 const_iterator cend() const noexcept
{
return const_iterator(this, m_size);
}
STAT_VEC_CONSTEXPR_CXX20 reverse_iterator rbegin() noexcept
{
return reverse_iterator(this, 0);
}
STAT_VEC_CONSTEXPR_CXX20 const_reverse_iterator rbegin() const noexcept
{
return const_reverse_iterator(this, 0);
}
STAT_VEC_CONSTEXPR_CXX20 const_reverse_iterator crbegin() const noexcept
{
return const_reverse_iterator(this, 0);
}
STAT_VEC_CONSTEXPR_CXX20 reverse_iterator rend() noexcept
{
return reverse_iterator(this, m_size);
}
STAT_VEC_CONSTEXPR_CXX20 const_reverse_iterator rend() const noexcept
{
return const_reverse_iterator(this, m_size);
}
STAT_VEC_CONSTEXPR_CXX20 const_reverse_iterator crend() const noexcept
{
return const_reverse_iterator(this, m_size);
}
STAT_VEC_NODISCARD STAT_VEC_CONSTEXPR_CXX20 bool empty() const noexcept
{
return m_size == 0;
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_CONSTEXPR_CXX20 size_type size() const noexcept
{
return m_size;
}
STAT_VEC_CONSTEXPR_CXX20 size_type max_size() const noexcept
{
return Capacity;
}
STAT_VEC_CONSTEXPR_CXX20 size_type capacity() const noexcept
{
return Capacity;
}
STAT_VEC_CONSTEXPR_CXX20 void clear() noexcept
{
for (size_type i = 0; i < m_size; i++) {
unchecked_at(i).~T();
}
m_size = 0;
}
STAT_VEC_CONSTEXPR_CXX20 iterator insert(const_iterator pos, const T& value)
{
check_insert(pos.m_idx, 1);
m_size++;
for (size_t i = m_size; i > pos.m_idx; i--) {
std::memcpy(unchecked_ptr_at(i), unchecked_ptr_at(i - 1), sizeof(T));
}
new (unchecked_ptr_at(pos.m_idx)) T(value);
return iterator(this, pos.m_idx);
}
STAT_VEC_CONSTEXPR_CXX20 iterator insert(const_iterator pos, T&& value)
{
check_insert(pos.m_idx, 1);
for (size_t i = m_size; i > pos.m_idx; i--) {
std::memcpy(unchecked_ptr_at(i), unchecked_ptr_at(i - 1), sizeof(T));
}
new (unchecked_ptr_at(pos.m_idx)) T(std::move(value));
m_size++;
return iterator(this, pos.m_idx);
}
iterator insert(const_iterator pos, size_type count, const T& value)
{
if (count > 0) {
check_insert(pos.m_idx, count);
for (size_t i = m_size; i > pos.m_idx; i--) {
std::memcpy(unchecked_ptr_at(i + count - 1), unchecked_ptr_at(i - 1), sizeof(T));
}
for (size_t i = 0; i < count; i++) {
new (unchecked_ptr_at(pos.m_idx + i)) T(value);
}
m_size += count;
}
return iterator(this, pos.m_idx);
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
template <class InputIt, typename std::enable_if<static_vec::is_input_iterator_t<InputIt>::value, bool>::type = true>
STAT_VEC_CONSTEXPR_CXX20 iterator insert(const_iterator pos, InputIt first, InputIt last)
{
check_iters(first, last);
size_t count = std::distance(first, last);
if (count > 0) {
check_insert(pos.m_idx, count);
for (size_t i = m_size; i > pos.m_idx; i--) {
std::memcpy(unchecked_ptr_at(i + count - 1), unchecked_ptr_at(i - 1), sizeof(T));
}
for (size_t i = 0; i < count; i++) {
new (unchecked_ptr_at(pos.m_idx + i)) T(*(first + i));
}
m_size += count;
}
return iterator(this, pos.m_idx);
}
STAT_VEC_CONSTEXPR_CXX20 iterator insert(const_iterator pos, std::initializer_list<T> ilist)
{
if (ilist.size() > 0) {
check_insert(pos.m_idx, ilist.size());
for (size_t i = m_size; i > pos.m_idx; i--) {
std::memcpy(unchecked_ptr_at(i + ilist.size() - 1), unchecked_ptr_at(i - 1), sizeof(T));
}
for (size_t i = 0; i < ilist.size(); i++) {
new (unchecked_ptr_at(pos.m_idx + i)) T(*(ilist.begin() + i));
}
m_size += ilist.size();
}
return iterator(this, pos.m_idx);
}
template <class... Args>
STAT_VEC_CONSTEXPR_CXX20 iterator emplace(const_iterator pos, Args&&... args)
{
check_insert(pos.m_idx, 1);
for (size_t i = m_size; i > pos.m_idx; i--) {
std::memcpy(unchecked_ptr_at(i), unchecked_ptr_at(i - 1), sizeof(T));
}
new (unchecked_ptr_at(pos.m_idx)) T(std::forward<Args>(args)...);
m_size++;
return iterator(this, pos.m_idx);
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_CONSTEXPR_CXX20 iterator erase(const_iterator pos)
{
check_erase(pos.m_idx, 1);
unchecked_at(pos.m_idx).~T();
for (size_t i = pos.m_idx; i < m_size - pos.m_idx; i++) {
std::memcpy(unchecked_ptr_at(i), unchecked_ptr_at(i + 1), sizeof(T));
}
m_size--;
return iterator(this, pos.m_idx + 1);
}
STAT_VEC_CONSTEXPR_CXX20 iterator erase(const_iterator first, const_iterator last)
{
check_iters(first, last);
size_t count = std::distance(first, last);
if (count > 0) {
check_erase(first.m_idx, count);
for (size_t i = 0; i < count; i++) {
unchecked_at(first.m_idx + i).~T();
}
for (size_t i = first.m_idx; i < m_size - first.m_idx; i++) {
std::memcpy(unchecked_ptr_at(i), unchecked_ptr_at(i + count), sizeof(T));
}
m_size -= count;
}
return iterator(this, first.m_idx + count);
}
STAT_VEC_CONSTEXPR_CXX20 void push_back(const T& value)
{
check_not_full();
new (unchecked_ptr_at(m_size)) T(value);
m_size++;
}
STAT_VEC_CONSTEXPR_CXX20 void push_back(T&& value)
{
check_not_full();
new (unchecked_ptr_at(m_size)) T(std::move(value));
m_size++;
}
template <class... Args>
STAT_VEC_CONSTEXPR_CXX20 T& emplace_back(Args&&... args)
{
check_not_full();
auto ptr = unchecked_ptr_at(m_size);
new (ptr) T(std::forward<Args>(args)...);
m_size++;
return *ptr;
}
STAT_VEC_CONSTEXPR_CXX20 void pop_back()
{
check_not_empty();
m_size--;
unchecked_at(m_size).~T();
}
STAT_VEC_CONSTEXPR_CXX20 void fill(const T& value)
{
clear();
for (size_t i = 0; i < Capacity; i++) {
new (unchecked_ptr_at(i)) T(value);
}
m_size = Capacity;
} | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
STAT_VEC_CONSTEXPR_CXX20 void swap(static_vec<T, Capacity>& other) noexcept
{
size_t temp_size = 0;
alignas(T) STAT_VEC_BYTE_T temp_data[sizeof(T) * Capacity];
std::memcpy(temp_data, m_data, sizeof(T) * Capacity);
std::memcpy(m_data, other.m_data, sizeof(T) * Capacity);
std::memcpy(other.m_data, temp_data, sizeof(T) * Capacity);
temp_size = m_size;
m_size = other.m_size;
other.m_size = temp_size;
}
};
#endif /* STAT_VEC_H */
Answer: Design
The reason for designing and using a fixed-capacity vector is generally efficiency. Forcing debug-iterators down the users throat breaks that. At least, make it opt-in, maybe following MS iterator debug levels.
If you use VectorType and const VectorType template arguments you can unify your checked iterators. Use copy_const and similar helpers:
template <class T, class U>
using copy_const_t = typename std::conditional<std::is_const<T>::value, const U, U>::type;
Implementation
You can strip all automatic handling for ctors/op=/dtors from a member by making it the sole member of an anonymous unnamed union without sacrificing ease of use.
Specifically, it will cut down on casting required, thus you no longer have to hide the uglyness.
Don't extract all of a function into a differently named function. How far would you go? Any reader would have to understand (and check) your functions in addition to the (now) wrapper.
People expect object to be destructed in reverse order of construction. Thus, the highest index should be destroyed first, the lowest last, unless that causes unacceptable inefficiency.
Most objects might be bitwise movable or even bitwise copyable (trivially copyable), thus doing so with std::memcpy() might work for them, but it is generally wrong. Beware if there are pointers to the object (e.g. short std::string in GCC's libstdc++) or the objects value is position-dependent (any kind of relative pointer). | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c++, c++11, vectors
InputIterators only guarantee the sequence they provide can be iterated and read once.
Only RandomaccessIterators guarantee efficient distance-calculation, and freedom from UB even if negative. Test for the subtractibility directly, don't depend on the iterator category. | {
"domain": "codereview.stackexchange",
"id": 44142,
"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++11, vectors",
"url": null
} |
c#, http, .net-core, httpclient
Title: HttpClient retry handler on response 429
Question: When the remote server returns a 429 (Too Many Requests) response with the Retry-After header, the HttpClient can handle such cases with a handler:
public class RetryHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.TooManyRequests
&& response.Headers.RetryAfter is not null)
{
var delta = TimeSpan.Zero;
if (response.Headers.RetryAfter.Date.HasValue)
{
delta = response.Headers.RetryAfter.Date.Value - DateTimeOffset.Now;
}
if (delta <= TimeSpan.Zero && response.Headers.RetryAfter.Delta.HasValue)
{
delta = response.Headers.RetryAfter.Delta.Value;
}
if (delta > TimeSpan.Zero)
{
await Task.Delay(delta, cancellationToken);
response = await base.SendAsync(request, cancellationToken);
}
}
return response;
}
}
And usage example:
HttpClient client = HttpClientFactory.Create(new RetryHandler(), new Handler2(), new Handler3());
Do you see any improvements / problems?
Answer: Let me suggest here an alternative solution, namely the Polly's retry policy. This library is the Microsoft suggested way to decorate any HttpClients (normal, named, typed or named and typed clients).
In order to use it, you need the following libraries:
Polly: this helps you to define policies
Microsoft.Extensions.Http.Polly: this helps you to integrate policies into the HttpClient's pipeline
Please be aware that there is a Polly.Extensions.Http package as well but that is deprecated | {
"domain": "codereview.stackexchange",
"id": 44143,
"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#, http, .net-core, httpclient",
"url": null
} |
c#, http, .net-core, httpclient
Please be aware that there is a Polly.Extensions.Http package as well but that is deprecated
The policy
In order to define a retry policy against HttpClient you need to do the followings:
Define a policy which returns with an HttpResponseMessage
Define that policy as asynchronous
So, the defined policy must be an IAsyncPolicy<HttpResponseMessage>:
IAsyncPolicy<HttpResponseMessage> retryAfterPolicy = Policy
.HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests && r.Headers.RetryAfter != null)
.WaitAndRetryAsync(
1,
(_, result, _) => result.Result.Headers.RetryAfter.Delta.Value,
(_, __, ___, ____) => Task.CompletedTask);
OR
Func<HttpResponseMessage, bool> shouldRetry = r => r.StatusCode == HttpStatusCode.TooManyRequests && r.Headers.RetryAfter != null;
var retryAfterPolicy = Policy
.HandleResult(shouldRetry)
.WaitAndRetryAsync(
1,
(_, result, _) => result.Result.Headers.RetryAfter.Delta.Value,
(_, __, ___, ____) => Task.CompletedTask);
The parameters of the WaitAndRetryAsync
retryCount: How many retries should be issued if the condition is met (the predicate provided to the HandleResult)
sleepDurationProvider: How much time should be spent with sleeping/waiting between retry attempts
onRetryAsync: This delegate is designed mainly for logging purposes. It is called before the policy goes to sleep between two retry attempts
The integration
The Microsoft.Extensions.Http.Polly defines several extension methods: | {
"domain": "codereview.stackexchange",
"id": 44143,
"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#, http, .net-core, httpclient",
"url": null
} |
c#, http, .net-core, httpclient
The integration
The Microsoft.Extensions.Http.Polly defines several extension methods:
AddPolicyHandler: It allows you to decorate an HttpClient with an IAsyncPolicy<HttpResponseMessage> policy
AddPolicyHandlerFromRegistry: Polly allows us to add our policies to a registry. This method allows you to decorate an HttpClient with an IAsyncPolicy<HttpResponseMessage> policy from a pre-populated registry
AddTransientHttpErrorPolicy: It allows you to decorate an HttpClient with an IAsyncPolicy<HttpResponseMessage> policy. It is pre-configured to trigger for HttpRequestException and for status code: 408 or 5xx
Under the hood all of them register a PolicyHttpMessageHandler into the HttpClient pipeline which is indeed a DelegatingHandler.
Let me show you how to use it for a named client
builder.Services
.AddHttpClient("SampleApi", client =>
{
client.BaseAddress = new Uri("http://.../");
})
.AddPolicyHandler(retryAfterPolicy);
Usage
public class SampleController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public SampleController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var httpClient = _httpClientFactory.CreateClient("SampleApi");
//...
}
} | {
"domain": "codereview.stackexchange",
"id": 44143,
"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#, http, .net-core, httpclient",
"url": null
} |
c#, http, .net-core, httpclient
Next steps
If you have received a 429 that means the downstream system is overloaded / under pressure / flooded with requests. So, it might make sense to let it perform self-healing and then retry any pending requests.
With the above setup each and every concurrent requests are sent to the downstream system to receive the same "I'm busy" response. It would be nice if we could avoid this unnecessary roundtrips to get the same message.
The good news is that we can do this by using a Circuit Breaker. This can be used to short cut any outgoing requests while the downstream is trying to heal itself. The CB has a shared state which can be accessed by the concurrent requests. So, rather than flooding the downstream with new requests we can prevent that on the client-side by short-cutting them.
We can combine the retry policy with circuit breaker to define a protocol which will respect the RetryAfter header and applies that to all outgoing requests.
I would like to mention one other policy which might be useful here and that is the timeout policy. It allows you to define an upper limit on time to get a valuable response.
Either you can define that time constraint on a per retry attempt bases
retry > local_timeout
Or you can define that time constraint as an overarching constraint which covers all retry attempts
global_timeout > retry
Or you can combine both
global_timeout (60 seconds) > retry (three times) > local_timeout (2 seconds)
And of course the Circuit Breaker could be added to this policy chain as well. I have posted a lots of answers on SO about this topic, just to name a few: 1, 2, 3, 4, etc. | {
"domain": "codereview.stackexchange",
"id": 44143,
"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#, http, .net-core, httpclient",
"url": null
} |
python, python-3.x, comparative-review, iterator
Title: Convert Rankine temperatures to Celsius
Question: I have this Python Package called ToTemp under development for precise Temperature Conversions and currently thinking in changing the method's implementation to be able to convert multiple values and return an Iterable with those converted values (in a list).
It would be good to see some reviews on this.
Default implementation:
class Rankine:
"""Provides conversion of Rankine to other temperature scales"""
@staticmethod
def to_celsius(rankine: float | int, /, *, float_ret=True) -> float | int:
"""
Converts Rankine to Celsius, returning a float by default.
If the float_ret parameter is False, it returns an approximate int value
(using the math's module trunc function).
:param rankine: Rankine value(s) to be converted
:param float_ret: Optional, True by default to return floats
:return: float, int or Iterable
"""
if float_ret:
return float((rankine - 491.67) * 5/9)
return trunc((rankine - 491.67) * 5/9)
Now, with the iter() method:
class Rankine:
"""Provides conversion of Rankine to other temperature scales"""
@staticmethod
def to_celsius(rankine: float | int | Iterable, /, *, float_ret=True) -> float | int | Iterable:
"""
Converts Rankine to Celsius, returning a float by default.
If the float_ret parameter is False, it returns an approximate int value
(using the math's module trunc function). | {
"domain": "codereview.stackexchange",
"id": 44144,
"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, python-3.x, comparative-review, iterator",
"url": null
} |
python, python-3.x, comparative-review, iterator
:param rankine: Rankine value(s) to be converted
:param float_ret: Optional, True by default to return floats
:return: float, int or Iterable
"""
try:
iter(rankine)
if float_ret:
return [float((value - 491.67) * 5/9) for value in rankine]
return [trunc((value - 491.67) * 5/9) for value in rankine]
except TypeError:
if float_ret:
return float((rankine - 491.67) * 5/9)
return trunc((rankine - 491.67) * 5/9)
Answer: Unit Typing
You are under-using the Rankine class, and I presume the other temperature classes.
Primitive Obsession (only manipulating primitive types) means never being quite sure which unit a type is in. When you have a temperature value in hand, is it expressed in Kelvin? Rankine? Celsius? Anything else? In fact... is it even a temperature?
Instead, make Rankine a @dataclass:
from dataclasses import dataclass
from typing import Generic, NewType, TypeVar
T = TypeVar('T', bound=int | float)
@dataclass
class Rankine(Generic[T]):
value: T
Then, you can write conversion methods in a generic manner.
User's Pick
Let the user pick the type they wish automatically, and do not change it "under their back" with an option:
def to_rankine(self) -> 'Rankine[T]':
return Rankine(self.value)
def to_celsius(self) -> 'Celsius[T]':
celsius = type(self.value)((self.value - 491.67) * 5/9)
return Celsius(celsius)
Instead, provide explicit methods to change the underlying type:
def with_float(self) -> 'Rankine[float]':
return Rankine(float(self.value))
def with_int(self) -> 'Rankine[int]':
return Rankine(int(self.value))
This means that any underlying type change is explicit, rather than the result of accidentally using the default option. | {
"domain": "codereview.stackexchange",
"id": 44144,
"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, python-3.x, comparative-review, iterator",
"url": null
} |
java, beginner, homework
Title: Printing a Hollow Butterfly pattern
Question:
I am a beginner to Java and have studied up to loops only. After loops lecture above pattern was given to print as homework. I have successfully managed to print this pattern with following code:
public class Main {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
{
System.out.print("*");
}
for(int j=1; j<=2*(n-i); j++){
System.out.print(" ");
}
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
{
System.out.print("*");
}
System.out.println(" ");
}
for (int i = n; i >= 1; i--) {
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
System.out.print("*");
for(int j=1; j<=2*(n-i); j++){
System.out.print(" ");
}
System.out.print("*");
for (int j = 1; j <= i - 2; j++){
System.out.print(" ");
}
if(i>1)
System.out.print("*");
System.out.println(" ");
}
}
}
I don't know if I have followed the best possible approach according to as much I have studied java until now. Please suggest if any improvements can be made. | {
"domain": "codereview.stackexchange",
"id": 44145,
"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, beginner, homework",
"url": null
} |
java, beginner, homework
Answer: I think your code is fine: it answers the question, and does not set any major red flag off. Good job!
There is one red flag, though: code repetition. The content of your two i-loops are identical. When that happens, you should put it inside a function, if you have learned how to do that.
There are a few ways to simplify your code.
First option: j tracks the index of the white space
I don't think this option is actually sensible, and I would go straight to the second one, but I'll describe it anyway in case you had not realize you could change the start index.
Here, each of your j-indexed loop counts from 1 to the number of whitespaces you want to include. You could change that and have j be the index of the character on the line. For example, for any line but the first and the last, the stars are positionned at indices (starting from 1 as you did rather than 0 as is usually done in Java and most computer languages) 1, i+1, 2*n-i+1, 2*n. Then, the whitespaces blocks have ranges [2,i], [i+2,2*n-i],[2*n-i+2,2*n-1]. The line for (int j = 1; j <= i - 2; j++){ could become for (int j = i+2; j <= 2*n-i; j++){.
It doesn't change much, and I would not go so far as to call that an improvement rather than an alternate solution.
Second option: only one loop per line
You obviously know how to use if-statements as well as loops, because you use four of them. You could leverage that to simplify the block you use to print a line: instead of breaking the j-loop, move the test inside.
I assume below that you also know how to use the if-else construct. If that is not the case, you can simply change the else line into another if-test.
System.out.print("*");
for (int j = 2; j < 2*n; j++){
if (j == i || j == 2*n-i+1){
System.out.print("*");
} else {
System.out.print(" ");
}
System.out.println("*");
} | {
"domain": "codereview.stackexchange",
"id": 44145,
"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, beginner, homework",
"url": null
} |
java, beginner, homework
Third option: down to only two loops
In this option, I assume that you actually know about function calls and String concatenation. Starting from Java 11, you could replace the j-loops with a simple call to String::repeat. Then, you obtain something like System.out.println("*" + " ".repeat(...) + "*" + " ".repeat(...)" + ...) for all lines but the first and the last. I leave it to you to actually fill in the blanks if you are using Java 11. | {
"domain": "codereview.stackexchange",
"id": 44145,
"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, beginner, homework",
"url": null
} |
java, comparative-review
Title: Functional Style if/else in java
Question: I would like to ask the opinion for experts out there. The following code snippet was written by a colleague of mine who is very fond of functional style in Java.
public Book findBookByIsbnOrId(String isbn, String id) {
return Optional.ofNullable(isbn).map(i -> {
return bookDao.findByIsbn(i);
})
.orElseGet(() -> {
return bookDao.findById(id);
});
}
This code has been modified to be used at Stack Exchange. Essentially, finding the book has preference (ISBN) which when not present should be search via (ID).
I would argue that this code although functionally fulfils the given requirement is less readable than
if (StringUtils.isNotBlank(isbn)) {
return bookDao.findByIsbn(isbn);
} else {
return bookDao.findById(id);
}
I would like to ask the opinion of others whether they think this is just over-engineering?
Answer: The two versions with equivalent functionality and cleaned would be:
public Book findBookByIsbnOrId(String isbn, String id) {
return Optional.ofNullable(isbn)
.map(bookDao::findByIsbn)
.orElseGet(() -> bookDao.findById(id));
}
public Book findBookByIsbnOrId(String isbn, String id) {
return isbn != null
? bookDao.findByIsbn(isbn)
: bookDao.findById(id));
}
Though using Stream is often better and allows more powerful expressions, here the nullable ISBN is dealt with an Optional and that is circumstantial here.
So your second version is much neater. However the first version might be a reaction to a nullable parameter - which is bad style. So he turned it into an Optional<String> on principle. The API should have been different, the most similar - though probably still not good style - would have been:
public Book findBookByIsbnOrId(Optional<String> isbn, String id) {
return isbn
.map(bookDao::findByIsbn)
.orElseGet(() -> bookDao.findById(id));
} | {
"domain": "codereview.stackexchange",
"id": 44146,
"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, comparative-review",
"url": null
} |
java, comparative-review
Conclusion: your version suffices, but nice would be
public Book findBookByIsbnOrId(@Nullable String isbn, String id) { | {
"domain": "codereview.stackexchange",
"id": 44146,
"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, comparative-review",
"url": null
} |
typescript
Title: Two Sum Leetcode problem using Typescript
Question: I've recently gotten into Typescript and I'm solving some Leetcodes to learn.
Problem description:
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Constraints:
2 <= nums.length <= 104
\$-10^9\$ <= nums[i] <= \$10^9\$
\$-10^9\$ <= target <= \$10^9\$
Only one valid answer exists.
I wrote this:
function twoSum(nums: number[], target: number): number[] {
let map: Entry[] = [];
type Entry = {
readonly index: number,
readonly value: number,
};
let result: number[] = [];
let test: any = nums.map((elem, index) => {
let map_search = map.find((entry) => entry.value === target - elem);
if(map_search) {
// contains suitable index
result.push(index, map_search.index);
} else {
let new_entry: Entry = {
index: index,
value: elem,
};
map.push(new_entry);
}
})
if(result) {
return result;
} else {
return [];
}
};
My solution works, but it feels a bit messy and inefficient in places. I feel like I'm not doing things in the proper Typescript way. Are there any suggestions for improvement? | {
"domain": "codereview.stackexchange",
"id": 44147,
"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": "typescript",
"url": null
} |
typescript
Answer: I'll start with the simple ones.
Use const instead of let when possible. It prevent accidental overwrites and it also better comunicates the intent. In fact, in your code, const is suitable in every single instance.
The test variable is unused and in fact, you should not call map at all if you're not mapping the array. You just wanna "forEach" the array or simply loop it using for.
Avoid using any type unless really necesary and it should stand for "any type is suitable here". If you just don't know what the type, better to use unknown.
Since result can only be Array, asking if (result) is meaningless because it will always be true.
No need to write semicolons in ts/js. At least you're consistent in using them, but it's very easy to go inconsistent without noticing. Most professionals probably use a linter configured to disallow them.
I would also change the return type if nothing is found to null rather then empty array and actually instead of number[] your can return [number, number] since it will always have two elements. If we were not constrained to exactly one solution, it would make sense to return [number,number][] and then empty array for "not found any solution" would fit.
Now for the performance. Time complexity of your solution is O(n^2).
From specification
each input would have exactly one solution
We can return as soon as we find it.
We can also infer that each element of nums array is unique. And so we can construct an inverted map and use it to better the algorithm time complexity into O(n). However we sacrficice O(n) extra memory for the Map (although your solution does that too).
function twoSum(nums: number[], target: number): [number, number] | null {
const visitedIndicesByValue = new Map<number, number>() | {
"domain": "codereview.stackexchange",
"id": 44147,
"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": "typescript",
"url": null
} |
typescript
for (let i = 0; i < nums.length; ++i) {
const diff = target - nums[i]
if (visitedIndicesByValue.has(diff)) {
return [visitedIndicesByValue.get(diff), i]
} else {
visitedIndicesByValue.set(nums[i], i)
}
}
return null
} | {
"domain": "codereview.stackexchange",
"id": 44147,
"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": "typescript",
"url": null
} |
php, strings
Title: Creating storage path for file from first characters of a hash
Question: I made the following function to create the storage path for files from the the first 5 characters of the file's hash:
function create_path($hash)
{
$splitted_hash = str_split(strtolower(substr($hash, 0, 5)));
$path = "";
foreach($splitted_hash as $char) {
$path.="/$char";
}
return "$path/";
}
// will output something like "a/h/q/6/d/"
But is there a better way to do that? This seems a bit cumbersome.
Answer: Php has a join (also known as implode) so you can simply do
function createPath($hash)
{
return join("/", str_split(strtolower(substr($hash, 0, 5)))) . "/";
}
Note the concatenation for the final "/". | {
"domain": "codereview.stackexchange",
"id": 44148,
"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": "php, strings",
"url": null
} |
java, strings, file
Title: FileIO lines to String Converter
Question: I think I made a good FileIO object because I can simply copy-paste whenever I need, however I wonder How I can improve my code.
This code takes file path of the target file and turns every line to Strings. And combine all of the Strings into String array so that we can use the data of the file.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileIO {
private BufferedReader br;
private FileInputStream fIn;
private String fileName;
private int length;
private String[] data;
public FileIO(String fileName) throws IOException {
this.fileName = fileName;
createFile();
setLength();
setData();
fIn.close();
br.close();
}
private void createFile() {
try {
fIn = new FileInputStream(fileName);
br = new BufferedReader(new InputStreamReader(fIn));}
catch (FileNotFoundException e) {
System.out.println("ERROR! " + fileName + " named file does not found!");
System.exit(-1);
}}
private void setLength() throws IOException {
length = 0;
br.readLine(); // if first line of the file is not title, delete this.
while((br.readLine()) != null) {
length++;
}}
private void setData() throws IOException {
data = new String[length];
fIn.getChannel().position(0);
br = new BufferedReader(new InputStreamReader(fIn));
br.readLine(); // if first line of the file is not title, delete this.
for (int i = 0; i < length; i++) {
data[i] = br.readLine();}
}
public int getNumberOfLines() {
return length;
}
public String[] getAllData() {
return data;
} | {
"domain": "codereview.stackexchange",
"id": 44149,
"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, file",
"url": null
} |
java, strings, file
public String[] getAllData() {
return data;
}
public String getDataLine(int lineNumber) throws Exception {
if (length < lineNumber) {
throw new Exception("Line number is greater than all of the lines! Please enter a number between 0 and " + length);}
return data[lineNumber-1];}
}
Answer: Java isn't my main language, but I noticed this:
catch (FileNotFoundException e) {
System.out.println("ERROR! " + fileName + " named file does not found!");
System.exit(-1);
We should be writing the message to System.err, not System.out.
It's normal to use small positive values for program exit status (-1 will likely end up converted to 255 in most shells).
Consider whether there's extra information in the exception e that should be reported (file doesn't exist, exists but permission denied, etc).
Most of these members:
private BufferedReader br;
private FileInputStream fIn;
private String fileName;
private int length;
private String[] data;
are used only to communicate between functions called by the constructor:
public FileIO(String fileName) throws IOException {
this.fileName = fileName;
createFile();
setLength();
setData();
fIn.close();
br.close();
}
I think we can get rid of most of them with small changes to the functions so that they make those communications explicit:
private String[] data;
public FileIO(String fileName) throws IOException {
FileInputStream fIn = openFile(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fIn));
data = new String[measureLength(br)];
fIn.getChannel().position(0);
br = new BufferedReader(new InputStreamReader(fIn));
readLines(br);
}
(Obviously, uses of length in the code are now replaced by data.length).
openFile(), measureLength() and readLines() can then all be static methods, making them more self-contained. | {
"domain": "codereview.stackexchange",
"id": 44149,
"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, file",
"url": null
} |
swift, stack, queue
Title: Queue implemented using two stacks in Swift
Question: I need your expert opinion! In fact, for a Leetcode Problem, I had to code a queue using 2 stacks. It's shown just below and functions well.
It is a pretty simple code with peek, pop, push, etc. functions, quite classic. But this code does not please me completely since I coalesce the optionals with a default value, taken out of my hat, to avoid forced unwrapping.
Do you see a more professional way to write this?
class MyQueue {
private var stack1: [Int]
private var stack2: [Int]
private var front: Int?
init() {
stack1 = []
stack2 = []
}
func push(_ x: Int) {
if stack1.isEmpty {
front = x
}
stack1.append(x)
}
func pop() -> Int {
if stack2.isEmpty {
while !stack1.isEmpty {
stack2.append(stack1.popLast() ?? -1)
}
}
return stack2.popLast() ?? -1
}
func peek() -> Int {
if !stack2.isEmpty {
return stack2.last ?? -1
}
return front ?? -1
}
func empty() -> Bool {
return stack1.isEmpty && stack2.isEmpty
}
}
Answer: Don't use “magic” values (in your case: -1) to indicate the absence of a value. Swift has the Optional type exactly for that purpose. The queue methods should be declared as
func push(_ x: Int)
func pop() -> Int?
func peek() -> Int?
func empty() -> Bool
and nil is returned if the queue is empty.
There is nothing special about the Int type here. It is simple to make the queue type generic
class MyQueue<Element> {
func push(_ x: Element)
func pop() -> Element?
func peek() -> Element?
func empty() -> Bool
}
and now you can use it with arbitrary types. For example
let queue = MyQueue<String>()
queue.push("foo")
There is no need for a dedicated front element, and the code becomes simpler without it.
Moving the elements from the first to the second stack in func pop() can be simplified to
while let elem = stack1.popLast() {
stack2.append(elem)
} | {
"domain": "codereview.stackexchange",
"id": 44150,
"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": "swift, stack, queue",
"url": null
} |
swift, stack, queue
with a single test instead of two per iteration. Or even simpler:
stack2 = stack1.reversed()
stack1.removeAll()
(If your queues become really large then you might want to check which of the above methods is faster.)
If a function body consists of a single expression then the return keyword can be omitted.
Putting it all together, we get
class MyQueue<Element> {
private var stack1: [Element]
private var stack2: [Element]
init() {
stack1 = []
stack2 = []
}
func push(_ x: Element) {
stack1.append(x)
}
func pop() -> Element? {
if stack2.isEmpty {
stack2 = stack1.reversed()
stack1.removeAll()
}
return stack2.popLast()
}
func peek() -> Element? {
stack2.last ?? stack1.first
}
func empty() -> Bool {
stack1.isEmpty && stack2.isEmpty
}
}
which is shorter and simpler.
Finally, naming:
I had to inspect the code in order to understand that what you have implemented is a “first in, first out” queue. This would be more obvious to a user of your code (or to you in one year) with a more specific class name, such as FIFO or FIFOQueue.
Typical names for adding something to a FIFO and retrieving it are enqueue and dequeue.
Swift collection types typically use “isEmpty” as the name of a property which indicates whether the collection contains elements or not:
var isEmpty: Bool {
stack1.isEmpty && stack2.isEmpty
} | {
"domain": "codereview.stackexchange",
"id": 44150,
"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": "swift, stack, queue",
"url": null
} |
python
Title: Encoding and Decoding Bytes in Python
Question: I'm dealing with a communication channel that:
Converts \n characters into \r\n
Removes 0xfd, 0xfe, and 0xff characters entirely
Not ideal for transferring binary data.
I can effectively use base64 to transfer binary data through it, but this makes the data being transferred 33% larger, which, when dealing with large amounts of binary data like I am, kinda sucks.
A simple, not entirely efficient way to use Python to create my own encoding is this:
escape_char = b'='
# These are the bytes we don't want in our stream
bytes_to_escape = b'\n\xfd\xfe\xff'
# This is a mapping of the bytes being replaced, with the bytes we're
# replacing them with
replacements = {
escape_char: escape_char,
**{
byte: i.to_bytes(1, "big")
for i, byte in enumerate([bytes([b]) for b in bytes_to_escape])
}
}
# Reverse mapping, for decoding
reverse_replacements = {v: k for k, v in replacements.items()}
# Encoder
def encode(data: bytes) -> bytes:
result = b''
for byte in [bytes([i]) for i in data]:
replacement = replacements.get(byte)
if replacement:
result += escape_char + replacement
else:
result += byte
return result
# Decoder
def decode(data: bytes) -> bytes:
result = b''
i = 0
while i < len(data):
current_byte = bytes([data[i]])
next_byte = bytes([data[i+1]]) if i+1 < len(data) else None
if current_byte == escape_char:
if not next_byte:
result += current_byte
else:
replacement = reverse_replacements[next_byte]
result += replacement
i += 1
else:
result += current_byte
i += 1
return result
This will essentially:
Escape the = character with ==, because it's used as our escape character
Convert \n to 0x00
Convert 0xfd to 0x01
Convert 0xfe to 0x02
Convert 0xff to 0x03 | {
"domain": "codereview.stackexchange",
"id": 44151,
"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",
"url": null
} |
python
Is there a way to make this more efficient, short of writing it in a low-level language as a python module? Maybe something that uses regex might work faster?
Answer: bytes
You are working with bytes which is very cumbersome.
You have to prefix all literals
single bytes have type int and need to be converted to to bytes again
At least I cannot do this without debugging some errors.
It is much more convenient to work with strings. So I suggest to decode the bytes to a string with an 8-bit codec like 'latin-1'.
No more bytes([x]) or x.to_bytes(). You can use plain comprehension, plain ''.join(), etc.
If required you encode the string to bytes again with the very same codec.
dict.get()
For conditional translations there is a nice trick - dict.get() - which allows to pass a default value for non-existing keys.
translated = replacements.get(char, char)
This returns replacements[char] if char is in replacements.keys(). Otherwise it returns the default char.
To use this functionality you include the escape character in the translation table (however you fill it).
replacements = {escape_char: escape_char + escape_char,
'\n': escape_char + '\x00',
'\xfd': escape_char + '\x01',
'\xfe': escape_char + '\x02',
'\xff': escape_char + '\x03',
}
The encoding function now reads
def encode(data: bytes) -> bytes:
str_data = data.decode(encoding='latin-1')
str_enc = ''.join(replacements.get(x, x) for x in str_data)
return str_enc.encode(encoding='latin-1') | {
"domain": "codereview.stackexchange",
"id": 44151,
"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",
"url": null
} |
python
loop like a pro
In your decoding function you loop over len(data) which is an anti-pattern. You should always loop over the elements. To make it worse you use a while loop and increment the loop counter manually. You also access elements with index i+1 which again is error prone.
Loop over elements only and keep a little state like a previous_byte. You cannot be out of bounds.
def decode(data: bytes) -> bytes:
d_data = data.decode(encoding='latin-1')
l = []
esc = ''
for x in d_data:
if not esc and x == escape_char:
esc = x
continue
l.append(reverse_replacements.get(esc + x, esc + x))
esc = ''
assert esc == ''
return ''.join(l).encode(encoding='latin-1)')
testing
For your nicely testable functions you should provide some tests. There are unit test frameworks available.
You can also do the most primitive assertions, of course in a main guard.
if __name__ == '__main__':
assert encode(b"asdf") == b"asdf"
assert decode(b"asdf") == b"asdf"
assert encode(b"as\ndf") == b"as=\x00df"
assert decode(b"as=\x00df") == b"as\ndf"
assert encode(b"\ndf") == b"=\x00df"
assert decode(b"=\x00df") == b"\ndf"
assert encode(b"as\n") == b"as=\x00"
assert decode(b"as=\x00") == b"as\n"
assert encode(b"as\xfddf") == b"as=\x01df"
assert decode(b"as=\x01df") == b"as\xfddf"
assert encode(b"as\xfedf") == b"as=\x02df"
assert decode(b"as=\x02df") == b"as\xfedf"
assert encode(b"as\xffdf") == b"as=\x03df"
assert decode(b"as=\x03df") == b"as\xffdf" | {
"domain": "codereview.stackexchange",
"id": 44151,
"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",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.