text stringlengths 1 2.12k | source dict |
|---|---|
c++, time-limit-exceeded, vectors, binary-search-tree
while (D--) {
char c;
int x;
std::cin >> c >> x;
if (c == 'B') {
// Buy stock
portfolio=insertIntoBST(portfolio, x);
} else if (c == 'S') {
portfolio=deleteNode(portfolio, x);
} else if (c == 'R') {
// Check if the stock is present in the portfolio
bool found = searchBST(portfolio,x);
if (found) {
std::cout << "YES" << std::endl;
} else {
std::cout << "NO" << std::endl;
}
}
}
return 0;
}
``` | {
"domain": "codereview.stackexchange",
"id": 45061,
"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++, time-limit-exceeded, vectors, binary-search-tree",
"url": null
} |
beginner, programming-challenge, rust
Title: Project Euler Problem 1: Multiples of 3 or 5
Question: The following is my solution to Project Euler Problem 1: Multiples of 3 or 5.
use clap::Parser;
use std::ops::RangeFrom;
use std::process::exit;
const VALID_NUMBER_RANGE: RangeFrom<u64> = 2..;
#[derive(Parser)]
struct Arguments {
#[arg(index = 1)]
first_number: u64,
#[arg(index = 2)]
second_number: u64,
#[arg(index = 3)]
threshold: u64,
}
fn main() {
let arguments = Arguments::parse();
let first_number = arguments.first_number;
let second_number = arguments.second_number;
let threshold = arguments.threshold;
if !VALID_NUMBER_RANGE.contains(&first_number) {
eprintln!("Error: First number out of range: {}", first_number);
exit(1);
} else if !VALID_NUMBER_RANGE.contains(&second_number) {
eprintln!("Error: Second number out of range: {}", second_number);
exit(1);
}
let pair_multiples_sum = sum_pair_multiples(first_number, second_number, threshold);
println!("{}", pair_multiples_sum);
}
fn sum_multiples(number: u64, threshold: u64) -> u64 {
(number..threshold).filter(|n| n % number == 0).sum()
}
fn find_greatest_common_divisor(first_number: u64, second_number: u64) -> u64 {
if second_number == 0 {
first_number
} else {
find_greatest_common_divisor(second_number, first_number % second_number)
}
}
fn find_least_common_multiple(first_number: u64, second_number: u64) -> u64 {
let greatest_common_divisor = find_greatest_common_divisor(first_number, second_number);
first_number * second_number / greatest_common_divisor
}
fn sum_pair_multiples(first_number: u64, second_number: u64, threshold: u64) -> u64 {
let least_common_multiple = find_least_common_multiple(first_number, second_number);
let mut first_number_multiples_sum: u64 = 0;
let mut second_number_multiples_sum: u64 = 0;
let mut least_common_multiple_multiples_sum: u64 = 0; | {
"domain": "codereview.stackexchange",
"id": 45062,
"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, programming-challenge, rust",
"url": null
} |
beginner, programming-challenge, rust
rayon::scope(|s| {
s.spawn(|_| first_number_multiples_sum = sum_multiples(first_number, threshold));
s.spawn(|_| second_number_multiples_sum = sum_multiples(second_number, threshold));
s.spawn(|_| {
least_common_multiple_multiples_sum = sum_multiples(least_common_multiple, threshold)
});
});
first_number_multiples_sum + second_number_multiples_sum - least_common_multiple_multiples_sum
}
How can I improve my code? Any form of improvement is welcome.
Answer: The implementation is far more complex than the problem calls for. Maybe that's practice for more complex problems?
You don't need to handle arguments, the problem has fixed parameters.
You don't need threading, this problem is far too small to warrant that. By the way sum_multiples can be expressed in closed form, in that case you definitely don't need threading, even if threshold was large (which it isn't so it doesn't actually matter, but it's an opportunity to explore some mathematics and that's what Project Euler is about).
fn find_greatest_common_divisor
Generally mathematical functions (especially the more "basic" or "light weight" ones, such as GCD) are exempted from the guideline to make function names verbs. Prefixing them with "find" or "compute" is not useful, just noisy. | {
"domain": "codereview.stackexchange",
"id": 45062,
"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, programming-challenge, rust",
"url": null
} |
c++, converting, c++20, casting
Title: safe numeric type converter
Question: I have written a function for casting between built in numeric types. I built it to check if the source value is within the range of the destination value, and to provide a nicely legible error if not. I also built it such that float -> conversions round instead of truncate and so that int -> float conversions do not error if the int value is not exactly representable as an int (so do best effort). It can be assumed that there will be no nan or inf in the input (if the input is float). Example code is here. My questions:
is this safe or are there cases that i am not checking?
are there some easy opportunities for optimization (for execution speed in non-error cases)? | {
"domain": "codereview.stackexchange",
"id": 45063,
"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++, converting, c++20, casting",
"url": null
} |
c++, converting, c++20, casting
main function:
// function to convert between types, inputs and outputs can be
// integral (including bool) and floating point
// throws if conversion not possible (including due to overflow)
// NB: we don't care if an integral to be converted to float cannot
// be precisely represented, so int types->float types conversion
// always succeeds
template <typename T, typename S>
requires (std::is_integral_v<S> || std::is_floating_point_v<S>) && (std::is_integral_v<T> || std::is_floating_point_v<T>)
constexpr
T convertType(S val_)
{
if constexpr (std::is_same_v<S, T>)
// source and target are the same type, no conversion needed
return val_;
else if constexpr (std::is_same_v<S, bool>)
{
// bool can be directly cast to any of the possible output types
return static_cast<T>(val_);
}
else if constexpr (std::is_same_v<T, bool>)
// any input can be directly converted to bool through the not operator
return !!val_;
else if constexpr (std::is_integral_v<S> && std::is_integral_v<T>)
{
if (std::in_range<T>(val_))
return static_cast<T>(val_);
else
throw std::range_error(std::format("Cannot convert value: the value contained in the input type '{}' ({}) is outside the range of the requested output type '{}'", typeToString<S>(), val_, typeToString<T>()));
}
else if constexpr (std::is_floating_point_v<S> && std::is_floating_point_v<T>)
{
// float -> float, may overflow if target type is smaller than source type
if (sizeof(T) < sizeof(S) && (val_ > std::numeric_limits<T>::max() || val_ < std::numeric_limits<T>::lowest()))
throw std::range_error(std::format("Cannot convert value: the value contained in the input type '{}' ({}) is outside the range of the requested output type '{}'", typeToString<S>(), val_, typeToString<T>())); | {
"domain": "codereview.stackexchange",
"id": 45063,
"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++, converting, c++20, casting",
"url": null
} |
c++, converting, c++20, casting
return static_cast<T>(val_);
}
// now either float -> int, or int -> float
else if constexpr (std::is_floating_point_v<S>)
{
// float -> int. We round the float away from zero
if (val_ + .5 > std::nextafter(std::numeric_limits<T>::max(), 0))
throw std::overflow_error(std::format("Cannot convert value: the value contained in the input type '{}' ({}) is too large for the requested output type '{}'", typeToString<S>(), val_, typeToString<T>()));
else if (val_ - .5 < std::nextafter(std::numeric_limits<T>::min(), 0))
throw std::underflow_error(std::format("Cannot convert value: the value contained in the input type '{}' ({}) is too small for the requested output type '{}'", typeToString<S>(), val_, typeToString<T>()));
else
{
// in range, now cast, rounding as appropriate
if (std::is_same_v<T, uint64_t> && (val_ + .5 > nextafter(std::numeric_limits<int64_t>::max(), 0)))
// can't use lround/llround, use a poor man's version that rounds away from zero
return static_cast<T>(val_ + .5 * ((val_ > 0.) ? 1. : ((val_ < 0.) ? -1. : 0.))); //+.5 if positive, -.5 if negative, +0 if 0 for good measure
else if (sizeof(T) > sizeof(long))
return static_cast<T>(llround(val_));
else
return static_cast<T>(lround(val_));
}
}
else if constexpr (std::is_floating_point_v<T>)
{
// int -> float
// NB: we ignore whether the value is representable by the float, so nothing to check here
return static_cast<T>(val_);
}
else
{
static_assert(always_false<T>, "Conversion not implemented");
return -1; // shut up static analysis
}
}
required includes, helpers and testing code:
#include <type_traits>
#include <limits>
#include <cmath>
#include <string>
#include <utility>
#include <stdexcept>
#include <format> | {
"domain": "codereview.stackexchange",
"id": 45063,
"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++, converting, c++20, casting",
"url": null
} |
c++, converting, c++20, casting
// helper needed to be able to do static_assert(false,...), e.g. to mark some constexpr if branches as todo
template <class...> constexpr std::false_type always_false{};
// another helper
template <typename T>
std::string typeToString()
{
if constexpr (std::is_same_v<T, bool>)
return "boolean";
if constexpr (std::is_same_v<T, uint8_t>)
return "uint8";
if constexpr (std::is_same_v<T, uint16_t>)
return "uint16";
if constexpr (std::is_same_v<T, uint32_t>)
return "uint32";
if constexpr (std::is_same_v<T, uint64_t>)
return "uint64";
if constexpr (std::is_same_v<T, int8_t>)
return "int8";
if constexpr (std::is_same_v<T, int16_t>)
return "int16";
if constexpr (std::is_same_v<T, int32_t>)
return "int32";
if constexpr (std::is_same_v<T, int64_t>)
return "int64";
if constexpr (std::is_same_v<T, float>)
return "float";
if constexpr (std::is_same_v<T, double>)
return "double";
}
int main()
{
auto f = convertType<float>(3.);
auto f2 = convertType<float>(false);
auto i = convertType<unsigned int>(-1);
auto i2 = convertType<unsigned int>(-1.);
auto i3 = convertType<unsigned int>(1);
auto i4 = convertType<unsigned int>(std::numeric_limits<uint64_t>::max());
auto i5 = convertType<int64_t>(1LL);
auto b = convertType<bool>(4ULL);
auto d = convertType<double>(4ULL);
} | {
"domain": "codereview.stackexchange",
"id": 45063,
"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++, converting, c++20, casting",
"url": null
} |
c++, converting, c++20, casting
Answer: It is unclear what it does
I am sure there is a use case where this function does exactly what you want. However, without looking very closely at the source code of this function it is very hard to tell what conversions are being done.
First, the name convertType<>() is very generic. How does it convert? static_cast<>() also converts types. But clearly your functions does something different, but it doesn't tell me what.
Second, it's a very mixed bag. Sometimes it is exact, sometimes it rounds. Conversion of anything to bool is allowed for some reason. inf and nan are not handled explicitly. Interestingly, you can convert a nan from one float type to another, but trying to convert an inf results in an exception being thrown, even though the latter seems like it should be fine.
I would define exactly what this does and make sure the name reflects it. Maybe you even want multiple functions. For example, an exactConvert<>() to allow conversions that preserve the exact mathematical value, or a roundtripConvert<>() that allows values to round trip such that you get the original value back, rangeCheckConvert() that just checks that the value is in range of the new type but allows imprecise conversions, and so on.
I would strongly recommend forbidding conversions to and from bool, or alternatively treat it like a 1-bit integer, and for example don't allow 3.1415 to be converted to bool.
Correctness
Using sizeof(T) > sizeof(long) to decide whether to use llround() or lround() looks very fishy; tt's perfectly legal to have an architecture where sizeof(long long) == sizeof(long). Although I can't imagine lround() and llround() doing something different then.
The exact fixed-width integer types like std::uint64_t are optional parts of the standard, so they are not guaranteed to be defined.
C++23 introduced std::float16_t. When using this type, a 32-bits or larger integer is not always in range of that.
Write a proper test suite | {
"domain": "codereview.stackexchange",
"id": 45063,
"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++, converting, c++20, casting",
"url": null
} |
c++, converting, c++20, casting
Write a proper test suite
As J_H mentioned in the comments, your main() is not a substitute for a proper test suite. Also, you want to meticulously check all the corner cases, like denormals, values right at the edge of the source and destination type's ranges, and also check that exceptions are thrown in cases where they should. | {
"domain": "codereview.stackexchange",
"id": 45063,
"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++, converting, c++20, casting",
"url": null
} |
python, web-scraping
Title: Scraping the Divar.ir
Question: I've wrote a code to scrape the Divar, which is an equivalent of Ebay in Iran. I have a few questions:
Am I doing the error handling and logging ok?
Is there a better way to optimize this code? (note that the API is limited to 30 calls in a minute for page retrieval, but isn't limited by the post retrieval)
What's the best way to cache the data that has already been scraped before?
Here's the code:
import concurrent.futures
import datetime
import json
import logging
import os
from time import sleep
import requests
from requests.exceptions import ConnectionError, HTTPError, RequestException
from urllib3.exceptions import MaxRetryError
def fetch_json_data(token):
url = f'{BASE_URL}/posts/{token}'
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except RequestException as e:
logging.error(f"Failed to fetch data for token {token}: {str(e)}")
except json.JSONDecodeError as e:
logging.error(f"Failed to decode JSON for token {token}: {str(e)}")
def fetch_and_save_post(token, category, city_code):
j = fetch_json_data(token)
if j:
save_json(j, category, city_code, token)
def save_json(j, category, city_code, token):
json_path = f"{RESULTS_DIR}/category_{category}__city_{city_code}"
with open(f'{json_path}/{token}.json', 'w', encoding='utf-8') as f:
json.dump(j, f, ensure_ascii=False, indent=4)
logging.info(f"Saved: {token}")
print(f"saved {token}", end="\r") | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
python, web-scraping
def retrieve_page(url, json_payload, headers, MAX_RETRY_ATTEMPTS):
for _ in range(MAX_RETRY_ATTEMPTS):
try:
start_time = datetime.datetime.now()
res = requests.post(url, json=json_payload, headers=headers)
res.raise_for_status()
response_time = (datetime.datetime.now() - start_time).total_seconds()
# Adjust sleep time dynamically based on response time
sleep_time = max(0.6, 2 - response_time)
sleep(sleep_time)
return res.json()
except (RequestException, MaxRetryError, ConnectionError, HTTPError) as e:
logging.error(f"An error occurred: {str(e)}")
sleep(2)
def date_to_unix(DTS):
return int(datetime.datetime.strptime(DTS, "%Y-%m-%d %H:%M:%S").timestamp()) * 1_000_000
def scrape(city_code, category, date_time_str, MAX_PAGES, MAX_RETRY_ATTEMPTS):
unix_timestamp = date_to_unix(date_time_str)
last_post_date = unix_timestamp
headers = {
"Content-Type": "application/json"
}
url = f"{BASE_URL}/search/{city_code}/{category}"
page_count = 1
try:
while page_count <= MAX_PAGES:
json_payload = {
"json_schema": {
"category": {"value": category}
},
"last-post-date": last_post_date,
"page": page_count
}
data = retrieve_page(url, json_payload, headers, MAX_RETRY_ATTEMPTS)
if data is None:
break
if not data.get("web_widgets", {}).get("post_list"):
break
post_list = data["web_widgets"]["post_list"]
# TODO Use ThreadPoolExecutor for parallel scraping at the post level
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [] | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
python, web-scraping
for post in post_list:
if "action" in post["data"]:
if "token" in post["data"]["action"]["payload"]:
token = post["data"]["action"]["payload"]["token"]
futures.append(executor.submit(fetch_and_save_post, token, category, city_code))
for future in concurrent.futures.as_completed(futures):
pass # TODO I can add any post-level processing here if needed
last_post_date = data["last_post_date"]
logging.info(f"Page {page_count} scraped. Last post date = {last_post_date}")
page_count += 1
except KeyboardInterrupt:
logging.info("Scraping interrupted by user.")
except Exception as e:
logging.error(f"An unexpected error occurred: {str(e)}")
if __name__ == "__main__":
BASE_URL = "https://api.divar.ir/v8"
RESULTS_DIR = "Results"
category="apartment-rent"
city_code=2
# Configure logging
json_path = f"{RESULTS_DIR}/category_{category}__city_{city_code}/"
if not os.path.exists(json_path):
os.makedirs(json_path)
logging.basicConfig(filename=json_path+"scrape_log.log", level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
scrape(city_code=city_code, category=category, date_time_str="2023-09-11 10:30:00", MAX_PAGES=4, MAX_RETRY_ATTEMPTS=5) | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
python, web-scraping
Answer: That's an overall pleasant code to read. A bit of oddities here and there but nothing to be afraid off.
Logging
You're using the root logger for each of your calls, that may be fine for this purpose but if you ever try to reuse part of this code as a module, it may be unnecessary cumbersome to reconfigure / disable these logs. As such, logs are usually handled through the logger returned by logging.getLogger(__name__). This way, it is easier to repurpose through a call of
logging.config.dictConfig({
'version': 1,
'formatters': {'divar': {'format': '=> %(message)s'}},
'filters': {},
'handlers': {'divar': {'class': 'logging.StreamHandler', 'formatter': 'divar'}},
'loggers': {'divar': {'level': 'INFO', 'handlers': ['divar']}},
})
or disable completely with dictConfig({'version': 1, 'loggers': {'divar': {'handlers': []}}}) (assuming the module is named divar). This makes it far easier for users of your code to configure the logs to their needs.
And speaking of logs, I really don't like the line print(f"saved {token}", end="\r"). It is so great that you're using logging to not clutter the output of your code unnecessarily, just continue doing so. Use another logger if necessary and configure a logging.StreamHandler for it if you really want to see these messages, but do not print here. Even better, since you are now both logging and printing, you can consolidate the code to a single logger.info call, as long as the new logger is a child of your __name__ logger and propagate the messages.
I also like to define a top-level function:
@functools.lru_cache(maxsize=1)
def getLogger():
return logging.getLogger(__name__)
Although not really necessary since logging already caches the loggers it creates, I find it removes a bit of clutter from the code and ease overall readability.
Requests
A few quick comments about your usage of requests: | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
python, web-scraping
Using the json parameter of a request automatically adds the Content-Type: application/json header, you don't need to add it yourself
Using a requests.Session to perform your requests allows to reuse connections and reduce network-related overheads
As I started using a Session in the ThreadPoolExecutor, I got some warnings from urllib3 that the default connection pool was getting full and some requests were dropped: consider using an adapter that suits your needs.
While on the topic of adapters, consider using an urllib3.Retry object instead of rolling your own retry mechanism. Interesting parameters for you seems to be total, status_forcelist and backoff_factor. Or even, consider rolling your own subclass to always get a retry delay of 2 seconds.
Download folder and caching
I like to use pathlib.Path instead of os.path for managing the filesystem. I find it easier to, for instance, pass a folder around that I can create or explore whenever I see fit. I also like the utility methods such as .open on files that tend to remove some clutter compared to the more verbose os.path.
So consider creating your destination folder and pass it as a parameter to the fetch_and_save_post / save_json functions. This will simplify writing the output file and you can also check, before the download, if the destination file already exist.
Command line arguments
There are a few parameters, in your code, that I feel are meant to be changed regularly, based on context.
It would feel better if these parameters were parsed from the command-line (with sensible defaults) so it is easier to change them. For this purpose, the argparse module is a decent first step that will allow you to call your script using syntax such as
$ python divar.py
$ python divar.py --max-pages 5 --city-code 5
$ python divar.py -c cats -d OutputFolder -t "2023-06-01 00:00:00" -r 7
Proposed improvements
import json
import logging
import argparse
import concurrent.futures as parallel | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
python, web-scraping
from pathlib import Path
from datetime import datetime
from time import sleep, perf_counter
from functools import lru_cache
import requests
from requests.exceptions import BaseHTTPError, RequestException
POST_LOGGER = f'{__name__}.post'
WAIT_TIME_BETWEEN_RETRIES = 2.0 # API limits to 30 pages call per minutes
class Retry(requests.urllib3.Retry):
def get_backoff_time(self):
return WAIT_TIME_BETWEEN_RETRIES
@lru_cache(maxsize=1)
def getLogger():
return logging.getLogger(__name__)
def build_api_url(*route, unparse=requests.utils.urlunparse):
route = Path('/v8').joinpath(*route)
return unparse(('https', 'api.divar.ir', route.as_posix(), '', '', ''))
def download_post(session, token, folder):
logger = logging.getLogger(POST_LOGGER)
destination = folder.joinpath(f'{token}.json')
if destination.exists():
logger.info("Skipping token %s: file already exists", token)
return
try:
response = session.get(build_api_url('posts', token))
response.raise_for_status()
post = response.json()
except RequestException as e:
getLogger().error("Failed to fetch data for token %s: %s", token, e)
except json.JSONDecodeError as e:
getLogger().error("Failed to decode JSON for token %s: %s", token, e)
else:
with destination.open('w', encoding='utf-8') as f:
json.dump(post, f, ensure_ascii=False, indent=4)
logger.info("Saved: %s", token)
def retrieve_page(session, url, payload):
try:
response = session.post(url, json=payload)
response.raise_for_status()
return response.json()
except (RequestException, BaseHTTPError) as e:
getLogger().error("An error occurred: %s", e)
def extract_tokens(posts):
for post in posts:
try:
token = post['data']['action']['payload']['token']
except (TypeError, KeyError):
pass
else:
yield token | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
python, web-scraping
def scrape(city_code, category, last_post_date, result_directory, max_pages, max_retries):
search_url = build_api_url('search', str(city_code), category)
last_post_date = int(last_post_date.timestamp() * 1_000_000)
session = requests.Session()
retries = Retry(total=max_retries, allowed_methods=['GET', 'POST'])
adapter = requests.adapters.HTTPAdapter(max_retries=retries, pool_block=True)
session.mount('https://api.divar.ir/', adapter)
sleep_time = 0
for page_count in range(1, max_pages + 1):
sleep(sleep_time)
json_payload = {
'json_schema': {
'category': {'value': category}
},
'last-post-date': last_post_date,
'page': page_count
}
start_time = perf_counter()
data = retrieve_page(session, search_url, json_payload)
try:
post_list = data['web_widgets']['post_list']
except (TypeError, KeyError):
break
with parallel.ThreadPoolExecutor() as executor:
futures = [
executor.submit(download_post, session, token, result_directory)
for token in extract_tokens(post_list)
]
for future in parallel.as_completed(futures):
# TODO I can add any post-level processing here if needed
pass
last_post_date = data['last_post_date']
getLogger().info("Page %d scraped. Last post date is %d.", page_count, last_post_date)
# Adjust sleep time dynamically based on response time
elapsed_time = perf_counter() - start_time
sleep_time = max(0.2, WAIT_TIME_BETWEEN_RETRIES - elapsed_time)
def command_line_parser():
def date_parser(user_input):
return datetime.strptime(user_input, '%Y-%m-%d %H:%M:%S') | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
python, web-scraping
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--category', '--cat', '-c',
default='apartment-rent',
help='category of posts to search for')
parser.add_argument('--city-code', '--city', '--code', '-z',
type=int, default=2,
help='...')
parser.add_argument('--result-directory', '--directory', '-d',
type=Path, default=Path('Results'),
help='Directory in which to store scraping results')
parser.add_argument('--last-post-date', '--date', '--time', '-t',
type=date_parser, default=datetime.now(),
help='...')
parser.add_argument('--max-pages', '--pages', '-p',
type=int, default=4,
help='Amount of pages to scrape for')
parser.add_argument('--max-retries', '--retries', '-r',
type=int, default=5,
help='Amount of time a request will be retried when a download fails')
return parser
def main(argv=None):
args = command_line_parser().parse_args(argv)
folder = args.result_directory.joinpath(f'category_{args.category}__city_{args.city_code}')
folder.mkdir(parents=True, exist_ok=True)
# Configure logging
logging.basicConfig(
filename=folder.joinpath('scrape_log.log').as_posix(),
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger(POST_LOGGER).addHandler(logging.StreamHandler())
args = vars(args)
args['result_directory'] = folder
try:
scrape(**args)
except KeyboardInterrupt:
getLogger().info("Scraping interrupted by user.")
except Exception as e:
getLogger().error("An unexpected error occurred: %s", e)
raise
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 45064,
"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, web-scraping",
"url": null
} |
c++, numerical-methods
Title: Minimalistic implementation of Leapfrog integration algorithm
Question: Please review this C++ listing of an implementation of Leapfrog integration.
Was the algorithm implemented correctly?
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <random>
// Constants for Argon
constexpr double epsilon = 119.8; // Depth of the potential well (in K)
constexpr double sigma = 3.405; // Distance for zero potential (in Angstrom)
constexpr double mass = 39.948; // Mass of Argon (in amu)
struct Vector3D {
double x, y, z;
};
// Lennard-Jones potential function
double lj_potential(const Vector3D& r)
{
double r_mag = std::sqrt(r.x * r.x + r.y * r.y + r.z * r.z);
double s_over_r = sigma / r_mag;
double s_over_r6 = pow(s_over_r, 6);
return 4.0 * epsilon * (s_over_r6 * s_over_r6 - s_over_r6);
}
// Derivative of the Lennard-Jones potential
Vector3D lj_force(const Vector3D& r)
{
// Define a small distance for the derivative approximation
double dr = 1e-6;
Vector3D force;
std::vector<Vector3D> r_plus_dr = { r, r, r };
r_plus_dr[0].x += dr;
r_plus_dr[1].y += dr;
r_plus_dr[2].z += dr;
// The force is the negative derivative of the potential energy
force.x = -(lj_potential(r_plus_dr[0]) - lj_potential(r)) / dr;
force.y = -(lj_potential(r_plus_dr[1]) - lj_potential(r)) / dr;
force.z = -(lj_potential(r_plus_dr[2]) - lj_potential(r)) / dr;
return force;
}
// Update the 'accel' function
void accel(std::vector<Vector3D>& a, const std::vector<Vector3D>& x)
{
int n = x.size(); // number of points
for (int i = 0; i < n; i++)
{
auto force = lj_force(x[i]);
// use Lennard-Jones force law
a[i].x = -force.x / mass;
a[i].y = -force.y / mass;
a[i].z = -force.z / mass;
}
} | {
"domain": "codereview.stackexchange",
"id": 45065,
"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++, numerical-methods",
"url": null
} |
c++, numerical-methods
void leapstep(std::vector<Vector3D>& x, std::vector<Vector3D>& v, double dt) {
int n = x.size(); // number of points
std::vector<Vector3D> a(n);
accel(a, x);
for (int i = 0; i < n; i++)
{
v[i].x = v[i].x + 0.5 * dt * a[i].x; // advance vel by half-step
v[i].y = v[i].y + 0.5 * dt * a[i].y; // advance vel by half-step
v[i].z = v[i].z + 0.5 * dt * a[i].z; // advance vel by half-step
x[i].x = x[i].x + dt * v[i].x; // advance pos by full-step
x[i].y = x[i].y + dt * v[i].y; // advance pos by full-step
x[i].z = x[i].z + dt * v[i].z; // advance pos by full-step
}
accel(a, x);
for (int i = 0; i < n; i++)
{
v[i].x = v[i].x + 0.5 * dt * a[i].x; // and complete vel. step
v[i].y = v[i].y + 0.5 * dt * a[i].y; // and complete vel. step
v[i].z = v[i].z + 0.5 * dt * a[i].z; // and complete vel. step
}
}
// Initialize positions and velocities of particles
void initialize(std::vector<Vector3D>& x, std::vector<Vector3D>& v, int n_particles, double box_size, double max_vel) {
// Create a random number generator
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(-0.5, 0.5);
// Resize the vectors to hold the positions and velocities of all particles
x.resize(n_particles);
v.resize(n_particles);
// Initialize positions and velocities
for (int i = 0; i < n_particles; i++)
{
// Assign random initial positions within the box
x[i].x = box_size * distribution(generator);
x[i].y = box_size * distribution(generator);
x[i].z = box_size * distribution(generator);
// Assign random initial velocities up to max_vel
v[i].x = max_vel * distribution(generator);
v[i].y = max_vel * distribution(generator);
v[i].z = max_vel * distribution(generator);
}
} | {
"domain": "codereview.stackexchange",
"id": 45065,
"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++, numerical-methods",
"url": null
} |
c++, numerical-methods
int main() {
int n_particles = 100; // number of particles
double box_size = 10.0; // size of the simulation box
double max_vel = 0.1; // maximum initial velocity
double dt = 0.01; // time step
int n_steps = 10000; // number of time steps
// Positions and velocities of the particles
std::vector<Vector3D> x, v;
// Initialize the particles
initialize(x, v, n_particles, box_size, max_vel);
// Run the simulation
for (int step = 0; step < n_steps; step++) {
leapstep(x, v, dt);
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45065,
"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++, numerical-methods",
"url": null
} |
c++, numerical-methods
Answer: The leapfrog part itself seems correct.
Use a vector math library
Instead of creating your own Vector3D, use a library that implements a similar type for you, along with overloads for all the mathematical operations you want to do on them. That avoids you from having to spell out all the operations done on the individual components of those vectors. I personally favor GLM (although it is oriented towards graphics it works fine for 3D vectors), but there are many more.
Use exact calculations where possible
We use numerical integration because it is the only practical thing to do when you have a system of many particles. However, you should always favor exact solutions where possible. For example, instead of using a numerical derivative of the Lennard-Jones potential, you should be able to write an exact version. This will then avoid any issues like the choice of dr, which may or may not be right depending on r itself.
What kind of system is this simulating?
vnp already mentioned in the comments that he doesn't see how the particles interact. Indeed, the acceleration of each particle only depends in its distance to the origin of the system, not on any other particle.
What are the units? I see some comments after the declarations of sigma, epsilon and mass, which is great, and from that I can assume that particle positions are also in ångström? But then the box seems very small compared to the size of the well in the Lennard-Jones potential. Even more important, what about time?
Are particles meant to be kept inside the box? Are there periodic boundary conditions? There are lots of questions here. You should document all this in comments in your source code, and/or refer to a paper or other document describing exactly what you are trying to simulate. | {
"domain": "codereview.stackexchange",
"id": 45065,
"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++, numerical-methods",
"url": null
} |
c++, numerical-methods
Note that these questions are important for deciding whether your use of the leapfrog algorithm is correct: it is just an approximation, and there will are sources of errors. Whether those errors will dominate your results depend on the velocities, forces and the size of your timesteps.
Performance optimizations
While the leapfrom algorithm is implemented correctly, you are calculating the accelarations twice as often as necessary. Consider that the result of the second call to accel() will be the same as the first call to accel() in the next iteration of the for-loop in main().
Related to that: avoid creating a new std::vector holding accelerations for each timestep. Just declare a in main() at the same place you are declaring x and v, and pass it on to leapfrog() by reference.
Create structs to organize your data
There are several ways you can group related data together in structs. For example, you could create a struct System that holds all the data related to the system you are simulating, in particular the particles' positions, velocities and accelerations, a struct Parameters to group all the parameters like sigma, epsilon, n_particles, box_size and so on. You can then easily pass these to initialize() and leapfrog().
You can also create a struct Particle to hold all the data for one particle, so that you only need one std::vector<Particle> particles instead of multiple separate vectors. Usually this make for more intuitive code, but this may or may not be faster. | {
"domain": "codereview.stackexchange",
"id": 45065,
"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++, numerical-methods",
"url": null
} |
beginner, c, hangman
Title: Hangman game in C
Question: I am a beginner who wrote this simple Hangman game in C for fun and to practice programming. I am looking for advice on optimizing this code and making it adhere to best practices. Are there too many variables, conditionals, and loops?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
int main(void)
{
//get a word
char words[12][10] = {"depend", "rich", "twig", "godly", "fang", "increase", "breakable", "stitch", "pumped", "pine", "shrill", "cable"};
srand(time(NULL));
int r = rand() % 12;
char* word = words[r];
int length = strlen(word);
int maxIncorrect = 5;
char correct[26] = {'\0'};
char incorrect[26] = {'\0'};
int amountCorrect = 0;
int amountIncorrect = 0;
//repeat until maxIncorrect wrong guesses
while (amountIncorrect < maxIncorrect)
{
char guess = '\0';
bool inWord = false;
bool allCorrect = true;
printf("\n________________________________________\n\n");
//print blanks and correcly guessed letters
for (int i = 0; i < length; i++)
{
inWord = false;
for (int j = 0; j < 26; j++)
{
if (word[i] == correct[j])
{
inWord = true;
}
}
if (inWord)
{
printf("%c ", word[i]);
}
else
{
printf("_ ");
allCorrect = false;
}
}
//stop if all letters have been correctly guessed
if (allCorrect)
{
printf("\n\nCorrect!\n");
return 0;
}
//print incorrect guesses
printf("\n\nIncorrect guesses: ");
for (int i = 0; i < amountIncorrect; i++)
{
printf("%c", incorrect[i]);
}
printf("\n"); | {
"domain": "codereview.stackexchange",
"id": 45066,
"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, c, hangman",
"url": null
} |
beginner, c, hangman
printf("\n");
inWord = false;
bool valid = true;
printf("\n%i incorrect guesses remaining\n", maxIncorrect - amountIncorrect);
printf("Enter a single lowercase letter: ");
//get user's guess and check if it is valid (a lowercase letter that has not been guessed before)
scanf("%c%*c", &guess);
for (int i = 0; i < amountCorrect; i++)
{
if (guess == correct[i])
{
valid = false;
}
}
for (int i = 0; i < amountIncorrect; i++)
{
if (guess == incorrect[i])
{
valid = false;
}
}
if (guess < 97 || guess > 122)
{
valid = false;
}
//go back to top of loop guess is invalid
if (!valid)
{
printf("\nInvalid\n");
}
//check if guess is part of the word or not
else
{
for (int i = 0; i < length; i++)
{
if (guess == word[i])
{
inWord = true;
}
}
if (inWord == true)
{
correct[amountCorrect] = guess;
amountCorrect++;
}
else
{
incorrect[amountIncorrect] = guess;
amountIncorrect++;
}
}
}
printf("\nThe word was %s\n", word);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45066,
"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, c, hangman",
"url": null
} |
beginner, c, hangman
printf("\nThe word was %s\n", word);
return 0;
}
Answer: General Overview
This is pretty good for a beginner.
I see some best practices are already being followed such as placing single statements in an if statement within { and } as well as putting each variable on a new line and initializing it. The variable names are quite understandable.
The code could be more flexible and more modular.
When developing code it is a good idea to compile with switches that report possible errors such as the GCC -pedantic flag. When I compile this code I get the following warning messages:
main.c(11,11): warning: 'function': conversion from 'time_t' to 'unsigned int', possible loss of data
main.c(15,18): warning: 'initializing': conversion from 'size_t' to 'int', possible loss of data
Complexity
A general best practice in almost every programming language is that no function should be larger than a single screen in the editor or IDE. This generally means no function should be larger than 55 to 60 lines of code, in the current implementation the main function is 118 lines of code. The reason for this particular best practice is that anything more than one screen makes it very difficult to follow the logic of the function.
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program. In the current code main is the
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. | {
"domain": "codereview.stackexchange",
"id": 45066,
"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, c, hangman",
"url": null
} |
beginner, c, hangman
An example of code that could be a function:
//print blanks and correcly guessed letters
for (int i = 0; i < length; i++)
{
inWord = false;
for (int j = 0; j < 26; j++)
{
if (word[i] == correct[j])
{
inWord = true;
}
}
if (inWord)
{
printf("%c ", word[i]);
}
else
{
printf("_ ");
allCorrect = false;
}
}
Magic Numbers
There are Magic Numbers in the code function (12, 10, 5, 26), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
Flexibility
This code at the very beginning of main does not allow for additional words to be added to the list:
char words[12][10] = { "depend", "rich", "twig", "godly", "fang", "increase", "breakable", "stitch", "pumped", "pine", "shrill", "cable" };
srand(time(NULL));
int r = rand() % 12;
char* word = words[r];
A flexible alternative would be:
//get a word
const char *words[] =
{
"depend",
"rich",
"twig",
"godly",
"fang",
"increase",
"breakable",
"stitch",
"pumped",
"pine",
"shrill",
"cable"
};
size_t wordCount = sizeof(words) / sizeof(*words);
size_t r = rand() % wordCount;
char* word = words[r]; | {
"domain": "codereview.stackexchange",
"id": 45066,
"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, c, hangman",
"url": null
} |
beginner, c, hangman
This will allow you to add all the words you want and then calculate the size of the array of words.
*Note: The above code could be a function, but seeding the random number generator should probably be one of the first lines in the main function. * | {
"domain": "codereview.stackexchange",
"id": 45066,
"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, c, hangman",
"url": null
} |
c, generics
Title: Generic type data storage
Question: We have a module which can be used by user to store and load value of variables. Every variable has an index associated with it (in the shown code cample this is ommitted and index is instead the data type) which refers to index in data table.
Shown code below is a minimum working example of what we currently have. To store variable value user inputs data type (or variable index) and pointer to variable which he wants to store as arguemnts to write() function.
When user wants to load value of variable he will use read() function.
/* This is inside of module */
#include <stdint.h>
enum t {t_u8, t_s8, t_u16, t_s16, t_u32, t_s32, t_f};
static uint32_t data[7];
void write(enum t t, void *val)
{
switch (t) {
case t_u32:
case t_s32:
case t_f: data[t] = *((uint32_t *)val); break;
case t_u16:
case t_s16: data[t] = *((uint16_t *)val); break;
case t_u8:
case t_s8: data[t] = *((uint8_t *)val); break;
}
}
void read(enum t t, void *val)
{
switch (t) {
case t_u32:
case t_s32:
case t_f: *((uint32_t *)val) = *((uint32_t *)&data[t]); break;
case t_u16:
case t_s16: *((uint16_t *)val) = *((uint16_t *)&data[t]); break;
case t_u8:
case t_s8: *((uint8_t *)val) = *((uint8_t *)&data[t]); break;
}
}
/* User of module */
int main(void)
{
uint8_t u8 = 123;
int8_t s8 = -55;
uint16_t u16 = 4992;
int16_t s16 = -31829;
uint32_t u32 = 3009238113;
int32_t s32 = -123394810;
float f = -1234.99f;
write(t_u8, &u8); read(t_u8, &u8);
write(t_s8, &s8); read(t_s8, &s8);
write(t_u16, &u16); read(t_u16, &u16);
write(t_s16, &s16); read(t_s16, &s16);
write(t_u32, &u32); read(t_u32, &u32);
write(t_s32, &s32); read(t_s32, &s32);
write(t_f, &f); read(t_f, &f);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45067,
"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, generics",
"url": null
} |
c, generics
return 0;
}
We want this code to be as portable and simple and easy to understand as possible without adding a lot of complexity.
You can assume that val will always point to variable of correct type.
What are the dangers of this code? One issue I see is that strict aliasing rule is violated multiple times. Are there any other pitfalls present? How would you change write() and read() functions to improve them?
Answer: Answers to your questions
What are the dangers of this code?
Use of globals, as mentioned in coderodde's answer. What if you want two generic variables?
There is no way to tell which element(s) of data[] hold a valid value. The common solution is to use a tagged union, as shown in the second part of Bas Visscher's answer.
One issue I see is that strict aliasing rule is violated multiple times. Are there any other pitfalls present?
You have in fact not violated the strict aliasing rule. Each element of data[] is only accessed through one type of pointer, so there is never access through a pointer of a different type.
You also do not have any pointer alignment issues.
However, your intuition tells you this pointer casting is dangerous, and rightfully so; it is easy to make a mistake when doing this. It is better to avoid it, for example by using the aforementioned tagged union.
How would you change write() and read() functions to improve them?
First, avoid globals by passing a pointer to the generic variable you want to access to your read() and write() functions.
Then, it depends on what you want to use this for. If you know at compile time which member you want to access, like in write(t_u8, &u8), then I would create functions where the type is part of the name, like write_u8(&u8), or rather just define a union and use it directly:
union t {
uint8_t u8;
uint16_t u16;
…
};
union t data;
data.u8 = 42; // replaces write(t_u8, 42); | {
"domain": "codereview.stackexchange",
"id": 45067,
"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, generics",
"url": null
} |
c, generics
union t data;
data.u8 = 42; // replaces write(t_u8, 42);
If you don't know the type at compile time, then I would go for the tagged union approach from Bart Visscher's answer.
Consider using C++
If you are not forced to use C, consider using C++ instead. The advantage of C++ is that it allows you to write type-safe code. For example, you could use std::variant and rewrite your main() to:
using t = std::variant<std::uint8_t, …, float>;
int main()
{
uint8_t u8 = 123;
…
float f = -1234.99f;
t data;
data = u8; u8 = std::get<std::uint8_t>(data);
…
data = f; f = std::get<float>(data);
}
And it would automatically throw an exception at runtime if you did something like:
data = u8; std::get<float>(data); | {
"domain": "codereview.stackexchange",
"id": 45067,
"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, generics",
"url": null
} |
php, parsing, linux, docker
Title: Parsing gateway ip from `/proc/net/route` in a docker container
Question: In try to replicate the outcome of the following command sequence using php:
netstat -rn | grep "^0.0.0.0 " | cut -d " " -f10
I did this using a PHP script:
#!/usr/bin/env php
<?php
/**
* Xdebug ip detector for docker
* Copyright (C) 2023 Dimitrios Desyllas
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
$matches = [];
preg_match("/^\w*\s(00000000)\s(\w*)/m",file_get_contents("/proc/net/route"),$matches);
// At regex each () is also matxched seperately. In my case I have 2 matched groups therefore the secodn match is my ip hex encoded
$ip = $matches[2];
$ip = str_split($ip,2);
$ip = array_reverse($ip);
$ip = array_reduce($ip,function($acc,$item){
return $acc.intval($item,16).".";
},"");
$ip = rtrim($ip,'.');
echo $ip;
Is this the way to parse the ip directly from /proc/net/route?
This script is intended to be run inside a docker container that also ships with PHP and xdebug.
Answer: Reading the gateway IP
I'm not an expert of reading routing info, but:
Linuxtopia's article on Linux Filesystem Hierarchy confirms that /proc/net/route contains the Kernel routing table.
The format assumed by the posted code matches what I get on recent Linux machine, and also on a pretty old Linux machine. | {
"domain": "codereview.stackexchange",
"id": 45068,
"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, parsing, linux, docker",
"url": null
} |
php, parsing, linux, docker
So I think your method is fine.
Another alternative to reading from /proc/net/route would be to call the netstat command as you mention in your post and parse its output.
Reading the gateway IP as a hex string
This functionality seems a good candidate to wrap into a function, having this "shape":
# Returns the gateway IP address as a hex string of reversed bytes,
# for example 0100A8C0, or null if not possible
function read_gateway_ip_hex_string() {
# ...
}
I find the preg_match solution a bit hacky.
I find it more natural to consider the structure of the file as a table with columns, and get the 2nd column when the 1st column is 00000000:
function read_gateway_ip_hex_string() {
$fn = fopen("/proc/net/route", "r");
while(! feof($fn)) {
$line = fgets($fn);
$parts = preg_split("/\s+/", $line);
if ($parts[1] == "00000000") {
$ip_hex_string = $parts[2];
break;
}
}
fclose($fn);
return $ip_hex_string;
}
It's more verbose than the posted code,
but I think it's easier to understand how it works.
Converting a hex string to dotted decimals
Similarly to getting the hex string,
I think this is also a good opportunity to wrap this functionality into a reusable and testable function:
function ip_hex_string_to_dotted_decimals($ip_hex_string) {
$ip_bytes = array_reverse(
array_map(fn($s): int => intval($s, 16),
str_split($ip_hex_string, 2)));
return implode('.', $ip_bytes);
}
Instead of the array_reduce + rtrim combo, this one maps array items and then joins them, which I find easier to understand.
Putting it together
From the building blocks in functions,
the main part of the program becomes:
$ip_hex_string = read_gateway_ip_hex_string();
if (is_null($ip_hex_string)) {
# TODO: do something helpful!
} else {
$ip = ip_hex_string_to_dotted_decimals($ip_hex_string);
echo $ip;
} | {
"domain": "codereview.stackexchange",
"id": 45068,
"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, parsing, linux, docker",
"url": null
} |
c++, reinventing-the-wheel, pointers, c++20
Title: C++ std::shared_ptr implementation
Question: Took a shot at implementing std::shared_ptr, with a thread-safe refcount and weak count. Didn't do weak_ptr, I'm doing this for learning purposes, and I think from an educational standpoint there's not much to learn from adding it.
Also tried to implement the "we know where you live" optimization, with the control block and the underlying memory allocated together in makeShared, but it feels sloppy and error prone and would love advice on if it can be done more cleanly.
#include <atomic>
#include <iostream>
template <typename T>
class ControlBlock {
public:
ControlBlock():
m_ptr{nullptr},
m_ref_count{0},
m_weak_count{0}
{}
ControlBlock(T* ptr):
m_ptr{ptr},
m_ref_count{1},
m_weak_count{0}
{}
void add_reference() {
m_ref_count.fetch_add(1, std::memory_order_relaxed);
}
void add_weak_reference() {
m_weak_count.fetch_add(1, std::memory_order_relaxed);
}
void remove_reference() {
// The release memory barrier ensures all operations on this thread are
// visible to other threads before a decrement happens
if (m_ref_count.fetch_sub(1, std::memory_order_release) == 1) {
// the acquire memory barrier makes sure we delete the pointer
// and control block only after the ref count has gone to 0
std::atomic_thread_fence(std::memory_order_acquire);
m_ptr->~T();
if (m_weak_count.load(std::memory_order_relaxed) == 0) {
delete this;
}
}
}
void remove_weak_reference() {
if (m_weak_count.fetch_sub(1, std::memory_order_release) == 1) {
std::atomic_thread_fence(std::memory_order_acquire);
if (m_ref_count.load(std::memory_order_relaxed) == 0) {
delete this;
}
}
}
T* get() const noexcept {
return m_ptr;
} | {
"domain": "codereview.stackexchange",
"id": 45069,
"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++, reinventing-the-wheel, pointers, c++20",
"url": null
} |
c++, reinventing-the-wheel, pointers, c++20
T* get() const noexcept {
return m_ptr;
}
std::size_t use_count() const noexcept {
return m_ref_count.load(std::memory_order_relaxed);
}
std::size_t weak_count() const noexcept {
return m_weak_count.load(std::memory_order_relaxed);
}
template<typename... Args>
static ControlBlock* create (Args&&... args) {
std::size_t cb_size = sizeof(ControlBlock);
std::size_t t_size = sizeof(T);
std::size_t t_alignment = alignof(T);
std::size_t remainder = cb_size % t_alignment;
std::size_t padding = remainder ? (t_alignment - remainder) : 0;
std::size_t t_offset = cb_size + padding;
char* chunk = static_cast<char*>(::operator new(cb_size + t_size));
T* ptr = nullptr;
try {
ptr = new (chunk + t_offset) T(std::forward<Args>(args)...);
} catch (...) {
::operator delete (chunk);
throw;
}
try {
return new(chunk) ControlBlock{ptr};
} catch(...) {
ptr->~T();
::operator delete(chunk);
throw;
}
}
private:
T* m_ptr;
std::atomic<std::size_t> m_ref_count;
std::atomic<std::size_t> m_weak_count;
};
template<typename T>
class SharedPtr {
public:
SharedPtr() noexcept : cb{new ControlBlock<T>()} {}
SharedPtr(T* item) : cb{new ControlBlock<T>{item}} {}
template<typename U>
requires(std::is_convertible_v<U*, T*>)
SharedPtr(SharedPtr<U>&& other) noexcept
: SharedPtr{other.cb}
{
other.cb = nullptr;
}
SharedPtr(const SharedPtr& other) : cb{other.cb} {
cb->add_reference();
}
SharedPtr (SharedPtr&& other) : cb{other.cb} {
other.cb = nullptr;
}
SharedPtr& operator=(const SharedPtr& other) {
if (this == &other) return *this;
SharedPtr temp{other};
swap(temp);
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 45069,
"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++, reinventing-the-wheel, pointers, c++20",
"url": null
} |
c++, reinventing-the-wheel, pointers, c++20
SharedPtr temp{other};
swap(temp);
return *this;
}
SharedPtr& operator=(SharedPtr&& other) {
if (this == &other) return *this;
SharedPtr temp{std::move(other)};
swap(temp);
return *this;
}
int use_count() const noexcept {
return cb -> use_count();
}
void swap(SharedPtr& other) noexcept {
std::swap(cb, other.cb);
}
T* reset() {
T* result = get();
SharedPtr new_ptr;
swap(new_ptr);
return result;
}
T* reset(T* new_val) {
T* result = get();
SharedPtr new_ptr{new_val};
swap(new_ptr);
return result;
}
T* get() const noexcept {
return cb->get();
}
T& operator*() const {
return *get();
}
T* operator->() const noexcept {
return get();
}
explicit operator bool() const noexcept {
return get() != nullptr;
}
~SharedPtr() {
if (cb) {
cb -> remove_reference();
}
}
private:
ControlBlock<T>* cb;
// Make all specializations of SharedPtr friends
// with one another
template<typename U>
friend class SharedPtr;
// Make makeShared a friend of the SharedPtr class
// so we can use the private ControlBlock constructor
template<typename U, typename...Args>
friend SharedPtr<U> makeShared(Args&&... args);
SharedPtr(ControlBlock<T>* cb) : cb{cb} {}
template <typename U>
SharedPtr(ControlBlock<U>* cb) :
cb{reinterpret_cast<ControlBlock<T>*>(cb)} {}
};
template<typename T, typename... Args>
SharedPtr<T> makeShared(Args&&... args) {
auto cb = ControlBlock<T>::create(std::forward<Args>(args)...);
return SharedPtr<T>{cb};
} | {
"domain": "codereview.stackexchange",
"id": 45069,
"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++, reinventing-the-wheel, pointers, c++20",
"url": null
} |
c++, reinventing-the-wheel, pointers, c++20
Added some unit tests as well, based on the example behavior on cppreference, but again would love some advice on how to really stress test this, especially since the control block creation is so manual and error prone.
// Have to define the test module first, always.
#define BOOST_TEST_MODULE sharedptrtest
#ifdef BOOST_TEST_DYN_LINK
# include <boost/test/unit_test.hpp>
#else
# include <boost/test/included/unit_test.hpp>
#endif // BOOST_TEST_DYN_LINK
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>
#include "SharedPtr.h"
struct Foo {
int id{0};
Foo (int i = 0) : id{i} {}
~Foo() = default;
int val() {
return id;
}
};
struct B
{
virtual ~B() = default;
virtual int val() const {return 0;}
};
struct D : B
{
D() { }
~D() {}
int val() const override {
return 2;
}
};
BOOST_AUTO_TEST_CASE(default_constructor_test)
{
{
SharedPtr<Foo> s1;
}
}
BOOST_AUTO_TEST_CASE(runtime_poly)
{
SharedPtr<B> p = makeShared<D>();
assert(p -> val() == 2);
}
BOOST_AUTO_TEST_CASE(copy_constructor_test)
{
SharedPtr<Foo> s1(new Foo{10});
BOOST_CHECK_EQUAL(s1.use_count(), 1);
{
SharedPtr<Foo> s2{s1};
BOOST_CHECK_EQUAL(s1.use_count(), 2);
}
BOOST_CHECK_EQUAL(s1.use_count(), 1);
}
BOOST_AUTO_TEST_CASE(copy_assigment_test)
{
SharedPtr<Foo> s1(new Foo{10});
BOOST_CHECK_EQUAL(s1.use_count(), 1);
{
SharedPtr<Foo> s2 = s1;
BOOST_CHECK_EQUAL(s1.use_count(), 2);
}
BOOST_CHECK_EQUAL(s1.use_count(), 1);
}
BOOST_AUTO_TEST_CASE(move_assigment_test)
{
SharedPtr<Foo> s1(new Foo{10});
BOOST_CHECK_EQUAL(s1.use_count(), 1);
SharedPtr<Foo> s2 = std::move(s1);
BOOST_CHECK_EQUAL(s2.use_count(), 1);
}
BOOST_AUTO_TEST_CASE(reset_test)
{
SharedPtr<Foo> s1(new Foo{10});
BOOST_CHECK_EQUAL(s1->val(), 10);
BOOST_CHECK_EQUAL(s1.use_count(), 1); | {
"domain": "codereview.stackexchange",
"id": 45069,
"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++, reinventing-the-wheel, pointers, c++20",
"url": null
} |
c++, reinventing-the-wheel, pointers, c++20
s1.reset(new Foo{20});
BOOST_CHECK_EQUAL(s1->val(), 20);
BOOST_CHECK_EQUAL(s1.use_count(), 1);
s1.reset();
BOOST_CHECK_EQUAL(s1.use_count(), 0);
}
BOOST_AUTO_TEST_CASE(swap_test)
{
SharedPtr<Foo> s1 = makeShared<Foo>(100);
SharedPtr<Foo> s2 = makeShared<Foo>(200);
BOOST_CHECK_EQUAL(s1->val(), 100);
BOOST_CHECK_EQUAL(s2->val(), 200);
BOOST_CHECK_EQUAL(s1.use_count(), 1);
BOOST_CHECK_EQUAL(s1.use_count(), 1);
s1.swap(s2);
BOOST_CHECK_EQUAL(s1->val(), 200);
BOOST_CHECK_EQUAL(s2->val(), 100);
BOOST_CHECK_EQUAL(s1.use_count(), 1);
BOOST_CHECK_EQUAL(s1.use_count(), 1);
}
BOOST_AUTO_TEST_CASE(get_and_deref_test)
{
int* pInt = new int{42};
SharedPtr shInt = makeShared<int>(42);
BOOST_CHECK_EQUAL(*pInt, *shInt);
BOOST_CHECK_EQUAL(*pInt, *(shInt.get()));
}
BOOST_AUTO_TEST_CASE(bool_test)
{
SharedPtr<int> ptr;
BOOST_CHECK(!(static_cast<bool>(ptr)));
ptr = makeShared<int>(7);
BOOST_CHECK((static_cast<bool>(ptr)));
}
```
Answer: Make ControlBlock's constructors noexcept
The constructors of ControlBlock are very trivial and never throw an exception, so mark these constructors noexcept. That then greatly simplifies create(), where you now only need one try-catch block:
try {
T *ptr = new (chunk + t_offset) T(std::forward<Args>(args)...);
return new(chunk) ControlBlock{ptr};
} catch (...) {
::operator delete (chunk);
throw;
}
Incorrect handling of alignment restrictions
There are two obvious mistakes in handling the alignment of T in create():
You don't reserve any memory for the padding.
You calculate the offset before you even know what address chunk will point to. | {
"domain": "codereview.stackexchange",
"id": 45069,
"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++, reinventing-the-wheel, pointers, c++20",
"url": null
} |
c++, reinventing-the-wheel, pointers, c++20
You should first allocate cb_size + t_size + t_alignment bytes. Then once you have the pointer to that allocation, you can check how much you have to add to chunk + cb_size to get an address that is correctly aligned for T.
Missing deletion of T
Unless you created the ControlBlock and the T object in one allocation, then there is a delete m_ptr missing. Note that you have to be careful to not both call m_ptr->~T() and delete m_ptr in that case.
Unnecessary checks for self-assignment
You added checks for self-(move)-assignment and early out in those cases. But without these checks, your code is still correct, thanks to the fact that you have used the copy-and-swap idiom. You might do more work than necessary if you do a self-assignment, but consider that it is very unlikely that someone assigns an object to itself, and you actually slightly reduce the performance of the normal case.
The move-assignment operator can be made noexcept
Since the move-assignment operator just does a move-construction and a swap, both of which are noexcept, the move-assignment operator itself can also be made noexcept.
Assignment operators should also be templates
For the same reason you made the move constructor a template, the assignment operators should also be templates, with the same requires clause.
Missing some functionality
Didn't do weak_ptr, I'm doing this for learning purposes, and I think from an educational standpoint there's not much to learn from adding it. | {
"domain": "codereview.stackexchange",
"id": 45069,
"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++, reinventing-the-wheel, pointers, c++20",
"url": null
} |
c++, reinventing-the-wheel, pointers, c++20
I think you are wrong about that. Implementing all the member functions of std::weak_ptr correctly is perhaps not rocket science, but you don't know about all the corner cases you might have to handle until you try it. Also consider that without it, you can't actually test correct handling of weak references in your test suite.
There is also other functionality missing that is in std::shared_ptr, like support for arrays, owner_before(), the member types element_type and weak_type, other non-member functions that work with std::shared_ptr, std::atomic<std::shared_ptr>, support for custom allocators and deleters, constructors/assignment operators that take a std::unique_ptr as argument, and more.
Add unit tests for ControlBlock as well
In addition to testing SharedPtr, you should add unit tests for ControlBlock as well, just to make sure the internals of your code are also working as you, the developer, are expecting. | {
"domain": "codereview.stackexchange",
"id": 45069,
"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++, reinventing-the-wheel, pointers, c++20",
"url": null
} |
performance, rust, webassembly
Title: ShareImage: Place Texts on Images to generate Social Media Preview Images
Question: ShareImage is a project which lets you use an Image ("Template") and place text over it, to generate Social Media Preview Images, the ones used in the og:image tag. The project is available at the regraphic/si-rs repo. Here's the src/lib.rs file (which contains all the code):
use image::{DynamicImage, GenericImage, GenericImageView, Rgb, Rgba};
use reqwest;
use rusttype::{point, Font, Scale};
use wasm_bindgen::prelude::*;
/// Represents a font used for text rendering.
#[wasm_bindgen]
#[derive(Clone)]
pub struct SiFont {
font: Option<Font<'static>>,
}
#[wasm_bindgen]
impl SiFont {
/// Constructor for SiFont, asynchronously loading font data from a URL or using provided bytes.
///
/// # Arguments
///
/// * `src` - The URL of the font file.
/// * `src_bytes` - Optional bytes of the font file.
///
/// # Returns
///
/// A `SiFont` instance containing the loaded font.
#[wasm_bindgen(constructor)]
#[cfg(feature = "async")]
pub async fn new(src: &str, src_bytes: Option<Vec<u8>>) -> Result<SiFont, JsValue> {
// Load font data from either URL or provided bytes.
let font_data = match src_bytes {
Some(bytes) => bytes.to_vec(),
None => reqwest::get(src)
.await
.expect("Could not fetch font")
.bytes()
.await
.expect("Could not extract font")
.to_vec(),
};
let font = Font::try_from_vec(font_data);
Ok(SiFont { font })
} | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
/// Constructor for SiFont, synchronously loading font data from a URL or using provided bytes.
///
/// # Arguments
///
/// * `src` - The URL of the font file.
/// * `src_bytes` - Optional bytes of the font file.
///
/// # Returns
///
/// A `SiFont` instance containing the loaded font.
#[cfg(feature = "blocking")]
pub fn new(src: &str, src_bytes: Option<Vec<u8>>) -> SiFont {
// Load font data from either URL or provided bytes.
let font_data = match src_bytes {
Some(bytes) => bytes.to_vec(),
None => reqwest::blocking::get(src)
.expect("Could not fetch font")
.bytes()
.expect("Could not extract font")
.to_vec(),
};
let font = Font::try_from_vec(font_data.to_vec());
SiFont { font }
}
}
/// Represents an image with text rendering capabilities.
#[wasm_bindgen]
#[derive(Clone)]
pub struct SiImage {
font: SiFont,
image: DynamicImage,
height: u32,
width: u32,
} | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
#[wasm_bindgen]
impl SiImage {
/// Constructor for SiImage, asynchronously loading an image from a URL or using provided bytes.
///
/// # Arguments
///
/// * `image_url` - The URL of the image file.
/// * `font` - A `SiFont` instance for text rendering.
/// * `image_bytes` - Optional bytes of the image file.
///
/// # Returns
///
/// A `SiImage` instance containing the loaded image and font.
#[wasm_bindgen(constructor)]
#[cfg(feature = "async")]
pub async fn new(image_url: &str, font: SiFont, image_bytes: Option<Vec<u8>>) -> SiImage {
// Load image data from either URL or provided bytes.
let image_data = match image_bytes {
Some(bytes) => bytes.to_vec(),
None => reqwest::get(image_url)
.await
.expect("Could not fetch image")
.bytes()
.await
.expect("Could not extract image")
.to_vec(),
};
let image = image::load_from_memory(&image_data).expect("Could not decode image");
let d = image.clone().dimensions();
Self {
font,
image,
height: d.1,
width: d.0,
}
} | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
/// Constructor for SiImage, synchronously loading an image from a URL or using provided bytes.
///
/// # Arguments
///
/// * `image_url` - The URL of the image file.
/// * `font` - A `SiFont` instance for text rendering.
/// * `image_bytes` - Optional bytes of the image file.
///
/// # Returns
///
/// A `SiImage` instance containing the loaded image and font.
#[cfg(feature = "blocking")]
pub fn new(image_url: &str, font: SiFont, image_bytes: Option<Vec<u8>>) -> SiImage {
// Load image data from either URL or provided bytes.
let image_data = match image_bytes {
Some(bytes) => bytes.to_vec(),
None => reqwest::blocking::get(image_url)
.expect("Could not fetch image")
.bytes()
.expect("Could not extract image")
.to_vec(),
};
let image = image::load_from_memory(&image_data).expect("Could not decode image");
let d = image.clone().dimensions();
Self {
font,
image,
height: d.1,
width: d.0,
}
} | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
/// Render text onto the image.
///
/// # Arguments
///
/// * `text` - The text to render.
/// * `text_scale` - The scale factor for the text.
/// * `pos_x` - The X-coordinate for text placement.
/// * `pos_y` - The Y-coordinate for text placement.
/// * `color` - Optional text color in hexadecimal format (e.g., "#RRGGBB").
///
/// # Returns
///
/// A new `SiImage` instance with the rendered text.
#[wasm_bindgen]
pub fn text(
&mut self,
text: &str,
text_scale: f32,
pos_x: f32,
pos_y: f32,
color: Option<String>,
) -> SiImage {
let mut image = self.image.clone();
let font = self
.font
.font
.as_ref()
.ok_or("Error loading font")
.expect("Could not decode/load font");
let scale = Scale::uniform(text_scale);
let v_metrics = font.v_metrics(scale);
let offset = point(pos_x, pos_y + v_metrics.ascent); | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
for glyph in font.layout(text, scale, offset) {
if let Some(bb) = glyph.pixel_bounding_box() {
glyph.draw(|x, y, v| {
let x = x as i32 + bb.min.x;
let y = y as i32 + bb.min.y;
let pixel = image.get_pixel(x as u32, y as u32);
let parsed_color = match color.clone() {
Some(c) => hex_to_rgb(&c).unwrap_or(Rgb([0, 0, 0])),
None => Rgb([0, 0, 0]),
};
let new_pixel = Rgba([
(((parsed_color[0] as f32 * (v)) as f32) + (pixel[0] as f32 * (1.0 - v)))
as u8,
((parsed_color[1] as f32 * (v)) as f32 + (pixel[1] as f32 * (1.0 - v)))
as u8,
((parsed_color[2] as f32 * (v)) as f32 + (pixel[2] as f32 * (1.0 - v)))
as u8,
(pixel[3] as f32 * (v)) as u8,
]);
image.put_pixel(x as u32, y as u32, new_pixel);
});
}
}
self.image = image.clone();
SiImage {
font: self.font.clone(),
image,
height: self.height,
width: self.width,
}
}
/// Get the image data as bytes in PNG format.
///
/// # Returns
///
/// A `Vec<u8>` containing the image data.
#[wasm_bindgen(getter)]
pub fn as_bytes(&self) -> Vec<u8> {
let mut v = std::io::Cursor::new(Vec::new());
self.image
.write_to(&mut v, image::ImageFormat::Png)
.expect("Could not write bytes");
v.into_inner()
} | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
/// Set the font for text rendering.
///
/// # Arguments
///
/// * `font` - A `SiFont` instance for text rendering.
///
/// # Returns
///
/// A new `SiImage` instance with the updated font.
#[wasm_bindgen(setter, js_name = "font")]
pub fn font(&mut self, font: SiFont) -> SiImage {
self.font = font;
SiImage {
font: self.font.clone(),
image: self.image.clone(),
height: self.height,
width: self.width,
}
}
/// Get the height of the image.
#[wasm_bindgen(getter)]
pub fn height(&self) -> u32 {
self.height
}
/// Get the width of the image.
#[wasm_bindgen(getter)]
pub fn width(&self) -> u32 {
self.width
}
}
/// Converts a hexadecimal color string (e.g., "#RRGGBB") to an `Rgb<u8>` color.
///
/// # Arguments
///
/// * `hex` - The hexadecimal color string.
///
/// # Returns
///
/// An `Option<Rgb<u8>>` representing the RGB color.
pub fn hex_to_rgb(hex: &str) -> Option<Rgb<u8>> {
let hex = hex.trim_start_matches('#'); // Remove "#" if present
if hex.len() == 6 {
let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
let b = u8::from_str_radix(&hex[4..6], 16).ok()?;
Some(Rgb([r, g, b]))
} else if hex.len() == 3 {
let r = u8::from_str_radix(&hex[0..1].repeat(2), 16).ok()?;
let g = u8::from_str_radix(&hex[1..2].repeat(2), 16).ok()?;
let b = u8::from_str_radix(&hex[2..3].repeat(2), 16).ok()?;
Some(Rgb([r, g, b]))
} else {
Some(Rgb([0, 0, 0]))
}
}
The code is primarily the base for the shareimage (Node.js) and sideno (Deno) projects and is ~6x faster than the existing ones. However, I'm open to any feedback on it. | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
Answer: You clone the Vec<u8> unnecessarily
In each of the new() methods, you have an Option<Vec<u8>>. Then you pattern-match on it and get Vec<u8> (or fetch the bytes from the network). Then you call .to_vec() on that, which effectively clones the Vec, unnecessarily since you already have a Vec and you don't need it twice.
You do it again unnecessarily
In the blocking version of SiFont::new() you call .to_vec() on before Font::try_from_vec() again (either on the bytes from the network or on the Vec from the parameter), again cloning it for no need.
There's a more efficient way to convert Bytes to Vec<u8>
reqwests bytes() gives you a Bytes. You need a Vec<u8>. Since Bytes derefs to [u8], you can call slice's methods on it, including to_vec(). However, <[T]>::to_vec() will always allocate a new Vec; there is a more efficient way to do this conversion.
You can use the impl From<Bytes> for Vec<u8>. This avoids allocating a new Vec if the Bytes instances uniquely owns the data (it is not shared), and I think (not sure) it also avoids a copy if the data is already in the right place. Since both are likely (perhaps will always) to hold when the Bytes came from reqwest, there can be a significant saving here.
You clone the image unnecessarily
When calling dimensions() on it. This is not needed, dimensions() takes &self.
Don't force callers into allocating
SiFont's constructor actually need an owned Vec<u8> for the bytes. But SiImage's constructor does not. All it needs is &[u8], for image::load_from_memory(). Therefore, it should take &[u8], to avoid forcing a caller that only has a slice (for example, because the image is embedded into the binary) to allocate and copy. This also allows you to avoid the conversion of Bytes to Vec (although, if done correctly as per the previous note, should be cheap). | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
Using the data from reqwest::get() as a slice without getting a lifetime error might be tricky, though, but you can use a little trick: declare the Bytes response before the match, so its lifetime is long enough, but only initialize it in the match (conditionally-initialize it). Then, return a reference to it from the match, and store it in a variable. The compiler knows that in all code paths, it is initialized before accessed (if accessed).
Let the caller decide whether to clone
In SiImage::text(), either take &mut self, update the image in place and return nothing (better), or take self and return Self (builder-like pattern). You can also take &mut self and return &mut Self, for chaining. But either way, let the caller decide if they want to clone. They know better than you if they need two copies of the image.
Currently, your code does the worst of both worlds: it clones the image, updates the clone then clones it again to also update the original. This way, you always clone twice for no reason: if the caller only needs the updated image, it needs to update in-place (no clone at all), but you clone twice; and if the caller wants both the original and the updated image, it still needs to clone before to keep the original image (so, three clones instead of just one).
You clone color unnecessarily too
In match color.clone().
This time, this actually has a reason (the code won't compile without it), but it is easily fixable: match on &color instead of on color, to not move it.
...and you should take Option<&str> for it, anyway
Since you don't really need it as a String, so again, let the caller decide.
Extract the color parsing out of the loop
You need to do it once and not more.
Also, there are some more comments on color parsing if it would be performant sensitive. They would make it less idiomatic but faster. Currently it is performance sensitive. If you'll extract it out of the loop it won't be anymore. | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
The rest are not performance notes.
Handle errors gracefully
Instead of panicking in the case of errors, return proper Results.
Features should be additive
Imagine what happens if someone enables both the async and the blocking features. It doesn't even have to be the same person: one dependency of you uses the async version and thus enables the async feature, and another one uses the blocking interface and thus enables the blocking feature. They work great in isolation, until you try to add both to your project and suddenly it fails to compile with a mysterious error, since Cargo is trying to unify the features.
This is why features should be additive; that is, enabling a feature should not change API, but add API. With your code this is not the case: enabling the features changes the asyncness of a function.
You should make it two functions, one async behind the async feature gate and the other sync behind the blocking feature gate. You can name them new() and new_blocking(), or new_async() and new(), or new_async() and new_blocking() (or whatever you want).
One constructor is just not enough
It's nice to have only one constructor, but in this case it just complicates things. There are two ways to construct a SiFont and a SiImage, one from bytes and the other from the network. Trying to unify them just doesn't work. Everyone wanting to construct from bytes will need to provide a dummy url, and everyone wanting a network request will need to provide None for the bytes (of course, this could also be the opposite. or you could make both Options, but then you have to handle the error of both absent or both present at runtime). And it's also easy to have both a URL and bytes by mistake, and the code perhaps won't do what you want it to do. | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
Instead, make illegal states irrepresentable. Have two constructor functions, from_bytes() and from_network(). For WebAssembly, you can overload the constructor to determine if it was given bytes or string (although I don't think wasm_bindgen can do that automatically), but IMHO it will be clearer to leave the constructor for one of the options and use a static factory function for the other (or use static functions for both!).
Destructure the dimensions immediately
After let d = image.clone().dimensions(), it is not immediately clear what is the width and what is the height (also, I'd use a more descriptive name than d, but this is arguable). It is much better to destructure it on the same line: let (width, height) = image.clone().dimensions().
Handle errors when they occur, not later
Instead of storing Option<Font>, store Font and handle the case of an invalid font when the font is loaded. This way, you also don't litter every access with expect().
You may want to differentiate between "no color given" and "invalid color was given"
Currently, you use black as a fallback for both. Consider instead returning an error in the case of an invalid color.
text() is not a clear name
And also, I prefer method names to be verbs. paint_text() would be more appropriate IMHO.
Neither as_ nor getter
Your as_bytes() method violates two expectations of people: first, it is named as_. By convention, as_ prefix should be reserved to operations that are near free. It is not. It is expensive. It should be named to_bytes(). Second, it is a getter (in JavaScript). People expect getters to be cheap. It is not. And as the tip of the iceberg, it is a getter named as_bytes, which is probably not what you intended (you probably wanted to call it bytes).
font() should not clone too
Just as with text(), let the caller decide. Either take &mut self and update in place, or take self and return Self, but don't do both.
font() sounds like a getter | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
performance, rust, webassembly
font() sounds like a getter
By convention, you should name it set_font(). Unless you go for a builder-style API (which might as well be what you're trying to do, I'm not sure). | {
"domain": "codereview.stackexchange",
"id": 45070,
"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, rust, webassembly",
"url": null
} |
c++, recursion, time-limit-exceeded, dynamic-programming
Title: Find largest sum not involving consecutive values
Question: There is a question to basically find the largest sum in an array, such that no two elements are chosen adjacent to each other. The concept is to recursively calculate the sum, while considering and not considering every element, and skipping an element depending on whether the previous element was selected or not.
I understand that this problem requires the use of Dynamic Programming, but doing so still gives me a TLE. Although my code is very similar to the solution code, I cannot figure out why am I getting a TLE (>1.9 seconds). The constraints are given that n >= 1, and so initialising the DP array to 0's shouldn't be a problem in my opinion.
Algorithmically, I think that the two codes below achieve the same task: processing each element, then either considering it in the sum (in this case, the next recursive call is done for the (i+2)th element), or not considering the element in the sum (the next recursive call is done for the (i+1)th element.
Note:
vector<int>&B -> denotes the array elements.
int K -> denotes the number of elements whose sum is to be taken
int N -> total number of elements in the vector.
int i -> keep track of which element is currently being processed
Here is my code:
class Solution{
public:
long long dp[1010][510];
long long maxSum(vector<int> &B, int K, int N, int i){
if (K == 0) return 0;
else if(i >= N){
return INT_MIN;
}
else{
if (dp[i][K] != INT_MIN) return dp[i][K];
dp[i][K] = max(maxSum(B, K, N, i+1), B[i] + maxSum(B, K-1, N, i+2));
return dp[i][K];
}
}
long long maximumBeauty(int N, int K, vector<int> &B){
int i = 0;
for (int i = 0; i<1010; i++){
for (int j = 0; j<510; j++){
dp[i][j] = INT_MIN;
}
}
return maxSum(B, K, N, i);
}
};
and here is the given solution: | {
"domain": "codereview.stackexchange",
"id": 45071,
"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++, recursion, time-limit-exceeded, dynamic-programming",
"url": null
} |
c++, recursion, time-limit-exceeded, dynamic-programming
and here is the given solution:
class Solution{
public:
long long dp(int i, int j, int N, int K, vector<int> &B,
vector<vector<long long>> &cache){
if(j >= K){
return 0;
}
if(i >= N){
return -1e15;
}
if(cache[i][j] != -1e18){
return cache[i][j];
}
cache[i][j] = max((long long )B[i] + dp(i + 2, j + 1, N, K, B, cache),
dp(i + 1, j, N, K, B, cache));
return cache[i][j];
}
long long maximumBeauty(int N, int K, vector<int> &B){
vector<vector<long long>> cache(N, vector<long long> (K, -1e18));
long long ans = dp(0, 0, N, K, B, cache);
return ans;
}
};
I've tried initialising the DP array to different values (such as initialising it with INT_MIN's instead of 0's), but I'm still getting a TLE. Please help me figure out the reason for getting a TLE in the first code, while the second code does not.
EDIT
If you want to test the code out and whether it's giving a TLE error, you can try submitting the code here:
question-link
Answer: Do the math to fix a bug
INT_MIN is not an appropriate value to return when the end of the array is reached (i >= N). It's not low enough!
Given the constraints:
\$1 ≤ N ≤ 1000\$
\$1 ≤ K ≤ ceil(N / 2)\$
\$1 ≤ B[i] ≤ 10^9\$
The biggest sum could reach \$10^9 * 500 = 500000000000\$.
reachable sum = 500000000000
INT_MIN = -2147483648 (in this competition environment)
And given that the code has this:
if (i >= N) return INT_MIN;
This leads to problems.
The intention at this point in the code is to stop exploring this branch of computations, because we're off the end of the input array, so no solutions could possibly come out of this.
Consider this valid input:
7 4
1 1000000000 1 1000000000 1 1000000000 1 | {
"domain": "codereview.stackexchange",
"id": 45071,
"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++, recursion, time-limit-exceeded, dynamic-programming",
"url": null
} |
c++, recursion, time-limit-exceeded, dynamic-programming
7 4
1 1000000000 1 1000000000 1 1000000000 1
The only way to pick 4 non-adjacent items is to pick 1 + 1 + 1 + 1 = 4.
The alternative path computed by the code is intended to be 1000000000 + 1000000000 + 1000000000 + IMPOSSIBLE.
But since "IMPOSSIBLE" is actually -2147483648, the program incorrectly computes as the solution 1000000000 + 1000000000 + 1000000000 + -2147483648 = 852516352.
The fix is simple: define const long long IMPOSSIBLE = -1e9 * 500, and use that instead of INT_MIN.
Allocate memory precisely
The program allocates memory for the dp array to hold computation results of sub-problems:
long long dp[1010][510];
The array dimensions don't match well the listed constraints.
The numbers look like something I used to lazily pick,
thinking along the lines of "that's gotta be enough to save me from off-by-one errors".
Later in life I realized it's worth forcing myself to think the math through.
What the program needs at most is really "just":
long long dp[1000][500];
This will force you to think through potential off-by one errors,
and realize that the program needs some minor adjustments.
But the main point here is not about the numbers, but about the process.
Because by thinking these numbers through,
now I'm more aware of any excess,
and it turns out to be important:
the program allocates a 500k array for every input, regardless of its size.
And as it turns out, replacing the fixed storage with dynamic storage that's just right for the input makes the solution fast enough to pass.
Other notes
I understand that this problem requires the use of Dynamic Programming, but doing so still gives me a TLE.
Yes. Using the right approach is often not enough.
It's important to use it the right way,
and to avoid wasting memory and unnecessary computations.
I've tried initialising the DP array to different values (such as initialising it with INT_MIN's instead of 0's), but I'm still getting a TLE. | {
"domain": "codereview.stackexchange",
"id": 45071,
"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++, recursion, time-limit-exceeded, dynamic-programming",
"url": null
} |
c++, recursion, time-limit-exceeded, dynamic-programming
The initial values are important for logical reasons, not the performance.
The algorithm needs to be able to decide if a value is unset or not.
Given the input constraints, any value that will never be a valid sum, for example -1 would work.
Alternative implementation
Based on the above, and some other minor improvements,
this is a slightly cleaner, passing version of your solution:
class Solution {
public:
const long long IMPOSSIBLE = -1e9 * 500;
const long long UNSET = -1;
long long maxSum(int i, int k, int N, vector<int> &B, vector<vector<long long>> &dp) {
if (k == 0) return 0;
if (i >= N) return IMPOSSIBLE;
if (dp[i][k - 1] != UNSET) return dp[i][k - 1];
dp[i][k - 1] = max(maxSum(i+1, k, N, B, dp), B[i] + maxSum(i+2, k-1, N, B, dp));
return dp[i][k - 1];
}
long long maximumBeauty(int N, int K, vector<int> &B) {
vector<vector<long long>> cache(N, vector<long long> (K, UNSET));
return maxSum(0, K, N, B, cache);
}
}; | {
"domain": "codereview.stackexchange",
"id": 45071,
"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++, recursion, time-limit-exceeded, dynamic-programming",
"url": null
} |
php, mysql, database, pdo, mysqli
Title: SQL & PHP login method
Question: My code is working however it seems to be using old outdated php version so less secure and I'm still new to programming so I'd be more than thankful if someone shows me how an improved updated and secured version would look like
My code:
Login.php:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="Styles/Bootstrap.css">
<link rel="stylesheet" href="Styles/Font-Awesome.css">
<link rel="stylesheet" href="Styles/General.css">
<link rel="stylesheet" href="Styles/Login.css">
<link rel="icon" href ="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<title>Register & Login</title>
</head>
<body>
<a class="btn btn-danger" href="index.html">Cancel</a>
<div>
<h1 class="px20">Please Login after you Register if you don't have an account.</h1>
<div>
<div class="form-box">
<div class="button-box">
<div id="btn"></div>
<button type="button" class="toggle-btn" onclick="Login()">
Login
</button>
<button type="button" class="toggle-btn" onclick="Register()">
Register
</button>
</div>
<form action="validation.php" method="POST" id="Login" class="input-group">
<input type="Email" name="Email" class="input-field" placeholder="Email" required>
<input type="Password" name="Password" id="Password" class="input-field" placeholder="Password" required>
<i class="far fa-eye" id="togglePassword"></i>
<button type="submit" class="submit-btn">Login</button>
</form> | {
"domain": "codereview.stackexchange",
"id": 45072,
"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, mysql, database, pdo, mysqli",
"url": null
} |
php, mysql, database, pdo, mysqli
<button type="submit" class="submit-btn">Login</button>
</form>
<form action="registeration.php" method="POST" id="Register" class="input-group">
<input type="Email" name="Email" class="input-field" placeholder="Email" required>
<input type="text" name="Username" class="input-field" placeholder="Username" required>
<input type="Password" name="Password" class="input-field" id="Password2" placeholder="Password" required>
<i class="far fa-eye" id="togglePassword2"></i>
<button type="submit" class="submit-btn">Register</button>
</form>
</div>
</div>
</div>
<script src="Scripts/Login.js"></script>
</body>
</html>
Registeration.php:
<?php
session_start();
$con = mysqli_connect('host','db_name','pass');
mysqli_select_db($con, 'table');
$Email = $_POST['Email'];
$Pass = $_POST['Password'];
$User = $_POST['Username'];
$s = "select * from Users where Email = '$Email'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo "<p align='center'> <font color=White size='50pt'>Email Already in use</font> </p>";
;}else{
$Date = date('Y-m-d H:i:s');
$reg= " insert into Users(Username, Email, Password, Creation_Date, VIP, Admin) values ('$User', '$Email' , '$Pass', '$Date', 'NO', 'NO')";
mysqli_query($con, $reg);
echo "<p align='center'> <font color=White size='50pt'>Registeration successful</font> </p>";
}
?>
<html>
<head>
<meta http-equiv="refresh" content="4;URL=login.php">
<link rel="stylesheet" href="Styles/General.css">
<link rel="stylesheet" href="Styles/Background.css">
<link rel="icon" href ="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<title>Register & Login</title>
</head> | {
"domain": "codereview.stackexchange",
"id": 45072,
"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, mysql, database, pdo, mysqli",
"url": null
} |
php, mysql, database, pdo, mysqli
<title>Register & Login</title>
</head>
<body class="Blue-Black">
<h1>Please wait, you will be automatically redirected to the login page.</h1>
</body>
</html>
Validation.php:
<?php
session_start();
$con = mysqli_connect('host','dbname','pass');
mysqli_select_db($con, 'table');
$Email = $_POST['Email'];
$Pass = $_POST['Password'];
$s = "select * from Users where Email = '$Email' && Password = '$Pass' ";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
$_SESSION['Email'] = $Email;
$Date = date('Y-m-d H:i:s');
$update = "UPDATE Users SET Last_Login = '$Date' WHERE Users.Email = '$Email'";
mysqli_query($con, $update);
$UpdateLastLogin = "UPDATE Users SET Login_Times = Login_Times + 1 where Email = '$Email'";
mysqli_query($con, $UpdateLastLogin);
header('location:home.php');
}else{
header('location:login.php');
}
?>
Answer: Yes indeed, your approach is severely outdated. Such a code nowadays is frowned upon. Here are some rules for the better code
Each script should consist of four parts
Initialization. Usually it's done in a separate file that's either includes the current script, or being included into it.
Input validation (if any)
Data manipulation.
Output (if any)
Security should be your foremost concern
in SQL, always use parameters instead of PHP variables for any database interaction
passwords must be hashed using password_hash()
all output in HTML must be done through htmlspecialchars()
User's convenience is a good thing to think of
for example, in case of user error, showing the error just on a white screen is not very convenient
already entered data is better to be kept filled too
Below is example code for the user registration. It's a single file which is split into four parts for sake of presentation
Part one. Initialization
<?php
require 'init.php'; | {
"domain": "codereview.stackexchange",
"id": 45072,
"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, mysql, database, pdo, mysqli",
"url": null
} |
php, mysql, database, pdo, mysqli
// Initialize all values so we won't have to always check them for existsnce
$error = ['name' => '', 'email' => '', 'password' => ''];
$input = ['name' => '', 'email' => '', 'password' => ''];
Parts two. Input validation
// if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// input validation
$name = $input['name'] = trim(filter_input(INPUT_POST, 'name'));
if (mb_strlen($name) < 3 || mb_strlen($name) > 30) {
$error['name'] = 'Please enter your name, it must be from 3 to 30 charaters long.';
}
$email = $input['email'] = trim(filter_input(INPUT_POST, 'email'));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error['email'] = 'Please enter a valid email address.';
} else {
$result = $db->execute_query("SELECT 1 FROM users WHERE email = ?", [$email]);
if ($result->fetch_row()) {
$error['email'] = 'Email address already taken.';
}
}
$password = filter_input(INPUT_POST, 'password');
if (strlen($password) < 6 || strlen($password) > 72) {
$error['password'] = 'Password must be from 6 to 72 bytes long.';
}
Part three. Data processing
// if no errors
if (implode($error) === '')
{
// passwords MUST be hashed using the dedicated function
$password = password_hash($password, PASSWORD_DEFAULT);
// a parameterized query MUST be used to avoid errors and injections
$stmt = $db->prepare("INSERT INTO users (name, email, password) VALUES (?,?,?)");
$stmt->execute([$name, $email, $password]);
// after each succesful POST request there MUST be a redirect
header("Location: /index.php");
// after sending Location header the code MUST be terminated
die;
}
}
Part four. Output
require 'templates/layout/header.php';
require 'templates/registration.php';
require 'templates/layout/footer.php'; | {
"domain": "codereview.stackexchange",
"id": 45072,
"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, mysql, database, pdo, mysqli",
"url": null
} |
php, mysql, database, pdo, mysqli
This code should be only the first iteration though. Innumerable improvements can be made to it. But it could be a good starting point
A minimal version of init.php could be like
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
if (!file_exists('config.php')) {
throw new Exception('Please create config.php based on config.sample.php');
}
$config = require 'config.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli(...$config['db']);
$db->set_charset($config['db_charset']);
config.sample.php
<?php
return [
'db' => [
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => '',
'port' => 3306,
],
'db_charset' => 'utf8mb4',
];
The HTML template for the form would be like
<div class="col-md-6 col-md-offset-3">
<h1 class="mb-5">Registration</h1>
<form role="form" method="post" action="">
<div class="form-group<?php if ($error['name']): ?> has-error <?php endif ?>">
<label class="control-label" for="inputError">Name</label>
<input type="text" class="form-control" name="name" value="<?= htmlspecialchars($input['name']) ?>">
<?php if ($error['name']): ?>
<span class="help-block"><?= htmlspecialchars($error['name']) ?></span>
<?php endif ?>
</div>
<div class="form-group<?php if ($error['email']): ?> has-error <?php endif ?>">
<label class="control-label" for="inputError">Email</label>
<input type="text" class="form-control" name="email" value="<?= htmlspecialchars($input['email']) ?>">
<?php if ($error['email']): ?>
<span class="help-block"><?= htmlspecialchars($error['email']) ?></span>
<?php endif ?>
</div> | {
"domain": "codereview.stackexchange",
"id": 45072,
"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, mysql, database, pdo, mysqli",
"url": null
} |
php, mysql, database, pdo, mysqli
<div class="form-group<?php if ($error['password']): ?> has-error <?php endif ?>">
<label class="control-label" for="password">Password</label>
<input type="password" class="form-control" name="password">
<?php if ($error['password']): ?>
<span class="help-block"><?= htmlspecialchars($error['password']) ?></span>
<?php endif ?>
</div>
<div class="d-flex justify-content-between">
<button type="submit" class="btn btn-primary">Register</button>
<a class="btn btn-outline-primary pull-right" href="login.php">Login</a>
</div>
</form>
</div>
The idea here is to display possible validation errors right along with already entered form controls, so the user don't have to enter them again. | {
"domain": "codereview.stackexchange",
"id": 45072,
"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, mysql, database, pdo, mysqli",
"url": null
} |
python, calculator, tkinter
Title: Simple calculator in python using tkinter
Question: I just learned Python and Tkinter and I've just made a simple calculator using Tkinter for a small project at my school. It can do addition, subtraction, multiplication and division. I think that my code is hacky and not clean. How can I improve this?
import tkinter as tk
def button_0():
print("button 0 clicked")
add_character_to_display("0")
def button_1():
print("button 1 clicked")
add_character_to_display("1")
def button_2():
print("button 2 clicked")
add_character_to_display("2")
def button_3():
print("button 3 clicked")
add_character_to_display("3")
def button_4():
print("button 4 clicked")
add_character_to_display("4")
def button_5():
print("button 5 clicked")
add_character_to_display("5")
def button_6():
print("button 6 clicked")
add_character_to_display("6")
def button_7():
print("button 7 clicked")
add_character_to_display("7")
def button_8():
print("button 8 clicked")
add_character_to_display("8")
def button_9():
print("button 9 clicked")
add_character_to_display("9")
def button_plus():
print("button + clicked")
do_operator_mode("plus")
def button_minus():
print("button - clicked")
do_operator_mode("minus")
def button_mutiply():
print("button * clicked")
do_operator_mode("mutiply")
def button_divide():
print("button / clicked")
do_operator_mode("divide")
def button_dot():
print("button . clicked")
add_character_to_display(".")
def button_equal():
print("button = clicked")
do_equal_mode()
def on_enter(e):
e.widget['background'] = '#fafafa'
def on_leave(e):
e.widget['background'] = 'SystemButtonFace' | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
def on_leave(e):
e.widget['background'] = 'SystemButtonFace'
def create_button(root, text, row, col, command=None):
button = tk.Button(root, text = text, padx = 20, pady = 20, command = command)
button.grid(row = row, column = col)
button.bind("<Enter>", on_enter)
button.bind("<Leave>", on_leave)
return button
def delete_display():
display.delete(0, tk.END)
def add_display(text):
display.insert(0, text)
def default_display():
delete_display()
add_display(0)
def is_string_only_zero(string):
for idx in string:
if idx != '0':
return False
return True
def add_character_to_display(new_number):
if(mode == "operator_input"):
return
current_text = display.get()
delete_display()
if(not current_text or is_string_only_zero(current_text)):
if new_number == '.':
add_display(current_text + new_number)
else:
add_display(new_number)
else:
add_display(current_text + new_number)
def do_operator_mode(input_mode):
global mode
global first_number
if mode == "number_input" or mode == "operator_input":
first_number = float(display.get())
mode = input_mode
default_display()
def do_equal_mode():
global mode
global first_number
second_number = float(display.get())
if mode == "plus":
result = first_number + second_number
elif mode == "minus":
result = first_number - second_number
elif mode == "mutiply":
result = first_number * second_number
elif mode == "divide":
result = first_number / second_number
delete_display()
add_display(str(result))
first_number = result
mode = "operator_input"
root = tk.Tk()
display = tk.Entry(root, width=30)
display.grid(row = 0, column = 0, columnspan=4)
global mode
mode = "number_input"
global first_number
first_number = 0
default_display() | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
global mode
mode = "number_input"
global first_number
first_number = 0
default_display()
buttons = [
('7', 1, 0, button_7), ('8', 1, 1, button_8), ('9', 1, 2, button_9), ('/', 1, 3, button_divide),
('4', 2, 0, button_4), ('5', 2, 1, button_5), ('6', 2, 2, button_6), ('*', 2, 3, button_mutiply),
('1', 3, 0, button_1), ('2', 3, 1, button_2), ('3', 3, 2, button_3), ('-', 3, 3, button_minus),
('0', 4, 0, button_0), ('.', 4, 1, button_dot), ('=', 4, 2, button_equal), ('+', 4, 3, button_plus),
]
for button_data in buttons:
create_button(root, *button_data)
root.mainloop()
Answer: Issues
Background colors
Traceback (most recent call last):
File "/usr/lib/python3.11/tkinter/__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "/home/…/calculator.py", line 72, in on_leave
e.widget['background'] = 'SystemButtonFace'
~~~~~~~~^^^^^^^^^^^^^^
File "/usr/lib/python3.11/tkinter/__init__.py", line 1713, in __setitem__
self.configure({key: value})
File "/usr/lib/python3.11/tkinter/__init__.py", line 1702, in configure
return self._configure('configure', cnf, kw)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/tkinter/__init__.py", line 1692, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown color name "SystemButtonFace" | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
Yeah, not a great start… Chances are that, on anything except Windows, SystemButtonFace is not a valid background color and you need to store it from a default button to be able to restore it later. One way would be to use yet another global variable to store it from your create_button calls. A better alternative would be to create a closure that will remember this value and use it as your event handler. This will also allows you to consolidate on_enter and on_leave into a single function:
def change_background_handler(color):
def on_event(event):
event.widget['background'] = color
return on_event
def create_button(…):
…
button.bind("<Enter>", change_background_handler('#fafafa'))
button.bind("<Leave>", change_background_handler(button['bg']))
Chaining operations
Using a calculator, it is expected that selecting an operator right after a computation is performed will reuse the result as the first operand. But:
One should still be able to enter a completely new first operand after pressing the = sign, which your code forbid.
It is expected that selecting a second operator performs an implicit press on the = sign just before. Instead, your code wrongfully discard the second operator input. | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
The fix is rather simple as you just need to use 0 and "plus" as your default first operand and mode (and reset to it after a press on =), and have your do_operator_mode call do_equal_mode first. This will allows you to get rid of all the checks of the form mode == 'xxx_input'.
In order to be able to reset the display if the user want to enter a fresh new first operand after a press on =, you may need to introduce a new variable that tells you if you need to clear the display or not.
Improvements
Operators
Instead of using strings to convey information about the operation to perform, have a look at the operator module. You can directly pass operator.add, operator.sub, operator.mul, operator.truediv around instead.
Buttons
You already know about unpacking, let's leverage that to remove all your button_X functions. Their main purpose is to transform a multi-parameter function like your do_xxx_mode into a parameter-less function suitable for the button command argument. But you can create them on the fly:
def create_button(root, text, row, col, *command):
if not command:
on_click = None
else:
command, *arguments = command
def on_click():
command(*arguments)
button = tk.Button(root, text=text, padx=20, pady=20, command=on_click)
… | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
Window creation
Since you already manually list the parameters to all your create_button calls, the for loop does not add much here and you would be better of just calling it with the appropriate parameters:
create_button(root, '0', 4, 0, add_character_to_display, '0')
create_button(root, '1', 3, 0, add_character_to_display, '1')
create_button(root, '2', 3, 1, add_character_to_display, '2')
create_button(root, '3', 3, 2, add_character_to_display, '3')
create_button(root, '4', 2, 0, add_character_to_display, '4')
create_button(root, '5', 2, 1, add_character_to_display, '5')
create_button(root, '6', 2, 2, add_character_to_display, '6')
create_button(root, '7', 1, 0, add_character_to_display, '7')
create_button(root, '8', 1, 1, add_character_to_display, '8')
create_button(root, '9', 1, 2, add_character_to_display, '9')
create_button(root, '.', 4, 1, add_character_to_display, '.')
create_button(root, '+', 4, 3, do_operator_mode, operator.add)
create_button(root, '-', 3, 3, do_operator_mode, operator.sub)
create_button(root, '*', 2, 3, do_operator_mode, operator.mul)
create_button(root, '/', 1, 3, do_operator_mode, operator.truediv)
create_button(root, '=', 4, 2, do_equal_mode) | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
Globals
Using globals like this is not ideal, consider passing the relevant variables around as parameters to functions. Consider using a list (meh) or a class to store values that are tied with the same concept and reduce the number of arguments to your functions.
Top-level code
Instead of putting blocks of code at the top-level of your code, consider using an if __name__ == '__main__' guard. It will make the code easier to deal with when importing / testing it.
Further
As with many GUI, it is advisable to regroup dependent parts of you application into a class to simplify reasoning about and ease passing of variables / context. To me, the whole Entry + Buttons you define here would be better of in a class like that.
Proposed improvements
import tkinter as tk
from operator import add, sub, mul, truediv
class Calculator:
def __init__(self, root):
display = tk.Entry(root, width=30)
display.insert(tk.END, '0')
display.grid(row=0, column=0, columnspan=4) | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
self.add_button(root, '0', 4, 0, self.new_character, '0')
self.add_button(root, '1', 3, 0, self.new_character, '1')
self.add_button(root, '2', 3, 1, self.new_character, '2')
self.add_button(root, '3', 3, 2, self.new_character, '3')
self.add_button(root, '4', 2, 0, self.new_character, '4')
self.add_button(root, '5', 2, 1, self.new_character, '5')
self.add_button(root, '6', 2, 2, self.new_character, '6')
self.add_button(root, '7', 1, 0, self.new_character, '7')
self.add_button(root, '8', 1, 1, self.new_character, '8')
self.add_button(root, '9', 1, 2, self.new_character, '9')
self.add_button(root, '.', 4, 1, self.new_character, '.')
self.add_button(root, '+', 4, 3, self.new_operation, add)
self.add_button(root, '-', 3, 3, self.new_operation, sub)
self.add_button(root, '*', 2, 3, self.new_operation, mul)
self.add_button(root, '/', 1, 3, self.new_operation, truediv)
self.add_button(root, '=', 4, 2, self.perform_operation)
self.display = display
self.operator = add
self.previous_result = 0
self.need_display_refresh = False
@staticmethod
def add_button(root, text, row, col, *command):
if not command:
on_click = None
else:
command, *arguments = command
def on_click():
command(*arguments)
button = tk.Button(root, text=text, padx=20, pady=20, command=on_click)
button.grid(row=row, column=col)
button.bind("<Enter>", change_background_handler('#fafafa'))
button.bind("<Leave>", change_background_handler(button['bg']))
def parse_display(self):
content = self.display.get()
if '.' in content:
return float(content)
return int(content) | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
python, calculator, tkinter
def new_character(self, new_number):
current_text = self.display.get()
if self.need_display_refresh or (new_number != '.' and only_zeroes(current_text)):
self.display.delete(0, tk.END)
self.display.insert(tk.END, new_number)
self.need_display_refresh = False
def new_operation(self, operator):
self.perform_operation()
self.previous_result = self.parse_display()
self.operator = operator
def perform_operation(self):
result = self.operator(self.previous_result, self.parse_display())
self.display.delete(0, tk.END)
self.display.insert(tk.END, str(result))
self.need_display_refresh = True
self.operator = add
self.previous_result = 0
def change_background_handler(color):
def on_event(event):
event.widget['background'] = color
return on_event
def only_zeroes(text):
return all(char == '0' for char in text)
if __name__ == '__main__':
root = tk.Tk()
Calculator(root)
root.mainloop()
TODOs
At least two buttons feels missing from your calculator: "clear" and "remove the last character".
You'll also need to improve the way numbers are retrieved from the Entry and properly handle inputs such as 3.14.159... which will otherwise leave your calculator in a broken state. | {
"domain": "codereview.stackexchange",
"id": 45073,
"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, calculator, tkinter",
"url": null
} |
performance, c, graphics, fractals
Title: Improving performance of mandelbrot set calculation
Question: I am making a hobby OS, and I thought about adding a command for interactively rendering the Mandelbrot set. The "interactive" part is not really important, but I wanted to check if the Mandelbrot algorithm is as good as it can be.
The most performance-sensitive part is the code inside the inner for loop, the one that iterates max_iter.
I tried making it as optimized as possible, but I might have left something (also note that my OS doesn't support multicore yet).
/* Smaller -> More zoom (1.0 is defaul) */
#define DEFAULT_ZOOM 1.0
/* Offsets for moving in the set. */
#define DEFAULT_X_OFF 0.0 /* -2.0..+2.0 (Left..Right) */
#define DEFAULT_Y_OFF 0.0 /* -1.0..+1.0 (Up..Down) */
/* Default steps when moving around */
#define ZOOM_STEP 0.5
#define DEFAULT_MOVE_STEP 0.1
int mandelbrot(int argc, char** argv) {
const uint32_t w = screen_width();
const uint32_t h = screen_height();
const int max_iter = atoi(argv[1]);
/* Check arguments are valid... */
/* Framebuffer. Each 32 bit entry is a color */
volatile uint32_t* fb = fb_get_ptr();
/* Calculate some values here for performance */
const double scaled_h = h / 2.0;
const double scaled_w = w / 3.0;
/* Will become smaller when zooming */
double zoom = DEFAULT_ZOOM;
double x_offset = DEFAULT_X_OFF;
double y_offset = DEFAULT_X_OFF;
/* Will be scaled when zooming, so we don't move too much */
double move_step = DEFAULT_MOVE_STEP;
bool main_loop = true;
while (main_loop) {
do_mandelbrot();
handle_input();
}
}
My do_mandelbrot() function:
static void do_mandelbrot(void) {
for (uint32_t y_px = 0; y_px < h; y_px++) {
double real_y = (y_px / scaled_h) - 1.0;
real_y *= zoom;
real_y += y_offset; | {
"domain": "codereview.stackexchange",
"id": 45074,
"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, graphics, fractals",
"url": null
} |
performance, c, graphics, fractals
for (uint32_t x_px = 0; x_px < w; x_px++) {
double real_x = (x_px / scaled_w) - 2.0;
real_x *= zoom;
real_x += x_offset;
double x = real_x;
double y = real_y;
bool inside_set = true;
int iter;
for (iter = 0; iter < max_iter; iter++) {
/* Calulate squares once */
double sqr_x = x * x;
double sqr_y = y * y;
/* Absolute value of a complex number is the distance from
* origin: sqrt(x^2 + y^2) > 2 */
if ((sqr_x + sqr_y) > 2 * 2) {
inside_set = false;
break;
}
y = (2.0 * x * y) + real_y;
x = (sqr_x - sqr_y) + real_x;
}
/* If it's inside the set, draw black */
if (inside_set) {
fb[y_px * w + x_px] = 0x000000;
continue;
}
/* Get 0..360 hue for color based on iter..max_iter */
int scaled_hue = iter * MAX_H / max_iter;
fb[y_px * w + x_px] = hue2rgb(scaled_hue);
}
}
}
My hue2rgb function:
static uint32_t hue2rgb(float h) {
float prime = fmod(h / 60.f, 6);
float x = 1 - fabs(fmod(prime, 2) - 1);
uint32_t ret = 0x000000; | {
"domain": "codereview.stackexchange",
"id": 45074,
"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, graphics, fractals",
"url": null
} |
performance, c, graphics, fractals
uint32_t ret = 0x000000;
if (prime >= 0 && prime < 1) {
ret |= 0xFF0000; /* r = 255 */
ret |= (uint8_t)(x * 0xFF) << 8; /* g = x */
} else if (prime < 2) {
ret |= 0x00FF00; /* g = 255 */
ret |= (uint8_t)(x * 0xFF) << 16; /* r = x */
} else if (prime < 3) {
ret |= 0x00FF00; /* g = 255 */
ret |= (uint8_t)(x * 0xFF) << 0; /* b = x */
} else if (prime < 4) {
ret |= 0x0000FF; /* b = 255 */
ret |= (uint8_t)(x * 0xFF) << 8; /* g = x */
} else if (prime < 5) {
ret |= 0x0000FF; /* b = 255 */
ret |= (uint8_t)(x * 0xFF) << 16; /* r = x */
} else if (prime < 6) {
ret |= 0xFF0000; /* r = 255 */
ret |= (uint8_t)(x * 0xFF) << 0; /* b = x */
}
return ret;
}
My handle_input function should not be important, but here it is:
static void handle_input() {
/* User input, not really important for performance */
switch (getchar()) {
case KEY_ZOOM_IN:
zoom *= ZOOM_STEP;
move_step *= ZOOM_STEP;
break;
case KEY_ZOOM_OUT:
zoom /= ZOOM_STEP;
move_step /= ZOOM_STEP;
break;
case KEY_UP:
if (y_offset > -1.1)
y_offset -= move_step;
break;
case KEY_DOWN:
if (y_offset < 1.1)
y_offset += move_step;
break;
case KEY_LEFT:
if (x_offset > -2.1)
x_offset -= move_step;
break;
case KEY_RIGHT:
if (x_offset < 2.1)
x_offset += move_step;
break;
case KEY_RESET:
zoom = DEFAULT_ZOOM;
move_step = DEFAULT_MOVE_STEP;
x_offset = DEFAULT_X_OFF;
y_offset = DEFAULT_X_OFF;
break;
default:
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 45074,
"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, graphics, fractals",
"url": null
} |
performance, c, graphics, fractals
Edit: I changed the hue2rgb return value.
Edit: Separated code into multiple blocks. Didn't bother with variables or returns, contents of do_mandelbrot and handle_input should be replaced where the functions are called.
Answer: There is a lot of literature on performant 2D visualisations of the Mandelbrot set, including wikipedia - I intend not to go into algorithmic improvements.
I expect most of what I think of to improve do_mandelbrot()'s speed is covered by contemporary "optimising" compilers, and may be at odds with code the way you think about the solution.
An inlining compiler would even cover using return for lack of continue a loop enclosing the current one - I suggest using goto instead of introducing a flag to re-establish why the innermost loop was terminated.
I consider goto a red flag rather than a problem: don't use it to code in an unstructured way.
I prefer declaring identifiers I want to have the same type for the same reason in a single declaration.
Switching the outer loops allows just walking the frame buffer with an index or pointer.
static const uint32_t BLACK = 0;
static void do_mandelbrot(void) {
const double scale_h = zoom / scaled_h,
scale_w = zoom / scaled_w,
hue_scale = MAX_H / max_iter;
for (uint32_t x_px = 0, fb_index = 0; x_px < w; x_px++) {
const double real_x = x_px * scale_w - 2*zoom;
pixel_loop:
for (uint32_t y_px = 0 ; y_px < h; y_px++, fb_index++) {
const double real_y = y_px * scale_h - zoom,
double x = real_x,
y = real_y; | {
"domain": "codereview.stackexchange",
"id": 45074,
"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, graphics, fractals",
"url": null
} |
performance, c, graphics, fractals
double x = real_x,
y = real_y;
for (int iter = 0; iter < max_iter; iter++) {
/* Calculate squares once */
const double sqr_x = x * x,
sqr_y = y * y;
/* Absolute value of a complex number is the
* distance from origin: sqrt(x^2 + y^2) > 2 */
if (sqr_x + sqr_y > 2 * 2) { /* outside set */
/* scale to 0..360 hue for color
* based on ratio of iter to max_iter */
fb[fb_index] = hue2rgb(iter * hue_scale);
goto next_pixel; /* continue pixel_loop; */
}
y = (2.0 * x * y) + real_y;
x = (sqr_x - sqr_y) + real_x;
}
fb[fb_index] = BLACK; /* inside set */
next_pixel:
}
}
}
hue2rgb() shows avoidable repetition in handling x:
static uint32_t hue_to_rgb(float h) {
float prime = fmod(h / 60.f, 6);
uint32_t rgb;
int shift;
switch (floor(prime)) {
default: return 0xffffff; /* not BLACK (inside) */
case 0:
rgb = 0xFF0000; /* r = 255 *//* introduce symbolic names? */
shift = 8; /* g */
break;
case 1:
rgb = 0x00FF00; /* g = 255 */
shift = 16; /* r */
break;
case 2:
rgb = 0x00FF00; /* g = 255 */
shift = 0; /* b */
break;
case 3:
rgb = 0x0000FF; /* b = 255 */
shift = 8; /* g */
break;
case 4:
rgb = 0x0000FF; /* b = 255 */
shift = 16; /* r */
break;
case 5:
rgb = 0xFF0000; /* r = 255 */
shift = 0; /* b */
break;
} | {
"domain": "codereview.stackexchange",
"id": 45074,
"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, graphics, fractals",
"url": null
} |
performance, c, graphics, fractals
float x = 1 - fabs(fmod(prime, 2) - 1);
return rgb | ((uint8_t)(x * 0xFF) << shift);
}
/* can be replaced by array access - less readable/mode difficult to comment */
static const uint32_t HUE2RGB[] = {
0xFF0000, /* r = 255 */
0x00FF00, /* g = 255 */
0x00FF00, /* g = 255 */
0x0000FF, /* b = 255 */
0x0000FF, /* b = 255 */
0xFF0000, /* r = 255 */
};
static const int HUE_SHIFT[] = {
shift = 8; /* g */
shift = 16; /* r */
shift = 0; /* b */
shift = 8; /* g */
shift = 16; /* r */
shift = 0; /* b */
};
static uint32_t hue2rgb(float h) {
float prime = fmod(h / 60.f, 6);
if (prime < 0 || 6 <= prime)
return 0xffffff;
float x = 1 - fabs(fmod(prime, 2) - 1);
int i_prime = floor(prime);
return HUE2RGB[i_prime] | ((uint8_t)(x * 0xFF) << HUE_SHIFT[i_prime]);
} | {
"domain": "codereview.stackexchange",
"id": 45074,
"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, graphics, fractals",
"url": null
} |
python, performance, python-3.x, sorting
Title: Algorithm "sort except zero"
Question: Task:
Sort the integers in sequence in sequence. But the position of zeros should not be changed.
Input: List of integers (int).
Output: List or another Iterable (tuple, generator, iterator) of integers (int).
Examples:
[5, 3, 0, 0, 4, 1, 4, 0, 7] => [1, 3, 0, 0, 4, 4, 5, 0, 7]
[0, 2, 3, 1, 0, 4, 5] => [0, 1, 2, 3, 0, 4, 5]
[0, 0, 0, 1, 0] => [0, 0, 0, 1, 0]
[4, 5, 3, 1, 1] => [1, 1, 3, 4, 5]
Precondition:
All numbers are non-negative.
My code:
from collections.abc import Iterable
def except_zero(items: list[int]) -> Iterable[int]:
without_z = [i for i in items if i != 0]
place_z = [i[0] for i in enumerate([i if i == 0 else 1 for i in items]) if i[1] == 0]
without_z = sorted(without_z)
for i in place_z: without_z.insert(i, 0)
return without_z
How can I make this faster?
Answer: Most of the work will be done by your call to sorted. You just need to make sure to not make too much extra fluff around that call.
One particular call that may greatly impact performances, especially on large lists with lots of zeroes is your without_z.insert which needs to move memory around. Instead, I’d rather use this result and pull elements out from it to build a whole new list with zeroes inserted as necessary.
The name of the function does not convey anything sort-related, please change it and consider using a docstring to document its particular behavior.
Lastly, your type hints are off as you are explicitly returning a list[int] but your code can accept any Sequence[int] iterables which allow you to iterate over them twice.
from typing import Sequence
def sort_except_zeroes(items: Sequence[int]) -> list[int]:
non_zeroes = iter(sorted(i for i in items if i != 0))
return [next(non_zeroes) if i != 0 else 0 for i in items] | {
"domain": "codereview.stackexchange",
"id": 45075,
"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, performance, python-3.x, sorting",
"url": null
} |
php, mysql, database, pdo, mysqli
Title: PHP Validation script
Question: The code below is modified slightly from the code in this previous post.
I believe the code below could be improved and more secured but i don't know how so someone please show me how an improved sample would look like
Validation.php
<?php
session_start();
$con = mysqli_connect('localhost','Bebo','Bebo');
mysqli_select_db($con, 'Bebo');
$Email = $_POST['Email'];
$Pass = $_POST['Password'];
$s = "select * from Users where Email = '$Email' && Password = '$Pass' ";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
$_SESSION['Email'] = $Email;
$Date = date('Y-m-d H:i:s');
$update = "UPDATE Users SET Last_Login = '$Date' WHERE Users.Email = '$Email'";
mysqli_query($con, $update);
$UpdateLastLogin = "UPDATE Users SET Login_Times = Login_Times + 1 where Email = '$Email'";
mysqli_query($con, $UpdateLastLogin);
header('location:home.php');
}else{
header('location:login.php');
} ?>
Answer: Use bound parameters in database queries
In the answer to your previous question by Your Common Sense was this advice:
in SQL, always use parameters instead of PHP variables for any database interaction
However it does not appear that parameters are used. Instead of using mysqli_query() one could use mysqli_prepare() to get a mysqli_stmt for use when binding parameters with mysqli_stmt_bind_param() before calling mysqli_stmt_execute(). Each of those manual pages have examples both with Object-oriented style and Procedural style.
YCS maintains phpdelusions.net which has a whole guide on SQL injection, including examples using PDO for binding parameters.
Reduce the number of queries executed
There are two update statements executed:
$update = "UPDATE Users SET Last_Login = '$Date' WHERE Users.Email = '$Email'";
mysqli_query($con, $update);
$UpdateLastLogin = "UPDATE Users SET Login_Times = Login_Times + 1 where Email = '$Email'";
mysqli_query($con, $UpdateLastLogin); | {
"domain": "codereview.stackexchange",
"id": 45076,
"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, mysql, database, pdo, mysqli",
"url": null
} |
php, mysql, database, pdo, mysqli
While the difference in speed may not be very noticeable, those could be combined into a single query:
$update = "UPDATE Users SET Last_Login = '$Date', Login_Times = Login_Times + 1 WHERE Users.Email = '$Email'";
This will reduce the amount of time needed to run the script, as well as the risk of a deadlock since the table is being updated.
Closing tag can be omitted
The last line has a closing PHP tag.
} ?>
From the PHP documentation for PHP tags:
If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
And some style guides recommend not including it. For example - from PHP Standards Recommendations PSR-12 section 2.2 Files:
The closing ?> tag MUST be omitted from files containing only PHP.
It is okay to keep it if desired. It may improve readability. | {
"domain": "codereview.stackexchange",
"id": 45076,
"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, mysql, database, pdo, mysqli",
"url": null
} |
php, mysql, database, mysqli, sql-injection
Title: Follow up to Validation Script in PHP
Question: So I've implemented the suggestions in Original question
And now my code looks like this:
<?php
require 'init.php';
$Email = $input['Email'] = trim(filter_input(INPUT_POST, 'Email'));
$Password = filter_input(INPUT_POST, 'Password');
$result = $db->execute_query("SELECT 1 FROM Users WHERE Email = ? && Password = ?", [$Email, $Password]);
if ($result->fetch_row()) {
$Date = date('Y-m-d H:i:s');
$_SESSION['Email'] = $Email;
$Update = "UPDATE Users SET Last_Login = '$Date', Login_Times = Login_Times + 1 WHERE Users.Email = '$Email'";
$stmt = $db->execute_query($Update);
header('location:home.php');
}
Is there any more improvements i can do and most importantly is my code secure enough against SQL injections?
Answer: First query looks good.
any more improvements
I don't understand why you're even asking the question.
What part of Sam's "use bound variables" answer was unclear?
We start out with $Email coming from the internet,
so it is "attacker controlled".
And then you filter down to the subset of address spellings
which already exist in the database.
A very charitable reviewer might assume that all such rows
match a this@that regex,
but I don't feel I can assume the rest of your code
(which INSERTs or UPDATEs) is rock solid.
So by the time we execute the second SQL statement,
I'm going to conservatively assume the
variable is still attacker controlled.
$Update = "UPDATE Users SET Last_Login = '$Date', Login_Times = Login_Times + 1
WHERE Users.Email = '$Email'"; | {
"domain": "codereview.stackexchange",
"id": 45077,
"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, mysql, database, mysqli, sql-injection",
"url": null
} |
php, mysql, database, mysqli, sql-injection
Now $Date is known to contain just [0-9 :-]+,
but still, why follow that old string interpolation habit?
Make it a ? bound variable already.
And if $Email is attacker controlled, then interpolating
little Bobby Tables
into the WHERE clause was definitely trouble.
Why make yourself, or a reviewer, even begin to think
about the injection exposure?
Just use a ? bound variable and be done with it.
EDIT
Here's a simple rule you can follow. It's in line with Sam's advice.
Whenever you execute_query( ... ), make sure you pass in a constant string
followed by a list of variables used by the query. The query string will
have one ? for each such variable. That way you avoid the habit of doing
string interpolation to construct a SQL query. As I mentioned, for something
not attacker-controlled like $Date it doesn't actually matter. But to have
a very simple rule you can follow all the time, just always supply variables
in that list at the end (bound vars) and never as part of the string.
show me a sample of how i can make the $Email not attacker controlled?
Let's start with a simpler example.
Suppose we're querying someone's U.S.
ZIP code.
So we grab it with:
$zip = filter_input(INPUT_POST, 'zip'); | {
"domain": "codereview.stackexchange",
"id": 45077,
"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, mysql, database, mysqli, sql-injection",
"url": null
} |
php, mysql, database, mysqli, sql-injection
At this point we have a string which is completely attacker controlled.
Mallory
can set it to nearly any Unicode text he wishes, including
punctuation-laden strings which will DROP table students;
How to sanitize and validate such input?
Compare this input to the regex "^[0-9]{5}$",
which demands exactly five digits.
Return an error code if no match.
Now any subsequent code can safely assume
we have only digits,
we have no punctuation,
and that there's certainly no injection danger
that would let us DROP the student table.
Casting to (int) and bailing if that didn't
succeed is another strategy,
though for ZIPs I caution against actually using the integer result,
for fear of annoying Bostonians who reside in zip code 02108.
Losing the leading zero would be Bad.
For $Email we could similarly use a this@that regex to verify
that no punctuation and only expected unicode runes are present.
However, I will leave that regex as an exercise to the reader,
as there are diverse opinions on what are "sensible"
characters to admit in an address.
Certainly we should admit both alphanumerics and + PLUS
on the left side of the @ AT-SIGN.
And rejecting a string with more than one @ AT-SIGN would be good.
There are multiple validation libraries.
Consider delegating the "well formed email?" decision
to one of them. | {
"domain": "codereview.stackexchange",
"id": 45077,
"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, mysql, database, mysqli, sql-injection",
"url": null
} |
c++, reinventing-the-wheel, c++20
Title: C++ std::any Implementation
Question: Took a shot at implementing std::any. I think this should cover a majority of the functionality of the standard version, except there may be some missing auxiliary functions, and the overload resolution may not be exactly as is written in the standard.
#include <memory>
#include <typeinfo>
#include <utility>
#include <stdexcept>
struct bad_any_cast: std::exception {
const char* what() const noexcept override {
return "bad_any_cast: failed type conversion using AnyCast";
}
};
class Any {
public:
constexpr Any() noexcept = default;
template<typename T, typename Decayed = std::decay_t<T>>
requires(!std::is_same_v<Decayed, Any>)
Any(T&& value) {
m_holder = std::make_unique<holder<Decayed>>(std::forward<T>(value));
}
template<typename T, typename... Args>
Any(std::in_place_type_t<T> type, Args&&...args) {
emplace<T>(std::forward<Args>(args)...);
}
Any(const Any& other) {
if (other.m_holder) {
m_holder = std::unique_ptr<base_holder>(other.m_holder->clone());
}
}
Any& operator=(const Any& other) {
if (this != &other) {
Any temp{other};
swap(temp);
}
return *this;
}
Any(Any&& other) noexcept : m_holder(std::move(other.m_holder)) {}
Any& operator=(Any&& other) noexcept {
if (this != &other) {
m_holder = std::move(other.m_holder);
}
return *this;
}
template<typename T, typename... Args>
void emplace(Args&&... args) {
m_holder = std::make_unique<holder<T>>(std::forward<Args>(args)...);
}
void swap(Any& other) noexcept {
std::swap(m_holder, other.m_holder);
}
void reset() noexcept {
m_holder.reset();
}
bool has_value() const noexcept {
return bool(*this);
} | {
"domain": "codereview.stackexchange",
"id": 45078,
"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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
explicit operator bool() const noexcept {
return m_holder != nullptr;
}
~Any() = default;
private:
template<typename U>
friend U AnyCast(const Any& value);
template<typename U>
friend U AnyCast(Any& value);
template<typename U>
friend U AnyCast(Any&& value);
template<typename U>
friend U* AnyCast(Any* value);
struct base_holder {
virtual const std::type_info &type() const noexcept = 0;
virtual base_holder* clone() const = 0;
virtual ~base_holder() = default;
};
template<typename T>
struct holder: base_holder {
template<typename U>
holder(U&& value):
item{std::forward<U>(value)} {}
template<typename... Args>
holder(Args&&... args):
item{T(std::forward<Args>(args)...)} {}
holder* clone() const override {
return new holder<T>{std::move(item)};
}
const std::type_info &type() const noexcept override {
return typeid(T);
}
T item;
};
std::unique_ptr<base_holder> m_holder;
};
template<typename T>
T AnyCast(const Any& value) {
if (value.m_holder->type() != typeid(T)) {
throw bad_any_cast();
}
return dynamic_cast<Any::holder<T>&>(*value.m_holder).item;
}
template<typename T>
T AnyCast(Any&& value) {
if (value.m_holder->type() != typeid(T)) {
throw bad_any_cast();
}
return dynamic_cast<Any::holder<T>&>(*value.m_holder).item;
}
template<typename T>
T AnyCast(Any& value) {
if (value.m_holder->type() != typeid(T)) {
throw bad_any_cast();
}
return dynamic_cast<Any::holder<T>&>(*value.m_holder).item;
}
template<typename T>
T* AnyCast(Any* value) {
if (!value || value->m_holder->type() != typeid(T)) {
return nullptr;
}
return &(dynamic_cast<Any::holder<T>&>(*value->m_holder).item);
} | {
"domain": "codereview.stackexchange",
"id": 45078,
"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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
return &(dynamic_cast<Any::holder<T>&>(*value->m_holder).item);
}
template<typename T, typename...Args>
Any makeAny(Args&&... args) {
return Any(std::in_place_type<T>, std::forward<Args>(args)...);
}
The class is very popular with lots of friends, most of which do very similar things. Is there some way I can consolidate this? Why is any_cast a separate function and not part of the class anyway?
Finally, some tests partially inspired by cppreference examples.
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif // BOOST_TEST_DYN_LINK
#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>
#include "Any.h"
struct A {
int age;
std::string name;
double salary;
A(int age, std::string name, double salary)
: age(age), name(std::move(name)), salary(salary) {}
};
BOOST_AUTO_TEST_CASE(default_constructor_test) {
Any a;
BOOST_CHECK(!a);
BOOST_CHECK(!a.has_value());
}
BOOST_AUTO_TEST_CASE(basic_int_test) {
Any a{7};
BOOST_CHECK_EQUAL(AnyCast<int>(a), 7);
BOOST_CHECK(a.has_value());
}
BOOST_AUTO_TEST_CASE(in_place_type_test) {
Any a(std::in_place_type<A>, 30, "Ada", 1000.25);
BOOST_CHECK_EQUAL(AnyCast<A>(a).age, 30);
BOOST_CHECK_EQUAL(AnyCast<A>(a).name, "Ada");
BOOST_CHECK_EQUAL(AnyCast<A>(a).salary, 1000.25);
}
BOOST_AUTO_TEST_CASE(bad_cast_test) {
Any a{7};
BOOST_CHECK_THROW(AnyCast<float>(a), bad_any_cast);
}
BOOST_AUTO_TEST_CASE(type_change_test) {
Any a{7};
BOOST_CHECK_EQUAL(AnyCast<int>(a), 7);
BOOST_CHECK_THROW(AnyCast<std::string>(a), bad_any_cast);
a = std::string("hi");
BOOST_CHECK_EQUAL(AnyCast<std::string>(a), "hi");
BOOST_CHECK_THROW(AnyCast<int>(a), bad_any_cast);
}
BOOST_AUTO_TEST_CASE(reset_test) {
Any a{7};
BOOST_CHECK_EQUAL(AnyCast<int>(a), 7);
a.reset();
BOOST_CHECK(!a.has_value());
} | {
"domain": "codereview.stackexchange",
"id": 45078,
"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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
a.reset();
BOOST_CHECK(!a.has_value());
}
BOOST_AUTO_TEST_CASE(pointer_test) {
Any a{7};
int *i = AnyCast<int>(&a);
BOOST_CHECK_EQUAL(*i, 7);
}
BOOST_AUTO_TEST_CASE(emplacement_test) {
Any a;
BOOST_CHECK(!a.has_value());
a.emplace<A>(30, "Ada", 1000.25);
BOOST_CHECK_EQUAL(AnyCast<A>(a).age, 30);
BOOST_CHECK_EQUAL(AnyCast<A>(a).name, "Ada");
BOOST_CHECK_EQUAL(AnyCast<A>(a).salary, 1000.25);
a.emplace<A>(50, "Bob", 500.5);
BOOST_CHECK_EQUAL(AnyCast<A>(a).age, 50);
BOOST_CHECK_EQUAL(AnyCast<A>(a).name, "Bob");
BOOST_CHECK_EQUAL(AnyCast<A>(a).salary, 500.5);
}
BOOST_AUTO_TEST_CASE(swap_test) {
Any a1{7};
Any a2{A{30, "Ada", 1000.25}};
a1.swap(a2);
BOOST_CHECK_EQUAL(AnyCast<int>(a2), 7);
BOOST_CHECK_EQUAL(AnyCast<A>(a1).age, 30);
BOOST_CHECK_EQUAL(AnyCast<A>(a1).name, "Ada");
BOOST_CHECK_CLOSE(AnyCast<A>(a1).salary, 1000.25, 0.0001); // Use BOOST_CHECK_CLOSE for floating point comparisons
}
BOOST_AUTO_TEST_CASE(make_any_test) {
Any a1 = makeAny<int>(7);
Any a2 = makeAny<A>(30, "Ada", 1000.25);
a1.swap(a2);
BOOST_CHECK_EQUAL(AnyCast<int>(a2), 7);
BOOST_CHECK_EQUAL(AnyCast<A>(a1).age, 30);
BOOST_CHECK_EQUAL(AnyCast<A>(a1).name, "Ada");
BOOST_CHECK_EQUAL(AnyCast<A>(a1).salary, 1000.25);
}
BOOST_AUTO_TEST_CASE(move_test) {
Any a1{42};
Any a2{std::move(a1)};
BOOST_CHECK(!a1.has_value());
BOOST_CHECK_EQUAL(AnyCast<int>(a2), 42);
}
BOOST_AUTO_TEST_CASE(copy_test) {
Any original{A{30, "Ada", 1000.25}};
Any copy{original};
A original_casted = AnyCast<A>(original);
A copy_casted = AnyCast<A>(copy);
original_casted.age = 40;
BOOST_CHECK_NE(original_casted.age, copy_casted.age);
}
BOOST_AUTO_TEST_CASE(self_assignment_test) {
Any a{5};
a = a; // self-assignment
BOOST_CHECK_EQUAL(AnyCast<int>(a), 5);
} | {
"domain": "codereview.stackexchange",
"id": 45078,
"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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
BOOST_AUTO_TEST_CASE(nested_any_test) {
Any inner{42};
Any outer;
outer.emplace<Any>(inner);
BOOST_CHECK_THROW(AnyCast<int>(outer), bad_any_cast);
BOOST_CHECK_EQUAL(AnyCast<Any>(outer).has_value(), true);
}
BOOST_AUTO_TEST_CASE(large_object_test) {
std::vector<int> largeVector(1000000, 5); // A vector with 1 million ints.
Any a{largeVector};
BOOST_CHECK_EQUAL(AnyCast<std::vector<int>>(a).size(), 1000000);
}
static int destructorCounter = 0;
struct TestDestruction {
~TestDestruction() {
destructorCounter++;
}
};
BOOST_AUTO_TEST_CASE(destructor_call_test) {
{
Any a;
a.emplace<TestDestruction>();
} // scope to ensure a is destroyed
BOOST_CHECK_EQUAL(destructorCounter, 1);
}
struct ExceptionThrower {
ExceptionThrower() {
throw std::runtime_error("Exception during construction");
}
};
BOOST_AUTO_TEST_CASE(exception_safety_test) {
BOOST_CHECK_THROW(Any a{ExceptionThrower{}}, std::runtime_error);
}
```
Answer: The copy constructor moves the value from other
There is a bug in holder::clone():
return new holder<T>{std::move(item)};
You shouldn't std::move(item) if you want to clone it. Your tests all pass because you either used trivial types, or std::strings with such a short string that small-string optimization kicks in and never actually causes an allocation that would have been moved.
Let clone() return a std::unique_ptr
Use std::unique_ptrs as early as possible, this simplifies the code and leaves less chance for manual memory management errors.
About those friends
The class is very popular with lots of friends, most of which do very similar things. Is there some way I can consolidate this? Why is any_cast a separate function and not part of the class anyway? | {
"domain": "codereview.stackexchange",
"id": 45078,
"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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, reinventing-the-wheel, c++20
Probably because static_cast<>() and friends already exist, which could not have been made class members, and any_cast<>() just follows that pattern. This is actually nice; it means it's easier to learn with less surprises.
It's not a lot of friends anyway, std::any only has three: std::swap<std::any>(), std::any_cast<>() and std::make_any<>(). It's just that each of these can have multiple overloads.
It also allows the convenience of casting a pointer to a std::any to a pointer to its value, something which would not be possible with a member function (unless you give that one a different name).
In-place construction slightly wrong?
The constructor of holder that takes a variadic number of parameters uses the following to initialize item:
item{T(std::forward<Args>(args)...)}
I would expect:
item(std::forward<Args>(args)...)
Note that a type might have neither move nor copy constructors, or copying/moving might have an overhead you should avoid.
Unnecessary code
There are a few lines of code that could be removed:
Instead of defaulting it, you can just omit the destructor of Any (but keep the one in base_holder, as that one needs to be virtual).
You use the copy-and-swap idiom in the copy constructor, so you don't need to check for this != &other.
The move constructor and move assignment operators can be defaulted. | {
"domain": "codereview.stackexchange",
"id": 45078,
"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++, reinventing-the-wheel, c++20",
"url": null
} |
c++, simulation, physics
Title: Minimalistic implementation of Leapfrog integration algorithm (2)
Question: Please review this C++ listing of an implementation of Leapfrog integration.
This C++ listing is rewritten according to this review.
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <cmath>
#include <random>
#include <fstream>
typedef double real;
// Constants for Argon
constexpr real epsilon = 119.8; // Depth of the potential well (in K)
constexpr real sigma = 3.405; // Distance for zero potential (in Angstrom)
constexpr real mass = 39.948; // Mass of Argon (in amu)
struct Trajectory
{
int step_no;
real position_x;
real position_y;
real position_z;
real velocity_x;
real velocity_y;
real velocity_z;
real temperature;
};
struct Energy
{
int step_no;
real Total_energy;
real Poten_energy;
real Pot_engy_repulsive;
real Pot_engy_attractive;
real Pot_engy_balloon;
real Kinetic_engy;
};
struct Vec3
{
real x;
real y;
real z;
};
struct DataSet
{
std::vector<real> VecX;
std::vector<real> VecY;
std::vector<real> VecZ;
};
void writeEnergyToFile(const std::string& filename, const Energy& energy)
{
std::ofstream outputFile(filename, std::ios_base::app); // Open the file in append mode
if (outputFile.is_open())
{
// Write the energy values to the file
outputFile << "Step: " << energy.step_no << std::endl;
outputFile << "Total Energy: " << energy.Total_energy << std::endl;
outputFile << "Potential Energy (Repulsive): " << energy.Pot_engy_repulsive << std::endl;
outputFile << "Potential Energy (Attractive): " << energy.Pot_engy_attractive << std::endl;
outputFile << "Potential Energy: " << energy.Poten_energy << std::endl;
outputFile << "Kinetic Energy: " << energy.Kinetic_engy << std::endl; | {
"domain": "codereview.stackexchange",
"id": 45079,
"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++, simulation, physics",
"url": null
} |
c++, simulation, physics
outputFile.close(); // Close the file
}
else
{
std::cout << "Unable to open the file: " << filename.c_str() << std::endl;
}
}
// Initialize positions and velocities of particles
void initialize(int n_particles, DataSet& positionData, DataSet& velocityData, real boxSize, real maxVelocity)
{
// Create a random number generator
std::default_random_engine generator;
std::uniform_real_distribution<real> distribution(-0.5, 0.5);
// Initialize positions and velocities
for (int i = 0; i < n_particles; i++)
{
// Assign random initial positions within the box
positionData.VecX[i] = boxSize * distribution(generator);
positionData.VecY[i] = boxSize * distribution(generator);
positionData.VecZ[i] = boxSize * distribution(generator);
// Assign random initial velocities up to max_vel
velocityData.VecX[i] = maxVelocity * distribution(generator);
velocityData.VecY[i] = maxVelocity * distribution(generator);
velocityData.VecZ[i] = maxVelocity * distribution(generator);
}
}
// Derivative of the Lennard-Jones potential
Vec3 lj_force(Vec3 posVec)
{
real r_mag = std::sqrt(posVec.x * posVec.x + posVec.y * posVec.y + posVec.z * posVec.z);
real s_over_r = sigma / r_mag;
real s_over_r6 = s_over_r * s_over_r * s_over_r * s_over_r * s_over_r * s_over_r;
real s_over_r12 = s_over_r6 * s_over_r6;
real factor = 24.0 * epsilon * (2.0 * s_over_r12 - s_over_r6) / (r_mag * r_mag * r_mag);
Vec3 force;
force.x = factor * posVec.x;
force.y = factor * posVec.y;
force.z = factor * posVec.z;
return force;
}
// Update the 'accel' function
void accel(int n_particles, DataSet& accelData, DataSet& posData)
{
// Reset the acceleration to zero
for (int i = 0; i < n_particles; i++)
{
accelData.VecX[i] = 0.0;
accelData.VecY[i] = 0.0;
accelData.VecZ[i] = 0.0;
} | {
"domain": "codereview.stackexchange",
"id": 45079,
"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++, simulation, physics",
"url": null
} |
c++, simulation, physics
// Compute the acceleration due to each pair
for (int i = 0; i < n_particles; i++)
{
for (int j = i + 1; j < n_particles; j++)
{
Vec3 posVec;
posVec.x = posData.VecX[j] - posData.VecX[i];
posVec.y = posData.VecY[j] - posData.VecY[i];
posVec.z = posData.VecZ[j] - posData.VecZ[i];
Vec3 force = lj_force(posVec);
// use Lennard-Jones force law
accelData.VecX[i] += force.x / mass;
accelData.VecY[i] += force.y / mass;
accelData.VecZ[i] += force.z / mass;
accelData.VecX[j] -= force.x / mass;
accelData.VecY[j] -= force.y / mass;
accelData.VecZ[j] -= force.z / mass;
}
}
}
void leapfrog_step(int n_particles, DataSet& posData, DataSet& velocData, real dt)
{
DataSet a;
accel(n_particles, a, posData); //compute acceleration
for (int i = 0; i < n_particles; i++)
{
velocData.VecX[i] = velocData.VecX[i] + 0.5 * dt * a.VecX[i]; // advance vel by half-step
velocData.VecY[i] = velocData.VecY[i] + 0.5 * dt * a.VecY[i]; // advance vel by half-step
velocData.VecZ[i] = velocData.VecZ[i] + 0.5 * dt * a.VecZ[i]; // advance vel by half-step
posData.VecX[i] = posData.VecX[i] + dt * velocData.VecX[i]; // advance pos by full-step
posData.VecY[i] = posData.VecY[i] + dt * velocData.VecY[i]; // advance pos by full-step
posData.VecZ[i] = posData.VecZ[i] + dt * velocData.VecZ[i]; // advance pos by full-step
}
/////////accel(n_particles, a, posData); //compute acceleration
for (int i = 0; i < n_particles; i++)
{
velocData.VecX[i] = velocData.VecX[i] + 0.5 * dt * a.VecX[i]; // and complete vel. step
velocData.VecY[i] = velocData.VecY[i] + 0.5 * dt * a.VecY[i]; // and complete vel. step
velocData.VecZ[i] = velocData.VecZ[i] + 0.5 * dt * a.VecZ[i]; // and complete vel. step
}
} | {
"domain": "codereview.stackexchange",
"id": 45079,
"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++, simulation, physics",
"url": null
} |
c++, simulation, physics
int main()
{
int n_particles = 10; // number of particles
real box_size = 10.0; // size of the simulation box
real max_vel = 0.1; // maximum initial velocity
real dt = 0.01; // time step
int n_steps = 10000; // number of time steps
DataSet posData; // Positions of the particles
DataSet velData; // Velocities of the particles
// Initialize the particles
initialize(n_particles, posData, velData, box_size, max_vel);
// Run the simulation
for (int step = 0; step < n_steps; step++)
{
leapfrog_step(n_particles, posData, velData, dt);
}
return 0;
}
Answer: Use a vector math library
As already mentioned in the previous review, you should really go and use a library that defines vector types for you. This will make your life much easier and will simplify the code a lot. It will probably have performance benefits as well.
For example, using the Eigen library, you would write:
using Vec3 = Eigen::Vector3D;
Vec3 lj_force(Vec3 posVec)
{
real r_mag = posVec.norm();
…
real factor = …;
return factor * posVec;
}
…
void accel(…)
{
…
auto posVec = posData[j] - posData[i];
auto force = lj_force(posVec);
accelData[i] += force / mass;
accelData[j] -= force / mass;
…
}
Note how you no longer have to access .x, .y and .z individually anymore.
Organizing your data
You have struct Vec3, but you are hardly using it. You should have used this (or better, a vector type from a library like mentioned above) everywhere that you have a 3D vector. So for example:
struct Trajectory
{
…
Vec3D position;
Vec3D velocity;
…
};
using DataSet = std::vector<Vec3D>; | {
"domain": "codereview.stackexchange",
"id": 45079,
"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++, simulation, physics",
"url": null
} |
c++, simulation, physics
using DataSet = std::vector<Vec3D>;
The struct Trajectory does not contain a trajectory, it just contains the current state of a single particle. So Particle would have been a better name for this. I would have added a Vec3D acceleration member variable, and removed step_no and temperature: the latter two can be derived from the context and from the particle's velocity.
What is the unit of time used in the simulation?
I see that you have some specific numbers for the properties of Argon atoms, along with their units. However, I don't see anywhere mentioned what the unit of time is, and the values for the maximum velocity and timestep seem to be chosen rather arbitrarily. Make sure you define that, and ensure that the velocities and timesteps are chosen such that the errors in your simulation are not too large.
The leapstep algorithm is now incorrect
In my previous review I mentioned that you only need to update the acceleration of the particles in leapfrog_step() once. However, you are now doing it at the wrong place. The acceleration should match that of where the particles are. So, you should update the acceleration right after you have updated all the positions.
It might be good to revisit the leapfrog integration algorithm, and pay attention to the subscripts \$i\$, \$i+1/2\$ and \$i+1\$ used for the position \$x\$, velocity \$v\$ and acceleration \$a\$. | {
"domain": "codereview.stackexchange",
"id": 45079,
"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++, simulation, physics",
"url": null
} |
c, raspberry-pi
Title: Stopwatch program written in C, using Pico W
Question: I've a raspberry Pico W and developed a simple stopwatch program in C. I configured GPIO pin 15 as an input and enabled the internal pull-up resistor. If the state is high, I will start the timer and print every second, if the state is low, I will stop the timer and reset the counter to 0. This is my code. However, I know that for embedded C coding standard, we should try not to use global variables. Hence, how can I improve my code to use less global variables?
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#define BTN_PIN 15
#define TIME_INTERVAL_MS 1000
#define DEBOUNCE_TIME_MS 50
volatile bool timer_running = false;
volatile uint32_t elapsed_time = 0;
volatile bool button_state = false; // Current debounced button state
volatile uint32_t last_debounce_time_ms = 0; // Timestamp of the last state change
struct repeating_timer timer;
// Debounce function to filter out button state changes caused by noise
bool debounce(bool new_state)
{
// Get the current time in milliseconds
uint32_t current_time_ms = to_ms_since_boot(get_absolute_time());
// Check if enough time has passed since the last state change
if (current_time_ms - last_debounce_time_ms >= DEBOUNCE_TIME_MS) // Adjust the debounce time as needed
{
// Update the last state change timestamp
last_debounce_time_ms = current_time_ms;
// Update the debounced state
button_state = new_state;
}
return button_state;
}
bool repeating_timer_callback(struct repeating_timer *t)
{
if (timer_running)
{
elapsed_time++;
printf("Elapsed Time: %d seconds\n", elapsed_time);
}
return true;
}
void gpio_irq_handler(uint gpio, uint32_t events)
{
// Read the status of the button and debounce it to reduce noise
bool debounced_state = debounce(gpio_get(BTN_PIN)); | {
"domain": "codereview.stackexchange",
"id": 45080,
"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, raspberry-pi",
"url": null
} |
c, raspberry-pi
if (debounced_state)
{
// If state is high, start timer
if (!timer_running)
{
timer_running = true;
printf("Timer started\n");
add_repeating_timer_ms(TIME_INTERVAL_MS, repeating_timer_callback, NULL, &timer);
}
}
else
{
// If state is low (GND), stop timer
if (timer_running)
{
timer_running = false;
elapsed_time = 0;
cancel_repeating_timer(&timer);
printf("Timer Stopped\n");
}
}
}
int main()
{
stdio_init_all();
// Set GPIO pin 15 as input and enable its internal pull - up resistor
gpio_set_dir(BTN_PIN, GPIO_IN);
gpio_set_pulls(BTN_PIN, true, false);
// Enable interrupts on GPIO pin 15 for falling and rising edges (button pressed)
gpio_set_irq_enabled_with_callback(BTN_PIN, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, true, &gpio_irq_handler);
while (1)
;
return 0;
}
Answer: No need for volatile
There is no need to make any of your variables volatile. This is only required when using pointers to hardware registers, or when you are signaling something from an interrupt context to the main thread. However, you are not doing either.
Removing global variables
Removing global variables is good practice in general, not just for embedded programming. In fact, it's even less of an issue in embedded systems such as your Pico. First, always check if variables need to be used by multiple functions. If not, just limit them to one function. For example, button_state and last_debounce_time_ms are only used by debounce(), so you can write:
bool debounce(bool new_state)
{
static bool button_state = false;
static int last_debounce_time_ms = 0;
…
} | {
"domain": "codereview.stackexchange",
"id": 45080,
"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, raspberry-pi",
"url": null
} |
c, raspberry-pi
Note that the static here only means these variables will outlive the function call, but they are no longer in the global namespace.
You can do the same for timer_running (just print unconditionally in repeating_time_callback(), so it's only used in gpio_irq_handler()).
Very weak debouncing
Your debounce() function doesn't debounce much at all, it only prevents button_state from changing more than 20 times per second. However, if there is any noise that would temporarily cause the IO line to switch state, it could still treat that as a button press.
A much better way to debounce is to check new_state every time debounce() is called, and only update button_state if new_state has the same value for many calls in a row, or perhaps even require the same value for the whole duration of DEBOUNCE_TIME_MS.
It could be that your physical button gives a clean enough signal so that you don't have to worry about this, but I recommend implementing more robust debouncing anyway.
Go to a low power mode in the main loop
It's very good that you are using interrupts to handle timer ticks and IO line changes. However, now you have nothing left to do in the main loop. Doing while(1); will cause it to use CPU cycles though. The Pico can go into a low(er) power sleep mode and will wake up automatically if there is an interrupt. Check the SDK you are using for which functions you can use for this. Especially if you want to run your Pico from batteries, this can make the difference between hours and months of battery life. | {
"domain": "codereview.stackexchange",
"id": 45080,
"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, raspberry-pi",
"url": null
} |
php, mysql, database, mysqli, sql-injection
Title: PHP login codes suggestions
Question: Now i have a fully functional PHP codes for login and registeration i was wondering if anyone could offer improvements to the code
The code:
Config.php:
<?php
return [
'db' => [
'hostname' => 'localhost',
'username' => 'Bebo',
'password' => 'Bebo',
'database' => 'Bebo',
'port' => 3306,
],
'db_charset' => 'utf8mb4',
];
init.php:
<?php
date_default_timezone_set('Asia/Riyadh');
$error = ['Username' => '', 'Email' => '', 'Password' => ''];
$input = ['Username' => '', 'Email' => '', 'Password' => ''];
session_start();
$config = require 'Config.php';
$db = new mysqli(...$config['db']);
$db->set_charset($config['db_charset']);
Registeration.php:
<?php
require 'init.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// input validation
$Username = $input['Username'] = trim(filter_input(INPUT_POST, 'Username'));
if (mb_strlen($Username) < 3 || mb_strlen($Username) > 30) {
$error['Username'] = 'Please enter your name, it must be from 3 to 30 charaters long.';
echo "<p class='Center'> <font color=White size='50pt'>Username should be at least 3 characters long!</font> </p>";
}
$Email = $input['Email'] = trim(filter_input(INPUT_POST, 'Email'));
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$error['Email'] = 'Please enter a valid email address.';
echo "<p class='Center'> <font color=White size='50pt'>Please enter a valid email address!</font> </p>";
} else {
$result = $db->execute_query("SELECT 1 FROM users WHERE email = ?", [$Email]);
if ($result->fetch_row()) {
$error['Email'] = 'Email address already taken.';
echo "<p class='Center'> <font color=White size='50pt'>Email address already taken.Please Login!</font> </p>";
}
} | {
"domain": "codereview.stackexchange",
"id": 45081,
"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, mysql, database, mysqli, sql-injection",
"url": null
} |
php, mysql, database, mysqli, sql-injection
}
}
$Password = $input['Password'] = filter_input(INPUT_POST, 'Password');
if (strlen($Password) < 3 || strlen($Password) > 72) {
$error['Password'] = 'Please enter password, it must be from 3 to 72 characters long.';
echo "<p class='Center'> <font color=White size='50pt'>Password should be at least 3 characters long!</font> </p>";
}
// if no errors
if (implode("", $error) === '')
{
// Password MUST be hashed using the dedicated function
$Password = password_hash($input['Password'], PASSWORD_DEFAULT);
$VIP= "NO";
$Admin = "NO";
$Creation_date = date('d-M-Y h:i:s A');
$Last_Login = date('d-M-Y h:i:s A');
$Login_Times=1;
// a parameterized query MUST be used to avoid errors and injections
$stmt = $db->prepare("INSERT INTO Users (Username, Email, Password, VIP, Admin, Creation_Date, Last_login, Login_Times) VALUES (?,?,?,?,?,?,?,?)");
$stmt->execute([
$Username,
$Email,
$Password,
$VIP,
$Admin,
$Creation_date,
$Last_Login,
$Login_Times,
]);
echo "<p class='Center'> <font color=White size='50pt'>Registeration successful</font> </p>";
$_SESSION['Email'] = $Email;
header("Location: ../home.php");
die;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="4;URL=../login.php">
<link rel="stylesheet" href="../Styles/General.css">
<link rel="stylesheet" href="../Styles/Background.css">
<link rel="icon" href ="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<title>Register & Login</title>
</head> | {
"domain": "codereview.stackexchange",
"id": 45081,
"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, mysql, database, mysqli, sql-injection",
"url": null
} |
php, mysql, database, mysqli, sql-injection
<title>Register & Login</title>
</head>
<body class="Blue-Black">
<h1 class="Center">Please wait, you will be automatically redirected to the login & registeration page.</h1>
</body>
</html>
Validation.php:
<?php
require 'init.php';
$Email = $input['Email'] = trim(filter_input(INPUT_POST, 'Email'));
$Password = $input['Password'] = filter_input(INPUT_POST, 'Password');
$result = $db->execute_query("SELECT Email FROM Users WHERE Email = ?", [$Email]);
if ($result->fetch_row()) {
$select = "SELECT Password FROM Users WHERE Email = ?;";
$result2 = $db ->execute_query($select, [$Email]) ;
$Get_hash = $result2 ->fetch_assoc();
$hash = $Get_hash['Password'];
if (password_verify($Password, $hash)) {
$_SESSION['Email'] = $Email;
$Date = date('d-M-Y h:i A');
$Update = "UPDATE Users SET Last_Login = ?, Login_Times = Login_Times + 1 WHERE Users.Email = ?";
$stmt = $db->execute_query($Update, [$Date, $Email]);
header('location:../home.php');
}else{
echo "<p class='Center'> <font color=White size='50pt'>Invalid Password. Try again!</font> </p>";
}
}else{
echo "<p class='Center'> <font color=White size='50pt'>There is no account associated with this email address please sign up!</font> </p>";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="4;URL=../login.php">
<link rel="stylesheet" href="../Styles/General.css">
<link rel="stylesheet" href="../Styles/Background.css">
<link rel="icon" href ="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<title>Register & Login</title>
</head>
<body class="Blue-Black">
<h1 class="Center">Please wait, you will be automatically redirected to the login & registeration page.</h1>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 45081,
"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, mysql, database, mysqli, sql-injection",
"url": null
} |
php, mysql, database, mysqli, sql-injection
Any suggestions and improvements associated with explanation would be appreciated!!
Answer: Nice to hear you got your code working. I will help you a bit with the validation script. These are the points of improvement:
Your input filtering is not doing anything because you haven't specified the type, I added FILTER_VALIDATE_EMAIL, and used it to give feedback.
You defined $input['Email'] and $input['Password'] but never use them. I removed them.
As I said before, one of the SELECT queries is not needed. I removed one.
You can get the current time in MySQL itself, see NOW(), no need to do it in PHP.
You output HTML outside of the HTML document body when there's an error.
I really don't like the forced redirection to the login page when an error occurs. This also contradicts the header you set when the login is successful, which makes it unpredictable what will actually happen. I use a "Retry" button to go to the login page when an error occurs.
This all results in the following code:
<?php
require 'init.php'; | {
"domain": "codereview.stackexchange",
"id": 45081,
"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, mysql, database, mysqli, sql-injection",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.