text
stringlengths
1
2.12k
source
dict
c, multithreading, memory-management, linux, socket All the fields of struct Job that are not explicitly specified will be set to zero, so no more need for = 0 and memset(). Print all error messages to stderr You are inconsistent in how you are printing error messages. Make sure all of them get printed to stderr. Ideally, usage information printed after an error parsing the command line should also go to stderr. If you are targetting only Linux and/or BSD platforms, consider using err() and warn() from <err.h>, which combine printing a custom message, the result of strerror(errno), and if desired, quiting with a non-zero exit code all in one go. Or you can indeed use quit_with_error_message(), but then make sure you use it consistently. Support IPv6 Your code only works for IPv4. We've run out of IPv4 addresses, so you should really make sure your code supports IPv6 as well. It's not much work: ensure you use functions that are independent of IP version to manipulate addresses, such as getaddrinfo() and getnameinfo(). getaddrinfo() will also return the socket type that as appropriate for a given address, so you can pass that to socket(). On Linux at least, if you bind to IPv6, and make sure the socket option IPV6_V6ONLY is set to false, it will also bind to IPv4, so you only need a single listening socket to support incoming connections from both IPv4 and IPv6 addresses. Otherwise, consider creating two listening sockets; one for IPv4 and one for IPv6. Missing or incorrect error checking If getcwd() returns NULL, you assume that the only possibe error could be that the working directory name is longer than your buffer. However, there are other possible reasons it can fail. Don't make assumptions, let perror() or err() print the actual error message. send() and read() can succeed but send or receive less bytes than requested. This is especially likely for TCP sockets. Make sure you handle this scenario and send/receive the remaining bytes if this happens.
{ "domain": "codereview.stackexchange", "id": 43639, "lm_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, multithreading, memory-management, linux, socket", "url": null }
c, multithreading, memory-management, linux, socket Sometimes you don't check return values at all. For example, you don't check the return value of accept(). There are also some functions that programmers typically don't check the return value of, because errors are very unlikely, but even snprintf(), pthread_mutex_lock(), strftime() and so on can return errors. Consider for all functions you call whether it can return an error, and if so what could go wrong if you don't handle errors correctly. Don't quit due to network errors Network errors are likely to happen, are not under your control, and temporary network issues can resolve themselves after a while. If something goes wrong when receiving data from a socket or sending data to a socket, don't quit your program, instead just close the socket and wait for the next one. Clean up properly If you accept() a socket, make sure you close() it after you are done with it. Failure to do so will cause resource leaks, and may cause your program to stop after running for a while because it ran out of memory or file descriptors. If you call pthread_mutex_init(), make sure you call pthread_mutex_destroy() after you have finished using that mutex. Maybe it's not important since your program is going to exit anyway, but it helps static and runtime analyzers ensure you have no resource leaks. Denial of service attack It's easy to prevent anyone from submitting jobs to your job server: just open a TCP connection to its listening socket, and then don't send anything. Don't sleep unnecessarily There is a sleep(1) in server(). Why force a one second wait between incoming connections? It does not seem useful, and will only make job submissions take longer than necessary.
{ "domain": "codereview.stackexchange", "id": 43639, "lm_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, multithreading, memory-management, linux, socket", "url": null }
c, multithreading, memory-management, linux, socket The calls to usleep() are also problematic. First, usleep() is a deprecated POSIX function, you should use nanosleep() or clock_nanosleep() instead. Apart from that, don't assume that sleeping for a bit after kill() is enough to ensure that the process you just sent SIGKILL are really killed. In any case, you either wait longer than necessary, or not long enough. Consider using waitpid() without WNOHANG to wait until a process is no longer running. As for the sleep(1) inside queue(), you do want to sleep if there are no jobs to run, otherwise it would just spin and keep the CPU busy for no good reason. But again, just sleeping a random amount of time is not great, as it puts a limit on the number of jobs you can run in a given amount of time. In this case, use a condition variable that you signal inside server() whenever a new job is submitted, and which you wait for in queue(). For waking up if a job process has exited, you can register a handler for SIGCHILD Don't call external programs unnecessarily
{ "domain": "codereview.stackexchange", "id": 43639, "lm_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, multithreading, memory-management, linux, socket", "url": null }
c, multithreading, memory-management, linux, socket The setting of CPU affinities is ultimately done over taskset, although I feel I could have implemented that myself aswell, [...] Starting an external program has lots of issues. Apart from the large amount of code you had to write, the nasty string manipulation you had to do, it is very inefficient. taskset is Linux-specific anyway, so since you don't have to worry about being platform independent, just use sched_setaffinity() to change the core affinity mask of a given process. Missing mutex for available_cores Several threads can modify available_cores, but no lock is taken to ensure the value is modified atomically. This means the core mask can potentially become corrupt, and either too many jobs will run simultaneously, or not all cores will be used. A simple solution is to add a mutex for it, or to use one of the existing mutexes to guard this variable.
{ "domain": "codereview.stackexchange", "id": 43639, "lm_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, multithreading, memory-management, linux, socket", "url": null }
java, bitwise Title: Integer multiplication without using multiply operator Question: I wrote a method that multiplies two integers. Is there a faster approach that doesn't use the * operator? The method mult(a, b) multiplies two arbitrary integers. Is there a quicker way to multiply two numbers, without using * in java? static int mult(int a, int b) { if (a > b) return recMult(a, b); return recMult(b, a); } static int recMult(int max, int min) { if (min <= 1) return min == 1 ? max : 0; int cntOfMin = 0, i = 1; while ((i = i << 1) <= min) cntOfMin++; return (max << cntOfMin) + recMult(max, min - (1 << cntOfMin)); } This method doesn't work on negative numbers and doesn't handle overflows. Answer: Your heuristic is not optimal. recMult is using binary arithmetic to multiply two numbers. It recurses a number of times based on the number of 1-bits in the second number. You pass in the smaller of the two numbers as the second number, but there is no guarantee the smaller number has fewer 1-bits. Consider 8 * 7, or in binary, 1000 * 111. The 7 is the smaller number, so you use it as the second argument, and you compute (8 << 2) + (8 << 1) + (8 << 0) + 0. If you had chosen to 8 as the second argument, you would have computed (7 << 3) + 0 ... far fewer operations. The function Integer.bitCount(int i) returns the number of 1-bits in an integer. Using this, we could rewrite mult(int a, int b) as follows: static int mult(int a, int b) { if (Integer.bitCount(a) > Integer.bitCount(b)) return recMult(a, b); return recMult(b, a); }
{ "domain": "codereview.stackexchange", "id": 43640, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, bitwise", "url": null }
java, bitwise The result should be faster. Similarly, Java provides several functions in the Integer class which can directly extract the 1-bits found in an integer. These are .lowestOneBit(i), .highestOneBit(i), .numberOfLeadingZeros(i), and .numberOfTrailingZeros(i). The last function is most useful here, as the number of trailing zeros corresponds to the bit position of the least significant 1-bit. For example, 8, or 1000 has 3 trailing zeros, and (1 << 3) == 8. Using this to simplify rectMult(), we could get something like: private static int recMult(int multiplicand, int multiplier) { int product = 0; while (multiplier != 0) { int shift = Integer.numberTrailingZeros(multiplier); product += multiplicand << shift; multiplier -= 1 << shift; } return product; } Since the second number is no longer guaranteed to be the smaller of the two, I've renamed max and min to multiplicand and multiplier. I've also replaced the recursion with a simple loop, which should additionally speed things up. Additionally, I've declared this helper function private, since it is unlikely other classes will use it.
{ "domain": "codereview.stackexchange", "id": 43640, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, bitwise", "url": null }
c#, performance, asp.net-core, asp.net-web-api, entity-framework-core Title: Is it optimal way to filter records from table using Entity Framework? Question: I have the SQL Products table migrated from MongoDb and I use ASP Core + MediatR. The filtering data comes from frontend Autocompletes where user can select multiple values (3 different ProductGroups + 2 different Suppliers for example). Wanted to ask is my implementation optimal, or did I miss something? Below the code for action: [HttpPut("[action]")] public async Task<IQueryable<ArticleDto>> Put([FromBody] ProductsQueryAll query) { var response = await _mediator.Send(query); return response; } And below the code for MediatR model and Handler: public class ProductsQueryAll : IRequest<IQueryable<ArticleDto>> { public string[] ProductGroups { get; set; } public int[] SupplierIds { get; set; } public string[] Categories { get; set; } } public class ProductsQueryAllHandler : IRequestHandler<ProductsQueryAll, IQueryable<ArticleDto>> { private readonly DbContext _dbContext; private readonly IMapper _mapper; public ProductsQueryAllHandler(DbContext dbContext, IMapper mapper) { _dbContext = dbContext; _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); }
{ "domain": "codereview.stackexchange", "id": 43641, "lm_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#, performance, asp.net-core, asp.net-web-api, entity-framework-core", "url": null }
c#, performance, asp.net-core, asp.net-web-api, entity-framework-core public Task<IQueryable<ArticleDto>> Handle(ProductsQueryAll request, CancellationToken cancellationToken) { var predicate = PredicateBuilder.True<ArticleDm>(); if (request.ProductGroups?.Length > 0) { predicate = predicate.And(x => request.ProductGroups.Any(y => y == x.ProductGroup)); } if (request.SupplierIds?.Length > 0) { predicate = predicate.And(x => request.SupplierIds.Any(y => y == x.SupplierId)); } if (request.Categories?.Length > 0) { predicate = predicate.And(x => request.Categories.Any( y => y == x.Category)); } var entityList = _dbContext.Articles .AsNoTracking() .Where(predicate); return Task.FromResult(_mapper.ProjectTo<ArticleDto>(entityList)); } }
{ "domain": "codereview.stackexchange", "id": 43641, "lm_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#, performance, asp.net-core, asp.net-web-api, entity-framework-core", "url": null }
c#, performance, asp.net-core, asp.net-web-api, entity-framework-core return Task.FromResult(_mapper.ProjectTo<ArticleDto>(entityList)); } } Answer: Small syntax improvements Foo?.Length > 0 can always be refactored to Foo?.Any() x => request.SupplierIds.Any(y => y == x.SupplierId) can be somewhat improved by using x => request.SupplierIds.Contains(x.SupplierId) I don't particularly like the name ProductsQueryAll. ProductsQuery seems more appropriate. "All" implies that you're going to get all of them, which is not the case since you're allowing filters. That being said, there may be circumstances that I'm not aware of that help explain why your name could make sense, e.g. to disambiguate it from something very similar. I'm aware that this is not something everyone agrees on, but I find the _ prefix for private fields superfluous, and simply use camelcasing (context, mapper). That being said, you might be subjected to an existing coding style, at which point I do agree that conformity to the rest of the existing codebase and development team style is more important. Query logic Because of the nature of your filtering logic, you could've omitted the predicate builder and instead chained your Where calls directly. I tend to structure this kind of logic like so: var query = _dbContext.Articles.AsQueryable(); if (request.ProductGroups?.Any()) query = query.Where(x => request.ProductGroups.Contains(x.ProductGroup)); if (request.SupplierIds?.Any()) query = query.Where(x => request.SupplierIds.Contains(x.SupplierId)); if (request.Categories?.Any()) query = query.Where(x => request.Categories.Contains(x.Category));
{ "domain": "codereview.stackexchange", "id": 43641, "lm_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#, performance, asp.net-core, asp.net-web-api, entity-framework-core", "url": null }
c#, performance, asp.net-core, asp.net-web-api, entity-framework-core Returning an IQueryable This is something you should avoid at all costs. Do not return IQueryable. Your return type should be IEnumerable. Also note that it is easy to still return an IQueryable even when your return type is IEnumerable (since IQueryable : IEnumerable), but you should actively avoid this. This is done by enumerating your IQueryable, most commonly done via ToList or ToListAsync. Building this off of my previous suggestion: public async Task<IEnumerable<ArticleDto>> Handle(ProductsQueryAll request, CancellationToken cancellationToken) { // see previous snippet return await query .ProjectTo<ArticleDto>(mapper.ConfigurationProvider) .ToListAsync(); } Small things to point out: Since you're working asynchronously, you should make this method actually asynchronous so you can benefit the most from it. ProjectTo has two signatures. You used mapper.ProjectTo(query) (oversimplified), but I prefer query.ProjectTo(mapper) (oversimplified) because it's more consistent with the rest of the syntax being used here, because it's always of the form query.Method(...).
{ "domain": "codereview.stackexchange", "id": 43641, "lm_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#, performance, asp.net-core, asp.net-web-api, entity-framework-core", "url": null }
python, python-3.x, web-scraping, tkinter, selenium Title: Scrape PokeDex and display in tkinter Question: Hi I am new here and I just completed my first working version of a pokedex app with a GUI using tkinter. I used selenium to scrape the data from pokemondb.net, and then used pandas to clean up the dataset then finished it up with a tkinter GUI. The project is still in early stages and can be improved in the front and backend. However, I do not have a specific question. I simply would like to receive feedback and an honest opinion of the project so far in the development process. I would be happy for any suggestions on improving the user interface also, and making it more aesthetically appealing as well. I have the entire project posted on github, however I am not sure if posting the link would be allowed here, so instead I'll post the code here. #pokedex.py from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import sys import os import numpy as np import pandas as pd import matplotlib as plt file_path = 'drivers/chromedriver.exe' driver = webdriver.Chrome(file_path) # assign the driver path to variable driver.execute("get", {'url': 'https://pokemondb.net/pokedex/all'}) driver.minimize_window() # minimize window data = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "table#pokedex"))).get_attribute("outerHTML") df = pd.read_html(data) df = df[0] driver.close() # close driver, end session columns = ['id', 'name', 'type', 'total', 'hp', 'attack', 'defense', 'special-attack', 'special-defense', 'speed'] # column names (labels) for dataset df.set_index("#", inplace=True) # set the id column to be the index os.makedirs('C:/Users/Salah/Documents/apps/pokedex-app/datasets', exist_ok=True) # create new folder in project directory to store dataset
{ "domain": "codereview.stackexchange", "id": 43642, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, web-scraping, tkinter, selenium", "url": null }
python, python-3.x, web-scraping, tkinter, selenium df.to_csv("datasets/pokedex.csv", index=False) # converts dataset to csv file df = pd.read_csv('datasets/pokedex.csv') # read and save file and check the first 5 entries df.head() for name in df.Name: if name.__contains__('Mega '): mega_id = df.index[df['Name'] == name].tolist() #print(mega_id) df.Name[mega_id] = name.split(' ', 1)[1] poke_list = list(df.Name[:]) poke_list df.head(10) #gui.py from os import times import tkinter as tk #from tkinter import ttk from PIL import ImageTk, Image from turtle import color, width from xmlrpc.client import loads from pokedex import * #window window = tk.Tk() #main window.title('Universal Pokedex') window.configure(background="red") window.iconbitmap("images/icon.ico") bg_image = tk.PhotoImage(file="images/pokedex.gif") canvas = tk.Canvas(window, height=700, width=800) canvas.pack() frame = tk.Frame(window, bg='red') frame.place(relwidth=1, relheight=1) #window def validate_text(): global entry string = entry.get() #label_2.configure(text=string) string = string.title() # capitalize first letter of entry to match database if string not in poke_list: # ensure the user is typing in valid input, if not create a validation loop by reiterating user to give valid pokemon name or id. label_2.configure(text="That pokemon was not found, please try again: ") # validation look/error trap string = string.title() if string in poke_list: print("Searching for {} ... ".format(string)) print("{} Found!".format(string)) poke_stats = df.loc[df['Name'] == string] # return pokemon stats to user if successfully located label_2.configure(text=poke_stats)
{ "domain": "codereview.stackexchange", "id": 43642, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, web-scraping, tkinter, selenium", "url": null }
python, python-3.x, web-scraping, tkinter, selenium #phsyical properties label_1 = tk.Label(window, text="Welcome to the Universal Pokedex! This program contains the statistics of all the pokemon stored in the official Pokemon Database. \n Begin by entering a pokemon name below.", bg='red', font=("Cambria", 25)) label_1.place(relx=0, rely=0.05, relwidth=1, relheight=0.1) label_2 = tk.Label(window, text="Enter a pokemon name to see a list of its stats: ", bg='#5CB3FF', font=("Courier", 20)) label_2.place(relx=0, rely=0.78, relwidth=1, relheight=0.1) img1 = ImageTk.PhotoImage(Image.open("images/johto-starters.gif")) img2 = ImageTk.PhotoImage(Image.open("images/pokeball.gif")) label_3 = tk.Label(window, bg='red', image=img1) # This label will contain the entered pokemon's image label_3.place(relx=0.25, rely=0.25, relwidth=0.50, relheight=0.50) label_4 = tk.Label(window, bg='white', image=img2) label_4.place(relx=0.05, rely=0.3, relwidth=0.2, relheight=0.3) label_5 = tk.Label(window, bg='white', image=img2) label_5.place(relx=0.75, rely=0.3, relwidth=0.2, relheight=0.3) entry = tk.Entry(window, bg='white') entry.place(relx=0.42, rely=0.89, relwidth=0.15, relheight=0.04) button = tk.Button(window, text="Search", command=validate_text, bg='grey') button.place(relx=0.42, rely=0.94, relwidth=0.15, relheight=0.05) #physical properties #widgets #widgets window.mainloop() #mainloop ``` Answer: Selenium is not necessary for this project so don't use it. You can go direct to requests. This website doesn't have an API but others do; you should prefer them instead. Even better, you should have an offline database embedded in your program since it never changes. Perhaps that's why you read_csv; this would be more useful if you first check for the existence of a CSV and only scrape in the application if it doesn't exist. These: import sys import os import numpy as np import matplotlib as plt
{ "domain": "codereview.stackexchange", "id": 43642, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, web-scraping, tkinter, selenium", "url": null }
python, python-3.x, web-scraping, tkinter, selenium aren't needed, so delete them. A decent IDE will show you which imports are unneeded. Move your global code into functions and/or classes. There isn't much point in redefining your column names - the defaults as scraped from Pandas are actually nicer for presentation purposes. Don't use for loops in Pandas. Your string operation is simple and vectorisable. Don't cast to a list. Your colours make my eyes bleed. Call me boring, but it's rarely justifiable to override colours and fonts. Your layout can be simplified by use of grid calls. You don't need a button if you search whenever the user updates their search term in the entry box. You should make better use of tk StringVar to decouple your data from your UI. Future improvements could include calling into a fuzzy-matching library to do inexact string search, and displaying your search results in multiple rows in a real tkinter TreeView instead of dumping them to a string. Suggested Covering some of the above, import tkinter as tk from threading import Thread from typing import Optional import pandas as pd import requests def load_data() -> pd.DataFrame: print('Retrieving data...') with requests.get( 'https://pokemondb.net/pokedex/all', headers={'User-Agent': 'Mozilla/5.0'}, ) as response: response.raise_for_status() df, = pd.read_html( io=response.text, flavor='bs4', index_col='#', ) df['SearchKey'] = df.Name.str.lower() df[['Name', 'Mega']] = df.Name.str.split(' Mega ', n=1, expand=True) return df class GUI: def __init__(self) -> None: window = tk.Tk() window.title('Universal Pokedex') self.run = window.mainloop frame = tk.Frame(window) frame.pack()
{ "domain": "codereview.stackexchange", "id": 43642, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, web-scraping, tkinter, selenium", "url": null }
python, python-3.x, web-scraping, tkinter, selenium tk.Label( frame, text='Welcome to the Universal Pokedex! This program contains the ' 'statistics of all the pokemon stored in the official Pokemon ' 'Database.\n' 'Begin by entering a pokemon name below.', justify='left', wraplength=200, ).grid(row=0, column=0, columnspan=2) tk.Label( frame, text='Pokemon name: ', ).grid(row=1, column=0) self.search_term = tk.StringVar(frame, name='search_term') self.entry = tk.Entry( frame, textvariable=self.search_term, state='disabled', ) self.entry.grid(row=1, column=1) self.result = tk.StringVar(frame, name='result', value='Loading...') tk.Label( frame, textvariable=self.result, ).grid(row=2, column=0, columnspan=2) self.data: Optional[pd.DataFrame] = None def set_data(self, data: pd.DataFrame) -> None: self.data = data self.result.set('') self.entry.configure(state='normal') self.search_term.trace_add('write', self.search) def search(self, name: str, _, mode: str) -> None: term = self.search_term.get().lower() if term: predicate = self.data.SearchKey.str.contains(term) matches = self.data[predicate].iloc[:1] if len(matches): first = matches.iloc[0, :] self.result.set(str(first)) return self.result.set('') def main() -> None: gui = GUI() def fetch_data() -> None: data = load_data() gui.set_data(data) data_thread = Thread(target=fetch_data) data_thread.start() gui.run() if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43642, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, web-scraping, tkinter, selenium", "url": null }
go, caesar-cipher Title: caesar cipher decoder and encoder - go Question: I implemented my first algorithm in golang - the caesar cipher. Is there something i could do more efficiently? I am quite new to go and any improvement suggestions are welcome. package main import "fmt" // +1 encoding, -1 decoding func main() { var text string var choice int var shift int fmt.Print("Text: ") fmt.Scanf("%s", &text) fmt.Print("+1 encoding, -1 decoding: ") fmt.Scanf("%d", &choice) fmt.Print("Shift: ") fmt.Scanf("%d", &shift) fmt.Println(cipher(text, choice, shift)) } func cipher(text string, choice int, shift int) string{ chars := []rune(text) var result string for i := 0; i < len(chars); i++ { if chars[i] >= 'a' && chars[i] <= 'z' || chars[i] >= 'A' && chars[i] <= 'Z' { dchar := chars[i] + rune(shift*choice) if dchar >= 'a' && dchar <= 'z' || dchar >= 'A' && dchar <= 'Z' { result += string(dchar) } else { result += string(dchar + rune(-26 * choice)) } } else { result += string(chars[i]) } } return result } Answer: Your API does not appear to be a thoughtful design: func cipher(text string, choice int, shift int) string A good API design follows the shape of the problem, not the implementation. The problem: Wikipedia: Caesar cipher Wikipedia:Encryption Wikipedia: Inverse function The general shape of the Caesar cipher is an encryption inverse function. For the Caesar cipher, an encryption package API, package caesar func Encrypt(plain string, key int) string func Decrypt(cipher string, key int) string with the encryption inverse function form plain = caesar.Decrypt(caesar.Encrypt(plain, key), key)
{ "domain": "codereview.stackexchange", "id": 43643, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, caesar-cipher", "url": null }
go, caesar-cipher with the encryption inverse function form plain = caesar.Decrypt(caesar.Encrypt(plain, key), key) Your cipher implementation function is not correct. For example, it fails the Wikipedia: Caesar cipher example: Example: func main() { var plainText = `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG` fmt.Println(plainText) var cipherText = `QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD` fmt.Println(cipherText) var key = -3 fmt.Println(key) fmt.Println(cipher(cipher(plainText, +1, key), -1, key)) } Output: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD -3 THE QUI&K %ROWN FOX JUMPS OVER THE L$ZY DOG Your cipher implementation function is orders of magnitude too expensive. Your cipher function versus reasonably efficient package caesar functions: name time/op Cipher-8 9.32µs ± 0% Caesar-8 502ns ± 0% name alloc/op Cipher-8 2.98kB ± 0% Caesar-8 192B ± 0% name allocs/op Cipher-8 172 ± 0% Caesar-8 4.00 ± 0% Amongst other things, your frequent use of immutable string concatenation (+=) is expensive. Here is a revised version of your code that addresses my code review issues. package main import "fmt" func caesar(text string, key int) string { shift := key % 26 c := make([]byte, len(text)) for i, b := range []byte(text) { lower := b | 0x20 // ASCII lower case if 'a' <= lower && lower <= 'z' { base := int('A') if b == lower { base |= 0x20 // ASCII lower case } b = byte(base + (int(b)-base+shift+26)%26) } c[i] = b } return string(c) } func Encrypt(plain string, key int) string { return caesar(plain, key) } func Decrypt(cipher string, key int) string { return caesar(cipher, -key) }
{ "domain": "codereview.stackexchange", "id": 43643, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, caesar-cipher", "url": null }
go, caesar-cipher func Decrypt(cipher string, key int) string { return caesar(cipher, -key) } func main() { Plaintext := `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG` fmt.Println(Plaintext) Ciphertext := `QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD` fmt.Println(Ciphertext) Key := -3 fmt.Println(Key) fmt.Println(Encrypt(Plaintext, Key)) fmt.Println(Decrypt(Encrypt(Plaintext, Key), Key)) } https://go.dev/play/p/7sDXyIcVFpc THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD -3 QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
{ "domain": "codereview.stackexchange", "id": 43643, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, caesar-cipher", "url": null }
java, strings, interview-questions Title: Checking if a string contains all unique characters Question: I am currently reviewing CTCI(Cracking the Coding Interview) The question is asking me to implement an algorithm which checks whether the characters in a string are all unique however they do not want me to use any auxillary data structures My Algorithm is relatively straight forward, Two nested loops one starting at 0(i) and another at 1(i+1) If the condition finds two characters that are equal then I print duplicate characters have been found. public static void checkUnique(String s) { for(int i = 0; i<s.length(); ++i) { for(int j = i +1; j<s.length(); ++j) { if(s.charAt(i) == s.charAt(j)) { System.out.println("Duplicates found"); } } } } My question Is this an optimal algorithm, my second approach was to sort, and find a pair which contains the same characters. Obviously a hashmap would be beneficial here, but questions does not really want me to use it. I have refactored the code and hopefully now it is correct. Is there any way of reducing it to an O(N) runtime. What if we keep track of the Unicode code's for each char character. I doubt O(N^2) is the best we can do here. Answer: A way to optimize it would be to return as soon as you have found a duplicate, unless the question specifically asks you to list all duplicates. You could refactor it to something like that: public static boolean checkUnique(String s) { int len = s.length(); for (int i = 0; i < len; i++) { int c = s.codePointAt(i); int next = s.indexOf(c, i + 1); if (next > i) { return false; } } return true; } It isn't more efficient as your solution, but I doubt there is an algorithm that can do it better.
{ "domain": "codereview.stackexchange", "id": 43644, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, interview-questions", "url": null }
java, algorithm, interview-questions Title: Add one to a number represented as an array of digits Question: I submitted this problem for an interview, and I was wondering if I could have done better. My solution works, and I solved in about 12-15 minutes. I feel like I did a bad job with the code. Please be honest. Here is the question: Given a non-negative number represented as an array of digits, plus one to the number. Also, the numbers are stored such that the most significant digit is at the head of the list. In particular, what stumped me was the fact that I'd get the right answer, but have the initial index (at 0) in sometimes empty with the answer on the other half, and couldn't figure out a quick half to shift all the elements to the left without using extra storage. public int[] plusOne(int[] digits) { int[] toRet=new int[digits.length+1]; int[] temp=null; for(int i=toRet.length-1; i>=0; i--){ if(i-1>=0){ toRet[i]=digits[i-1]; } } for(int i=toRet.length-1; i>=0; i--){ if(toRet[i]+1 == 10){ toRet[i]=0; } else{ toRet[i] = toRet[i]+1; break; } } if(toRet[0]==0){ temp = new int[toRet.length-1]; for(int i=1; i<toRet.length;i++){ temp[i-1] = toRet[i]; } return temp; } else{ return toRet; } } Answer: What you did well I like that you have: decently named varaibles you use good backward looping through the data the formatting and style is good. Issues you are doing a lot of manual copying... Arrays.copyOf() is your friend. you should be declaring variables where you need them, not at the beginning of the method (temp). the algorithm is not a natural fit for the problem.... too complicated, and that is why there is the odd offset in your results.
{ "domain": "codereview.stackexchange", "id": 43645, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, interview-questions", "url": null }
java, algorithm, interview-questions Alternative... Consider this code alternative, which uses a standard adder-with-carry: public static final int[] addOne(int[] digits) { int carry = 1; int[] result = new int[digits.length]; for (int i = digits.length - 1; i >= 0; i--) { int val = digits[i] + carry; result[i] = val % 10; carry = val / 10; } if (carry == 1) { result = new int[digits.length + 1]; result[0] = 1; } return result; } The carry is initialized with the value-to-add 1, and it is added to the least significant value. If the overall addition results in a carry still, then we add a new digit to the result, and, because the sub being added is a 1, we can make assumptions about the result. Edit: My test code: public static void main(String[] args) { System.out.println(Arrays.toString(addOne(new int[]{}))); System.out.println(Arrays.toString(addOne(new int[]{1}))); System.out.println(Arrays.toString(addOne(new int[]{9}))); System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9}))); System.out.println(Arrays.toString(addOne(new int[]{3, 9, 9, 9}))); System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 9}))); System.out.println(Arrays.toString(addOne(new int[]{9, 9, 9, 8}))); } and my results: [1] [2] [1, 0] [4, 0, 0] [4, 0, 0, 0] [1, 0, 0, 0, 0] [9, 9, 9, 9]
{ "domain": "codereview.stackexchange", "id": 43645, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, algorithm, interview-questions", "url": null }
python, python-3.x, multithreading, beautifulsoup, python-requests Title: Monitoring webpages to be notified Question: I have been writing a monitoring script where I check for whenever there is changes on a webpage. When a change has happend I want to be notified by printing out that there is a difference. I have also written a spam filter function that could be caused due to a cache issue where a repo count can go from a old count to a new and back... Here is the code import sys import threading import time from datetime import datetime, timedelta from typing import Union import requests from bs4 import BeautifulSoup from loguru import logger URLS: set = set() def filter_spam(delay: int, sizes: dict, _requests) -> Union[dict, bool]: """Filter requests to only those that haven't been made previously within our defined cooldown period.""" # Get filtered set of requests. def evaluate_request(r): return r not in _requests or datetime.now() - _requests[r] >= timedelta(seconds=delay) if filtered := [r for r in sizes if evaluate_request(r)]: # Refresh timestamps for requests we're actually making. for r in filtered: _requests[r] = datetime.now() return _requests return False class MonitorProduct: def __init__(self): self._requests: dict[str, datetime] = {} self.previous_state = {} def doRequest(self, url): while True: if url not in URLS: logger.info(f'Deleting url from monitoring: {url}') sys.exit() response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser')
{ "domain": "codereview.stackexchange", "id": 43646, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, multithreading, beautifulsoup, python-requests", "url": null }
python, python-3.x, multithreading, beautifulsoup, python-requests if soup.find("span", {"data-search-type": "Repositories"}): # if there are sizes self.compareData({ 'title': soup.find("input", {"name": "q"})['value'], 'repo_count': {soup.find("span", {"data-search-type": "Repositories"}).text.strip(): None} }) else: logger.info(f"No diff for {url}") else: logger.info(f"Error for {url} -> {response.status_code}") time.sleep(30) def compareData(self, data): if self.previous_state != data: if filter_spam(3600, data['repo_count'], self._requests): logger.info(f"The data has been changed to {data}") self.previous_state = data # mocked database def database_urls() -> set: return { 'https://github.com/search?q=hello+world', 'https://github.com/search?q=python+3', 'https://github.com/search?q=world', 'https://github.com/search?q=wth', } if __name__ == '__main__': while True: db_urls = database_urls() # get all urls from database diff = db_urls - URLS URLS = db_urls # Replace URLS with db_urls to get the latest urls # Start the new URLS for url in diff: logger.info(f'Starting URL: {url}') threading.Thread(target=MonitorProduct().doRequest, args=(url,)).start() time.sleep(10)
{ "domain": "codereview.stackexchange", "id": 43646, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, multithreading, beautifulsoup, python-requests", "url": null }
python, python-3.x, multithreading, beautifulsoup, python-requests time.sleep(10) The code is working pretty good however I have written a mocked database where it will constantly be pulled every 10s (If I need to higher it up, please explain to me why) - The reason I wrote a mocked data is that to be able to show you people how it is working. The idea will be to read from database (postgresql through peewee) - I also used Github as an example where it was easiest for me to get the values I want to compare against. I am aware that there is an API for Github but for my situation, I would like to get a better knowledge regarding beautifulsoup therefore I use bs4. To mention it again, the point for me with this script is that I would like to get notified whenever something has been changed on the webpage. I hope I could get a feedback from you lovely code reviewer!
{ "domain": "codereview.stackexchange", "id": 43646, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, multithreading, beautifulsoup, python-requests", "url": null }
python, python-3.x, multithreading, beautifulsoup, python-requests Answer: URLS should not be global. There's a better name for filter_spam, since it isn't spam you're filtering; but I can't get more inventive than "change filter". The algorithm here is probably inefficient - you have no mechanism to purge requests once they've exceeded your cooloff. Another big problem is that this method, though it exists in the global namespace, mutates a class member. Better to only return bool, and also to be a member of your class. An improved algorithm could keep a combined FIFO queue and hash table, represented by an ordered dict. It's important that you use a session instead of making an isolated get() every time. Put your response in context management. Don't check status_code in your case; just check ok. Do as much computation up-front as possible for BeautifulSoup, using both a strainer and a CSS sieve. You're not looking at a very useful element span. Have you noticed that often it returns a numeric contraction, 1M? You should look at the h3 instead. I don't understand why you're passing around your repo_count as a dictionary of a single integer key to a None value. Don't do this. Don't if self.previous_state != data; your filter does that for you. Don't bake https://github.com/search into your database; only your search term varies so only use that. It's good that you have a __main__ guard but it isn't enough. All of those symbols are still globally visible. Make a main() function. You already have a thread context object, MonitorProduct, so why also require a url parameter? That can be moved to the object. exit() doesn't seem like what you actually want. If you want to exit the thread, just return. Suggested import locale import logging import soupsieve import threading import time from collections import OrderedDict from datetime import datetime from typing import Callable from bs4 import BeautifulSoup from bs4.element import SoupStrainer from requests import Session logger = logging.getLogger()
{ "domain": "codereview.stackexchange", "id": 43646, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, multithreading, beautifulsoup, python-requests", "url": null }
python, python-3.x, multithreading, beautifulsoup, python-requests logger = logging.getLogger() class MonitorProduct: STRAINER = SoupStrainer(name='main') SIEVE = soupsieve.compile('div.position-relative h3') def __init__(self, term: str, is_alive: Callable[[str], bool]) -> None: self.is_alive = is_alive self.term = term self.requests: OrderedDict[int, datetime] = OrderedDict() self.session = Session() def do_request(self) -> None: while True: if not self.is_alive(self.term): logger.info(f'Deleting term from monitoring: "{self.term}"') return with self.session.get( url='https://github.com/search', params={'q': self.term}, headers={'Accept': 'text/html'}, ) as response: if not response.ok: logger.info(f"Error for {self.term} -> {response.status_code}") continue soup = BeautifulSoup(markup=response.text, features='html.parser', parse_only=self.STRAINER) result_head = self.SIEVE.select_one(soup) if result_head: result = result_head.text.strip() logger.debug(f'Results for {self.term}: {result}') repo_count = locale.atoi(result.split(maxsplit=1)[0]) else: repo_count = 0 self.compare_data(repo_count) time.sleep(30) def compare_data(self, repo_count: int) -> None: if self.filter_dupes(repo_count): logger.info(f"The data for term {self.term} has been changed to {repo_count}") def filter_dupes(self, repo_count: int, delay: int = 60 * 60) -> bool: """Filter requests to only those that haven't been made previously within our defined cooldown period."""
{ "domain": "codereview.stackexchange", "id": 43646, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, multithreading, beautifulsoup, python-requests", "url": null }
python, python-3.x, multithreading, beautifulsoup, python-requests # Purge old entries now = datetime.now() while self.requests: oldest = next(iter(self.requests.values())) if (now - oldest).total_seconds() > delay: self.requests.popitem(last=False) else: break # Check current entry if repo_count in self.requests: return False self.requests[repo_count] = now return True # mocked database def database_terms() -> set[str]: return { 'hello world', 'python 3', 'world', 'wth', } def main() -> None: logging.basicConfig(level=logging.DEBUG) terms: set[str] = set() # Needs to match the locale of github.com locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') while True: db_terms = database_terms() # get all terms from database terms.clear() terms |= diff # Replace URLS with db_terms to get the latest terms # Start the new URLS for url in diff: logger.info(f'Starting URL: {url}') threading.Thread( target=MonitorProduct(url, terms.__contains__).do_request ).start() time.sleep(10) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43646, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, multithreading, beautifulsoup, python-requests", "url": null }
python, python-3.x, multithreading, beautifulsoup, python-requests time.sleep(10) if __name__ == '__main__': main() Output INFO:root:Starting URL: wth INFO:root:Starting URL: hello world INFO:root:Starting URL: world INFO:root:Starting URL: python 3 DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): github.com:443 DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): github.com:443 DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): github.com:443 DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): github.com:443 DEBUG:urllib3.connectionpool:https://github.com:443 "GET /search?q=wth HTTP/1.1" 200 None DEBUG:root:Results for wth: 1,550 repository results INFO:root:The data for term wth has been changed to 1550 DEBUG:urllib3.connectionpool:https://github.com:443 "GET /search?q=python+3 HTTP/1.1" 200 None DEBUG:root:Results for python 3: 101,658 repository results DEBUG:urllib3.connectionpool:https://github.com:443 "GET /search?q=world HTTP/1.1" 200 None INFO:root:The data for term python 3 has been changed to 101658 DEBUG:root:Results for world: 1,981,644 repository results INFO:root:The data for term world has been changed to 1981644 DEBUG:urllib3.connectionpool:https://github.com:443 "GET /search?q=hello+world HTTP/1.1" 200 None DEBUG:root:Results for hello world: 1,733,873 repository results INFO:root:The data for term hello world has been changed to 1733873
{ "domain": "codereview.stackexchange", "id": 43646, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, multithreading, beautifulsoup, python-requests", "url": null }
java, interview-questions, complexity, simulation Title: Given the arrival times of people at a door, resolve their passage times Question: I was trying to solve the following question: You are given 2 arrays: one representing the time people arrive at a door and other representing the direction they want to go (in or out) You have to find at what time each person will use the door provided no 2 people can use the door at the same time. Constraints: the door starts with ‘in’ position, in case of a conflict (2 or more people trying to use the door at the same time), the direction previously used holds precedence. If there is no conflict whoever comes first uses the door. Also if no one uses the door, it reverts back to the starting ‘in’ position. Should be linear time complexity. Is this a good approach? Can I get my code reviewed / refactored? Any advice regarding the following approach? Is there a better way to do this? public class Doors { public class visitor { int time; String dir; public visitor(int time, String dir) { this.time = time; this.dir = dir; } } public String defaultDir = "In"; public String lastDir = defaultDir; public static void main(String[] args) { int[] time = new int[] { 2, 3, 5, 1, 7, 4, 2 }; String dir[] = new String[] { "In", "Out", "In", "Out", "Out", "In", "Out" }; Doors obj = new Doors(); obj.findTime(time, dir); } private void findTime(int[] time, String[] dir) {
{ "domain": "codereview.stackexchange", "id": 43647, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, complexity, simulation", "url": null }
java, interview-questions, complexity, simulation private void findTime(int[] time, String[] dir) { Map<Integer, Map<String, List<visitor>>> myMap = new TreeMap<>(); for (int i = 0; i < time.length; i++) { List<visitor> myList = new ArrayList<Doors.visitor>(); if (!myMap.containsKey(time[i])) { Map<String, List<visitor>> visitorMap = new HashMap<String, List<visitor>>(); myList.add(new visitor(time[i], dir[i])); visitorMap.put(dir[i], myList); myMap.put(time[i], visitorMap); } else { Map<String, List<visitor>> visitorMap = myMap.get(time[i]); if (!visitorMap.containsKey(dir[i])) { myList.add(new visitor(time[i], dir[i])); visitorMap.put(dir[i], myList); } else { myList = visitorMap.get(dir[i]); myList.add(new visitor(time[i], dir[i])); visitorMap.put(dir[i], myList); } } }
{ "domain": "codereview.stackexchange", "id": 43647, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, complexity, simulation", "url": null }
java, interview-questions, complexity, simulation for (Entry<Integer, Map<String, List<visitor>>> entry : myMap.entrySet()) { if (entry.getValue().size() > 1) { // now we know multiple people are trying to enter at the same time List<visitor> visitors = entry.getValue().get(lastDir); for (visitor v : visitors) { System.out.println(v.time + " : " + v.dir); } lastDir = lastDir.contentEquals("In") ? "Out" : "In"; visitors = entry.getValue().get(lastDir); for (visitor v : visitors) { System.out.println(v.time + " : " + v.dir); } } else { if (entry.getValue().containsKey("In")) { List<visitor> visitors = entry.getValue().get("In"); for (visitor v : visitors) { System.out.println(v.time + " : " + v.dir); } lastDir = "In"; } else { List<visitor> visitors = entry.getValue().get("Out"); for (visitor v : visitors) { System.out.println(v.time + " : " + v.dir); } lastDir = "Out"; } } entry.setValue(new HashMap<String, List<visitor>>()); } } }
{ "domain": "codereview.stackexchange", "id": 43647, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, complexity, simulation", "url": null }
java, interview-questions, complexity, simulation Answer: I finally came up with an idea that might work. I created a TreeMap<Integer, List<String>>. Here's the output from my last test run. The first group is the TreeMap I created. The second group is a List<Visitor> that I created from the map. I just used the Visitor class toString method to output the List. 1 [Out] 2 [In, Out] 3 [Out] 4 [In] 5 [In] 7 [Out] Visitor [time=1, direction=Out] Visitor [time=2, direction=Out] Visitor [time=2, direction=In] Visitor [time=3, direction=Out] Visitor [time=4, direction=In] Visitor [time=5, direction=In] Visitor [time=7, direction=Out] Here's the code. It took me several hours to come up with this idea. I don't envy anyone trying to come up with this in an interview. Edited to add: I'm not sure what comments the OP is looking for. The createMap method checks to see if a key, value pair exists indirectly. If the value is null, the key, value pair doesn't exist. So I create an ArrayList<String> and add the key, value to the map. If the key, value pair exists, then I add the string to the value List. Since the value is a List, I maintain the order of the input people. The createList method is a little more complicated. I iterate through the map keys, retrieving the List<String> value for each key. If there's only one element in the List (one person), I put them through the door and set the default direction of the door. If there's more than one element in the List<String> value, I iterate through the List twice. Once with the default door direction, and once again with the opposite door direction. Since the List for one time value is likely to be small, the double iteration is pretty short. Worst case, when everyone arrives at the door at the same time, the cost of creating the map, and iterating through the map value is 3n, which is effectively n. import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap;
{ "domain": "codereview.stackexchange", "id": 43647, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, complexity, simulation", "url": null }
java, interview-questions, complexity, simulation public class Doors { public static void main(String[] args) { int[] time = new int[] { 2, 3, 5, 1, 7, 4, 2 }; String direction[] = new String[] { "In", "Out", "In", "Out", "Out", "In", "Out" }; Doors obj = new Doors(); List<Visitor> visitors = obj.findTime(time, direction); for (Visitor visitor : visitors) { System.out.println(visitor); } } public List<Visitor> findTime(int[] time, String[] direction) { Map<Integer, List<String>> map = createMap(time, direction); printMap(map); return createList(map); } private void printMap(Map<Integer, List<String>> map) { Set<Integer> set = map.keySet(); Iterator<Integer> iter = set.iterator(); while (iter.hasNext()) { Integer key = iter.next(); List<String> value = map.get(key); System.out.println(key + " " + value); } System.out.println(); } private Map<Integer, List<String>> createMap( int[] time, String[] direction) { Map<Integer, List<String>> map = new TreeMap<>(); for (int i = 0; i < time.length; i++) { Integer key = time[i]; List<String> value = map.get(key); if (value == null) { value = new ArrayList<>(); } value.add(direction[i]); map.put(key, value); } return map; }
{ "domain": "codereview.stackexchange", "id": 43647, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, complexity, simulation", "url": null }
java, interview-questions, complexity, simulation private List<Visitor> createList( Map<Integer, List<String>> map) { List<Visitor> visitors = new ArrayList<>(); String defaultDirection = "In"; Set<Integer> set = map.keySet(); Iterator<Integer> iter = set.iterator(); while (iter.hasNext()) { Integer key = iter.next(); List<String> value = map.get(key); if (value.size() == 1) { String s = value.get(0); Visitor visitor = new Visitor(key, s); visitors.add(visitor); defaultDirection = s; } else { createVisitors(visitors, defaultDirection, key, value); defaultDirection = changeDefaultDirection( defaultDirection); createVisitors(visitors, defaultDirection, key, value); } } return visitors; } private void createVisitors(List<Visitor> visitors, String defaultDirection, Integer key, List<String> value) { for (int i = 0; i < value.size(); i++) { String s = value.get(i); if (s.equals(defaultDirection)) { Visitor visitor = new Visitor(key, s); visitors.add(visitor); } } } private String changeDefaultDirection( String defaultDirection) { return defaultDirection.equals("In") ? "Out" : "In"; } public class Visitor { private final Integer time; private final String direction; public Visitor(Integer time, String direction) { this.time = time; this.direction = direction; } public int getTime() { return time; } public String getDirection() { return direction; }
{ "domain": "codereview.stackexchange", "id": 43647, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, complexity, simulation", "url": null }
java, interview-questions, complexity, simulation public String getDirection() { return direction; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Visitor [time="); builder.append(time); builder.append(", direction="); builder.append(direction); builder.append("]"); return builder.toString(); } } }
{ "domain": "codereview.stackexchange", "id": 43647, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, complexity, simulation", "url": null }
javascript, datetime, node.js, ecmascript-6, mongodb Title: Find events associated with users on a certain date in MongoDB Question: I have this script which works perfectly but I experienced some delays because of these 2 for loops [i][j]. Is there any way to do the same function but with a better and more effective process like foreach or other? User.find({}).lean(true).exec((err, users) => { let getTEvent = []; //nested loops() //callbacks for (let i =0 ; i < users.length; i++) { if(users[i].events && users[i].events.length) { const dt = datetime.create(); dt.offsetInDays(0); const formatted = dt.format('d/m/Y'); // console.log(formatted) for (let j = 0; j < users[i].events.length; j++) { if(users[i].events[j].eventDate === formatted) { getTEvent.push({events: users[i].events[j]}); } } } } return res.json(getTEvent) }); The main role of this code is: find the data in Mongodb: find all users with or without events loop through data and select events made by any users push the results in an array which is getEventin order to be useful later for the client side Details: The User is the model: const User = require('../models/users.model'); and events is [] array. This is Mongodb structure of that models: Answer: I think the main cause of your delays is not a nested for but rather the fact that you extract all data from your MongoDB collection into memory. What you can do is: calculate formatted date once query just those users that contain given event date instead of populating all users in memory. Here's the guide. This will look roughly like the following: const dt = datetime.create(); dt.offsetInDays(0); const formatted = dt.format('d/m/Y'); User.find({ "events": { eventDate: formatted } }).lean(true).exec((err, users) => { let getTEvent = []; //nested loops() //callbacks
{ "domain": "codereview.stackexchange", "id": 43648, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, datetime, node.js, ecmascript-6, mongodb", "url": null }
javascript, datetime, node.js, ecmascript-6, mongodb for (let i = 0 ; i < users.length; i++) { if(users[i].events && users[i].events.length) { for (let j = 0; j < users[i].events.length; j++) { if(users[i].events[j].eventDate === formatted) { getTEvent.push({events: users[i].events[j]}); } } } } return res.json(getTEvent) });
{ "domain": "codereview.stackexchange", "id": 43648, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, datetime, node.js, ecmascript-6, mongodb", "url": null }
python, beginner, strings Title: Encode text to Baudot (teletype) code
{ "domain": "codereview.stackexchange", "id": 43649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, strings", "url": null }
python, beginner, strings Question: After watching Computerphile videos on WW2 cryptography and radioteletype I decided to code a translator to Baudot code. I wonder if it can be somehow improved? def translate_to_baudot(untranslatedtext): from textwrap import wrap def getdic(): chars=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ ∆-:$3!&#8\'().,9014‽57;2/6"') #‽ is bell and ∆ is new line baud=["11000","10011","01110","10010","10000","10110","01011","00101","01100","11010","11110","01001","00111","00110","00011","01101","11101","01010","10100","00001","11100","01111","11001","10111","10101","10001","00100","01000","11000","10011","01110","10010","10000","10110","01011","00101","01100","11010","11110","01001","00111","00110","00011","01101","11101","01010","10100","00001","11100","01111","11001","10111","10101","10001"] baudic={chars[i]: baud[i] for i in range(len(chars))} return baudic def add_shift(text,charnum): if charnum>0: if text[charnum-1] in'ABCDEFGHIJKLMNOPQRSTUVWXYZ ∆' and text[charnum] not in'ABCDEFGHIJKLMNOPQRSTUVWXYZ': return '11111' elif text[charnum-1] not in'ABCDEFGHIJKLMNOPQRSTUVWXYZ ∆' and text[charnum] in'ABCDEFGHIJKLMNOPQRSTUVWXYZ': return '11011' else: return "" elif charnum==0 and text[0] not in'ABCDEFGHIJKLMNOPQRSTUVWXYZ ': return '11111' else: return "" def bell_check(text): text=text.replace('\a','‽') return text def line_check(text): text=text.replace('\n','∆') return text def strip_non_baud(text): for char in text: if char not in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ-:$3!&#8\'().,9014‽57;2/6" ∆': text=text.replace('char','') return text def text_to_baud(text): baudic=getdic() baudtext='' charnum=0 for char in text: baudtext+=add_shift(text,charnum) baudtext+=baudic[char]
{ "domain": "codereview.stackexchange", "id": 43649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, strings", "url": null }
python, beginner, strings baudtext+=add_shift(text,charnum) baudtext+=baudic[char] charnum+=1 return baudtext text=untranslatedtext text=bell_check(text) text=line_check(text) text=text.upper() text='‽‽‽∆'+strip_non_baud(text)+'∆‽‽‽' print(text) baudtext=text_to_baud(text) baudint=int(baudtext,2) print(baudint) return baudtext if __name__=='__main__': text=input('enter your text here: ') translate_to_baudot('text')
{ "domain": "codereview.stackexchange", "id": 43649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, strings", "url": null }
python, beginner, strings I made this when I just had started coding so it's probably not even close to the best approach. Answer: You need blank lines between your functions for both PEP8 and general sanity. This: chars[i]: baud[i] for i in range(len(chars))
{ "domain": "codereview.stackexchange", "id": 43649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, strings", "url": null }
python, beginner, strings should not use range, and should use a zip instead. However, I am going to suggest that you rework this database so that your alphabets are expressed in binary order, not in alphabetic order. (If you stuck to alphabetic order you'd also want to sort your ordinals, which 3!&#8\'().,9014‽57;2/6 you have not.) If you hold these in binary order, you can simply enumerate() over them to get their code as the index. I don't understand why you use the pseudo-printable substitutes ∆, ‽ for bell and newline. You're going from plaintext to an encoding. If someone wants a bell, they can write alarm \a within the input string; I don't see why bell_check would be useful. Also note that (like Windows, and traditional printers) this encoding relies on CRLF pairs, so you might want to do some translation from single '\n' characters to such pairs. I had a lot of difficulty in reconciling your alphabet data with the alphabets described on Wikipedia. In my example code I have assumed that Wikipedia is right. The Baudot shift is stateful; that is, the terminal is either in letter mode or figure mode for a string of potentially multiple characters. Your add_shift checks both the previous and current character, but this is more complicated than it needs to be: you can just hold a state variable for whether you're in letter or figure mode. Rather than returning a blank string, consider writing an iterator function that either yields or doesn't. Consider an optional feature that throws if there are non-encodable characters in the input. Representing the output as one enormous integer is not useful. If anything, you would want to form a binary-packed bytes object; but I have not shown how to do this. Instead I have demonstrated an easy way to show the binary output with separation spaces. Suggested # Assume US TTY variant of ITA2, LSB on right # https://en.wikipedia.org/wiki/Baudot_code#ITA2 from typing import Iterator
{ "domain": "codereview.stackexchange", "id": 43649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, strings", "url": null }
python, beginner, strings LETTER_SERIES = ( '\0' # null 'E' '\n' # linefeed 'A SIU' '\r' # carriage return 'DRJNFCKTZLWHYPQOBG' '\x0E' # shift-to-figure (shown as "shift-out") 'MXV' '\x0F' # letter page extension (shown as "shift-in") ) FIGURE_SERIES = ( '\0' # null '3' '\n' # linefeed '- ' '\a' # bell (shown as "alarm") '87' '\r' # carriage return '$4' "'" ',!:(5")2#6019?&' '\x0E' # figure page extension (shown as "shift-out") './;' '\x0F' # shift-to-letter (shown as "shift-in") ) def series_to_codes(series: str) -> Iterator[tuple[str, str]]: for i, c in enumerate(series): yield c, f'{i:05b}' LETTER_CODES = dict(series_to_codes(LETTER_SERIES)) FIGURE_CODES = dict(series_to_codes(FIGURE_SERIES)) def text_to_baudot_codes(text: str, strict: bool = False) -> Iterator[str]: i_codeset = 0 codesets = LETTER_CODES, FIGURE_CODES shifts = '\x0E\x0F' for orig in text: if orig in shifts: if strict: raise ValueError() continue orig = orig.upper() current_code = codesets[i_codeset].get(orig) if current_code is not None: yield current_code continue other_code = codesets[1 - i_codeset].get(orig) if other_code is not None: yield codesets[i_codeset][shifts[i_codeset]] yield other_code i_codeset = 1 - i_codeset continue if strict: raise ValueError() def text_to_baudot(text: str, strict: bool = False) -> str: return ' '.join(text_to_baudot_codes(text, strict)) if __name__ == '__main__': text = input('Text: ') print(text_to_baudot(text)) Output Text: t3rd. 10000 11011 00001 11111 01010 01001 11011 11100
{ "domain": "codereview.stackexchange", "id": 43649, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, strings", "url": null }
c++, coordinate-system, linear-algebra Title: Yet another mathematical vector class Question: This is an implementation of a mathematical vector. I am currently working on a linear algebra project and before proceeding further with other classes (matrix, polar_vector etc.) I would like to have some code review if someone's up for that. Currently complex components are supported but not all operations are defined for them (yet), because I need to learn some new stuff before implementing them. But anyway, what I'd like to be reviewed mostly: Design. I'm sure I have a lot to improve from this perspective. Tell me anything! Code review. Probably I could've have written some things better? I'm open to new ideas. Here's the code. #ifndef MATH_VECTOR_MINILIBRARY #define MATH_VECTOR_MINILIBRARY #include <algorithm> #include <cmath> #include <complex> #include <cassert> #include <concepts> #include <initializer_list> #include <iterator> #include <numeric> #include <optional> #include <random> #include <type_traits> #include <utility> // Todo: remove friend functions from vector and move them in namespace Math:: namespace Math { enum class Cos { ALPHA = 0, BETA, THETA }; template<typename T> struct is_complex : std::false_type {}; template<typename T> struct is_complex<std::complex<T>> : std::true_type {}; // only allows arithmetic types (chars excluded) and complex numbers. // const types are unneccessary as they disallow most operations. template<typename T> concept underlying_vector_type = (is_complex<T>::value or std::is_arithmetic_v<T>) and not std::is_same_v<T, char> and not std::is_const_v<T>; template<typename T> concept arithmetic_char_const_excluded = std::is_arithmetic_v<T> and not std::is_same_v<T, char> and not std::is_const_v<T>; #define ASSERT_SIZE_MISMATCH(Size, Size2) assert((Size2 >= Size && "Size mismatch!"));
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra #define ASSERT_SIZE_MISMATCH(Size, Size2) assert((Size2 >= Size && "Size mismatch!")); #define ASSERT_DIV_BYZERO(Value) assert((Value != T{} && "Cannot perform division by zero!")); #define STATICASSERT_COMPLEX_DIFFTYPES(Type1, Type2)\ if constexpr (is_complex<T>::value)\ static_assert(std::same_as<Type1, Type2>);\ /* General vector expressed in cartesian coordinates - accepts the specified type and any size. Not all internal operations are yet defined for complex numbers. For a specialization of this vector representation with polar coordinates, see @... */ template<underlying_vector_type T, std::size_t Size> class vector { private: template<underlying_vector_type T2, std::size_t Size2> friend class vector; T _vector[Size]{}; public: using size_type = std::size_t; using value_type = T; using pointer_type = T*; using reference_type = T&; using const_pointer_type = T* const; /* Constructors: default (1), same value for all elements (2), initialize internal vector through another container (3), initialize internal vector through an multiple values (4), fill the internal vector with random numbers (5), others = defaulted */ constexpr vector() = default; constexpr explicit vector(value_type value) { std::fill(std::begin(_vector), std::end(_vector), value); } template<std::input_iterator InputIter> constexpr vector(InputIter first, InputIter last) { static_assert(std::convertible_to<value_type, typename std::iterator_traits<InputIter>::value_type>, "The type of InputIter must be convertible to the type of Math::Vector"); ASSERT_SIZE_MISMATCH(std::distance(first, last), Size); std::copy(first, last, std::begin(_vector)); }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra std::copy(first, last, std::begin(_vector)); } /* [4] template<typename First, typename... Rest> requires (std::convertible_to<value_type, First> and std::conjunction_v<std::is_convertible<First, Rest>...> and sizeof...(Rest) + 1 <= Size) constexpr explicit vector(const First& first, const Rest... rest) : _vector{first, rest...} {} */ /* Call such as Math::vector<int, 6> vec({3,4,5,2}); This constructor was added instead of constructor [4] to avoid a call such as Math::vector<int, 2> vec(2, 3) to call constructor [4], and instead prefer the constructor initializing the vector through random numbers (by passing std::size_t lower, std::size_t higher). */ template<std::size_t Sz, typename T2> constexpr explicit vector(const T2 (&arr)[Sz]) requires (std::convertible_to<value_type, T2>) : vector(arr, std::make_index_sequence<Sz>{}) {} private: // Perhaps taking const T2(&arr)[Size] would make this slower in case Size is very big and the caller // only passes a small array? Take advantage of that and take a size that represents the actual size of the passed array // instead: needs further checks too see if this improves anything template <typename T2, std::size_t... Index> constexpr explicit vector(const T2(&arr)[sizeof...(Index)], std::index_sequence<Index...>) : _vector{ arr[Index]... } {} public: template<typename T2, std::size_t Size2> constexpr vector(const vector<T2, Size2>& other) requires (Size2 <= Size) { std::copy(std::begin(other._vector), std::end(other._vector), std::begin(_vector)); }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra // Currently useless; keep for future changes of the allowed types. template<typename T2, size_type Size2> constexpr vector(vector<T2, Size2>&& other) /*noexcept (std::is_nothrow_move_constructible_v<T>)*/ requires (Size2 <= Size) { std::move(std::begin(other._vector), std::end(other._vector), std::begin(_vector)); } constexpr explicit vector(size_type lower, size_type higher) { std::mt19937 mt(std::random_device{}()); std::uniform_real_distribution<T> dist(lower, higher); for (size_type i = 0; i < Size; ++i) { _vector[i] = dist(mt); } } // Initialize the complex vector with random initial real and imaginary values constexpr explicit vector(size_type lower, size_type higher) requires (is_complex<T>::value) { std::mt19937 mt(std::random_device{}()); std::uniform_real_distribution<typename T::value_type> dist(lower, higher); for (size_type i = 0; i < Size; ++i) { _vector[i] = { dist(mt), dist(mt) }; } } constexpr vector(const vector& other) = default; constexpr vector(vector&& other) /*noexcept*/ = default; constexpr vector& operator=(vector&& other) /*noexcept*/ = default; constexpr vector& operator=(const vector& other) = default; template<typename Function> constexpr vector apply_foreach(const Function& function) noexcept(noexcept(function)) { for (size_type i{}; i < Size; ++i) { function(_vector[i]); } return *this; } constexpr const T& operator[] (size_type index) const noexcept { return _vector[index]; } constexpr T& operator[] (size_type index) noexcept { return _vector[index]; }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra constexpr T& get_x() const noexcept { return _vector[0]; } constexpr T& get_y() const noexcept requires (Size >= 1) { return _vector[1]; } constexpr T& get_z() const noexcept requires (Size >= 2) { return _vector[2]; } constexpr T& get_w() const noexcept requires (Size >= 3) { return _vector[3]; } // Addition operations template<typename T2> constexpr vector& operator+=(const vector<T2, Size>& rhs) { STATICASSERT_COMPLEX_DIFFTYPES(T, T2); for (size_type i = 0; const auto & element : rhs._vector) { _vector[i++] += element; } return *this; } template<underlying_vector_type T2> constexpr vector& operator+=(T2 val) { std::for_each(std::begin(_vector), std::end(_vector), [val](T& current) { current += val; }); return *this; } template<underlying_vector_type T2> friend constexpr vector operator+(vector lhs, T2 val) { return lhs += val; } template<underlying_vector_type T2> friend constexpr vector operator+(T2 val, vector lhs) { return lhs += val; } template<typename T2> friend constexpr vector operator+(vector lhs, const vector<T2, Size>& rhs) { return lhs += rhs; } public: constexpr vector operator-() requires (not std::is_unsigned<T>::value) { vector temp = *this; for (auto& current : temp) { current = -current; } return temp; } // Substraction operations private: template<typename T2> constexpr vector& substract(const vector<T2, Size>& rhs) { STATICASSERT_COMPLEX_DIFFTYPES(T, T2);
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra for (size_type i = 0; const auto & element : rhs._vector) { _vector[i++] -= element; } return *this; } template<underlying_vector_type T2> constexpr vector& substract(T2 val) { std::for_each(std::begin(_vector), std::end(_vector), [val](auto& current) { current -= val; }); return *this; } public: template<typename T2> constexpr vector& operator-=(const vector<T2, Size>& rhs) { return substract(rhs); } template<typename T2> [[deprecated("substracting vector of type unsigned might cause issues!")]] constexpr vector& operator-=(const vector<T2, Size>& rhs) requires std::is_unsigned<T>::value { return substract(rhs); } template<typename T2> friend constexpr vector operator-(vector lhs, const vector<T2, Size>& rhs) { return lhs -= rhs; } template<underlying_vector_type T2> constexpr vector& operator-=(T2 val) { return substract(val); } template<underlying_vector_type T2> [[deprecated("substracting from an unsigned vector might cause issues!")]] constexpr vector& operator-=(T2 val) requires std::is_unsigned<T>::value{ return substract(val); } template<underlying_vector_type T2> friend constexpr vector operator-(vector lhs, T2 val) { return lhs -= val; } private: template<underlying_vector_type T2> constexpr vector& lambda_multiplicator(T2 lambda) { std::for_each(begin(), end(), [lambda](auto& current) { current *= lambda; }); return *this; }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra return *this; } public: // Multiplication with a Lambda - Scalar multiplication template<underlying_vector_type T2> constexpr vector& operator*=(T2 lambda) { return lambda_multiplicator(lambda); } template<underlying_vector_type T2> [[deprecated("multiplying vector of type unsigned might cause issues!")]] constexpr vector& operator*=(T2 lambda) requires std::is_unsigned<T>::value{ return lambda_multiplicator(lambda); } template<underlying_vector_type T2> friend constexpr vector operator*(vector lhs, T2 lambda) { return lhs *= lambda; } template<underlying_vector_type T2> friend constexpr vector operator*(T2 lambda, vector lhs) { return lhs *= lambda; } // Cross product private: template<typename T2> constexpr vector& cross_product_internal(const vector<T2, Size>& rhs) requires (Size == 3 and std::is_convertible<T2, value_type>::value) { vector temp{ *this }; if constexpr (is_complex<T>::value) { STATICASSERT_COMPLEX_DIFFTYPES(T, T2); // The cross product for complex vectors has the same formulas as a cross product in R3, with the only // difference being that the final step is taking the complex conjugates of the results. _vector[0] = std::conj((temp[1] * rhs[2] - temp[2] * rhs[1])); _vector[1] = std::conj((temp[2] * rhs[0] - temp[0] * rhs[2])); _vector[2] = std::conj((temp[0] * rhs[1] - temp[1] * rhs[0])); return *this; } _vector[0] = temp[1] * rhs[2] - temp[2] * rhs[1]; _vector[1] = temp[2] * rhs[0] - temp[0] * rhs[2]; _vector[2] = temp[0] * rhs[1] - temp[1] * rhs[0]; return *this; }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra public: template<typename T2> constexpr vector& cross_product(const vector<T2, Size>& rhs) { return cross_product_internal(rhs); } template<typename T2> [[deprecated("Multiplication on two vectors of type unsigned might cause issues!")]] constexpr vector& cross_product(const vector<T2, Size>& rhs) requires std::is_unsigned<T>::value { return cross_product_interna(rhs); } // Not in-place template<typename T2> friend constexpr vector cross_product(vector lhs, const vector<T2, Size>& rhs) { return lhs.cross_product_internal(rhs); } // Division with a constant/lambda - for precision and correctness, use multiplication instead template<underlying_vector_type T2> constexpr vector& operator/=(T2 lambda) { ASSERT_DIV_BYZERO(lambda); std::for_each(std::begin(_vector), std::end(_vector), [lambda](auto& current) { current /= lambda; }); return *this; } template<underlying_vector_type T2> friend constexpr vector operator/(vector lhs, T2 lambda) { return lhs /= lambda; } template<underlying_vector_type T2> constexpr vector& operator%=(T2 lambda) requires (std::is_integral_v<T> and std::is_integral_v<T2> and !is_complex<T>) { ASSERT_DIV_BYZERO(lambda); std::for_each(std::begin(_vector), std::end(_vector), [lambda](auto& current) { current %= lambda; }); return *this; } constexpr void reset() noexcept { std::fill(std::begin(_vector), std::end(_vector), T{}); }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra template<underlying_vector_type T1> constexpr auto inner_product(const vector<T1, Size>& other) const { return std::inner_product(std::begin(_vector), std::end(_vector), std::begin(other._vector), T{}); } friend constexpr auto scalar_triple_product(const vector& first, const vector& other2, const vector& other3) requires (Size == 3 and not is_complex<T>::value) { vector temp{ first }; return other3.inner_product(temp.cross_product(other2)); } // Not in place friend constexpr vector vector_triple_product(const vector& first, const vector& other2, const vector& other3) requires (Size == 3 and not is_complex<T>::value) { vector temp{ first }; vector temp3{ other3 }; return temp3.cross_product(temp.cross_product(other2)); } friend constexpr bool are_coplanar(const vector& first, const vector& other2, const vector& other3) requires (Size == 3 and not is_complex<T>::value) { auto result = scalar_triple_product(first, other2, other3); return result >= 0 && result <= 1E-6; } // Calculates projection of other to this, then stores the result in this (inplace) template<typename T2> constexpr vector& vector_projection_from(const vector<T2, Size>& other) { T denominator = inner_product(*this); // a null vector results in a scalar product of 0, thus a denominator of 0 // todo: decide whether this is the appropriate way to proceed, or whether another result can be given (eg. using limits) ASSERT_DIV_BYZERO(denominator); *this *= (inner_product(other) / denominator); return *this; }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra return *this; } // Return direction of a 2D vector. The vector components must be cartesian coordinates. x will return (angle)x, // y returns (angle)y. constexpr double direction_radiants_y() const requires (Size == 2 and not is_complex<T>::value) { return std::atan2(_vector[0], _vector[1]); // (x / y) } constexpr double direction_radiants_x() const requires (Size == 2 and not is_complex<T>::value) { return std::atan2(_vector[1], _vector[0]); // (y / x) } constexpr double direction_degrees_y() const { return direction_radiants_y() * 180.0 / 3.141592653589793238463; } constexpr double direction_degrees_x() const { return direction_radiants_x() * 180.0 / 3.141592653589793238463; } // Direction cosines of 3D vectors. constexpr double direction_cosine(Cos type) const requires (Size == 3 and not is_complex<T>::value) { double denominator = magnitude(); ASSERT_DIV_BYZERO(denominator); return static_cast<double>(_vector[static_cast<int>(type)] / denominator); } constexpr double direction_angle(Cos type) const requires (Size == 2 and not is_complex<T>::value) { return std::acos(direction_cosine(type)); } constexpr vector& normalize() { double denominator = magnitude(); ASSERT_DIV_BYZERO(denominator); *this *= (1 / denominator); return *this; } // Return || magnitude || of this vector constexpr double magnitude() const { double sum = std::accumulate(begin(), end(), T{}, [](auto internal_sum, const auto& element) { return internal_sum + std::pow(element, 2); }); return std::sqrt(sum); }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra return std::sqrt(sum); } // Computes the norm for a complex vector constexpr double magnitude() const requires (is_complex<T>::value) { // The norm of a complex vector has a different definition than that of a vector with R components. double sum = std::accumulate(std::begin(_vector), std::end(_vector), 0, [](auto sum, const auto& element) { return sum + std::pow(std::abs(element.real()), 2) + std::pow(std::abs(element.imag()), 2); }); return std::sqrt(sum); } // Vector Parallelism Condition // 3 dimensions case: checks whether the cross product is near 0 template<typename T2> friend constexpr bool are_parallel(const vector& first, const vector<T2, Size>& other) requires (Size == 3 and not is_complex<T>::value and not is_complex<T2>::value) { vector temp_cross = first; vector temp = temp_cross.cross_product(other); // Two vectors are parallel in 3D only if their cross product result is near zero. return temp[0] >= 0 && temp[0] <= 1E-6 && temp[1] >= 0 && temp[1] <= 1E-6 && temp[2] >= 0 && temp[2] <= 1E-6; } // Other dimensions: scalar product method. Parallelism condition if result's near 0 (approx 1E-6) template<typename T2> friend constexpr bool are_parallel(const vector& first, const vector<T2, Size>& other) requires (not is_complex<T>::value and not is_complex<T2>::value) { auto sum_and_pow = [](auto sum, const auto& element) { return sum + std::pow(element, 2); };
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra T inner_product = first.inner_product(other); double lhs = std::pow(inner_product, 2); double rhs1 = std::accumulate(std::begin(first._vector), std::end(first._vector), 0, sum_and_pow); double rhs2 = std::accumulate(std::begin(other._vector), std::end(other._vector), 0, sum_and_pow); return std::abs(rhs1 * rhs2 - lhs) <= 1E-6; } // Perpendicular conditions template<typename T2> friend constexpr bool are_perpendicular(const vector& first, const vector<T2, Size>& other) requires (not is_complex<T>::value and not is_complex<T2>::value) { auto inner_product = first.inner_product(other); return inner_product >= 0 && inner_product <= 1E-6; } // Angle between two vectors (in radiants) // Todo: Add support for complex vectors template<typename T2> constexpr double angle_between_radiants(const vector<T2, Size>& other) requires (not is_complex<T>::value) { double inner_prod = inner_product(other); double magnitude_mult = magnitude() * other.magnitude(); ASSERT_DIV_BYZERO(magnitude_mult); return std::acos(inner_prod / magnitude_mult); } template<typename T2> constexpr double angle_between_degrees(const vector<T2, Size>& other) { return angle_between_radiants(other) * 180 / 3.141592653589793238463; } constexpr bool is_empty() const { return (Size == 0 || std::all_of(std::begin(_vector), std::end(_vector), [](value_type i) { return i == value_type{}; })); } auto operator<=>(const vector&) const = default; template<typename Stream> constexpr void print(Stream& stream) const { for (auto x : _vector) stream << x << ' '; stream << '\n'; }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra consteval value_type size() const noexcept { return Size; } constexpr auto begin() const noexcept { return std::begin(_vector); } constexpr auto end() const noexcept { return std::end(_vector); } constexpr auto begin() noexcept { return std::begin(_vector); } constexpr auto end() noexcept { return std::end(_vector); } }; // Not in place counterparts template<underlying_vector_type T, std::size_t Size, typename T2> constexpr auto lambda_multiplication(const vector<T, Size>& vec, T2 lambda) { using Type = decltype(std::declval<T>()* std::declval<T2>()); vector<Type, Size> temp(vec); return temp.lambda_multiplicator(lambda); } template<typename T, std::size_t Size> constexpr vector<T, Size> normalize(const vector<T, Size>& other) { vector<T, Size> copy(other); copy.normalize(); return copy; } // Deduction guides // [1] aggregate initialization template<typename T2, std::same_as<T2>...Args> vector(T2, Args...)->vector<T2, sizeof...(Args) + 1>; // [2] complex numbers deduction template <arithmetic_char_const_excluded T, std::size_t N, std::size_t M> vector(T const (&arr)[N][M])->vector<std::complex<T>, N>; } #endif ```
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra } #endif ``` Answer: Consistency You mix and and &&, and not and !. Choose one and stay consistent. Namespace Using a namespace is a good idea to avoid name clashes. That being said, giving the namespace a very common name, such as Math is likely to reintroduce the issue. unsigned integer I spotted some parts in the code where you disable certain functions for unsigned integers or even marked them deprecated. Considering that unsigned integers, i.e. natural numbers, do not form a vector space in the first place, I'd rather prohibit the entire class from being constructed with them. preprocessor macros I would define the macros outside the namespace, because they are not affected by it either way Naming conventions Typically, class names are written with a capital letter class Vector Unnecessary restriction enum class Cos { ALPHA = 0, BETA, THETA }; and constexpr double direction_cosine(Cos type) const requires (Size == 3 and not is_complex<T>::value) { double denominator = magnitude(); ASSERT_DIV_BYZERO(denominator); return static_cast<double>(_vector[static_cast<int>(type)] / denominator); } I'd consider naming the enum values X_AXIS, Y_AXIS and Z_AXIS, because you're somewhat mixing conventions here. But then again, this can be generalized to n-dimensions and you do not need an enum nor the three dimensional restriction. Mix of C with C++ T _vector[Size]{}; is a C-style array. In C++ this should be std::array<T, Size> _vector; you need to #include <array> for it. You made a good habit of using stl algorithms, so you can just swap the declarations and your code still compiles. Constants template<typename T2> constexpr double angle_between_degrees(const vector<T2, Size>& other) { return angle_between_radiants(other) * 180 / 3.141592653589793238463; }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra Why do you not use M_PI which is defined in <cmath> that you even include? Also, while the constant is very well known, it should really be a constant. You can define it as a static member variable conversion_rad2deg. stream operator I'm not sure if it makes sense to use a template here: template<typename Stream> constexpr void print(Stream& stream) const { for (auto x : _vector) stream << x << ' '; stream << '\n'; } Also your version does not return the stream, so I can not chain it, as is usually possible. Instead I'd write: constexpr std::ostream& print(std::ostream& stream) const { for (auto const& x : _vector) stream << x << ' '; stream << '\n'; return stream; } std::accumulate You should check the performance on this one. Before C++20 it copied by value and didn't move. So it could be quite slow for bigger vectors. For smaller vectors it should be fine. Dangerous Bug template<typename T2> friend constexpr bool are_perpendicular(const vector& first, const vector<T2, Size>& other) requires (not is_complex<T>::value and not is_complex<T2>::value) { auto inner_product = first.inner_product(other); return inner_product >= 0 && inner_product <= 1E-6; }
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
c++, coordinate-system, linear-algebra This introduces a potentially dangerous bug. Comparing floating point numbers is hard. But hardcoding the 1E-6 is a very bad solution. Furthermore, the inner product can be negative. So you should at least check std::abs. The easiest fix would be to allow an epsilon parameter, that you compare against. This code appears in several other places so you should really consider making it a function, i.e. is_near_zero(double d) or is_approximately_equal(double x, double y). Problems You mentioned that not everything is yet defined. For example, I can not add a vector of complex numbers to a vector of doubles. Comments Overall this looks well done and a lot of good paradigms were followed. I wouldn't create a polar_vector class though. Simply supply a constructor that takes r, theta and phi. Once you implemented the Matrix class, you can also consider making the vector class a special case, i.e. template<typename T, std::size_t n> using Row_Vector = Matrix<T, 1, n>.
{ "domain": "codereview.stackexchange", "id": 43650, "lm_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++, coordinate-system, linear-algebra", "url": null }
javascript Title: JavaScript handler to seek to one of several locations Question: How would I simplify the following function to reduce repetitive code? I would like to define "arg" as an array since that is the only changing aspect of each case. function jumpMovement(iMovement) { switch (iMovement) { case 0: document.getElementById('opus-08a').contentWindow.postMessage('{"method": "seekSeconds", "arg":"0.0"}', 'https://musescore.com'); break; case 1: document.getElementById('opus-08a').contentWindow.postMessage('{"method": "seekSeconds", "arg":"99.45"}', 'https://musescore.com'); break; case 2: document.getElementById('opus-08a').contentWindow.postMessage('{"method": "seekSeconds", "arg":"201.45"}', 'https://musescore.com'); break; case 3: document.getElementById('opus-08a').contentWindow.postMessage('{"method": "seekSeconds", "arg":"319.49"}', 'https://musescore.com'); break; default: document.getElementById('opus-08a').contentWindow.postMessage('{"method": "seekSeconds", "arg":"0.0"}', 'https://musescore.com'); } } Sample of use in html: <button onclick="jumpFigure(0)">0</button> &nbsp; <button onclick="jumpFigure(1)">1</button> &nbsp; <button onclick="jumpFigure(2)">2</button> &nbsp; etc... Answer: You can completely remove the switch (assuming that iMovement can be used as an index). If iMovement is going to have a much wider spread of values, then you can use a switch and just set arg accordingly, then make the DOM call at the end. function jumpMovement(iMovement) { const args = [ 0.0, 99.45, 201.45, 319.49 ] const arg = args[iMovement] ?? 0.0 document.getElementById('opus-08a').contentWindow.postMessage(`{"method": "seekSeconds", "arg":"${arg.toFixed(2)}"}`, 'https://musescore.com'); }
{ "domain": "codereview.stackexchange", "id": 43651, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript", "url": null }
bash Title: Single instance of mpv while maintaining the coordinates of the previous window Question: The code I am using is: #!/bin/bash pid=$(pidof "mpv") if [[ "$pid" ]]; then wmctrl -x -R gl.mpv echo "{ \"command\": [\"loadfile\", \"$1\", \"append\"] }" | socat - "/tmp/mpv-socket" echo playlist-next | socat - "/tmp/mpv-socket" else mpv --input-ipc-server=/tmp/mpv-socket --player-operation-mode=pseudo-gui "$1" fi It makes sure that there is only one instance of mpv. It also make sure that the new instance is open in the previous window's position. It also has memory. I mean, it adds to the playlist then play it. So, I can go to the previous video. Please note that socat must be installed in the machine. How can I make this code better? Answer: Make the important elements easy to see In the posted code I mean the script parameter $1. Currently it appears in the middle of the code in two places. Until I take a closer look, I don't even know the script takes a parameter. I suggest to store the script parameters early in the script in a variable. And make sure the variable has a descriptive name, it's crucial to help readers understand the meaning and purpose. In this example it seems the parameter is a path to a file, so I suggest to do this near the top of the script: path=$1 gl.mpv might be a good candidate too, to give a descriptive name near the top of the script. Validate parameters In both branches of the if-statement, the parameter is used. Therefore it seems it's a required parameter for the script to work well. Here's one way to validate this and exit when the parameter is missing: if [[ $# != 1 ]]; then echo >&2 "Missing parameter: path-to-file" echo >&2 "usage: $0 path-to-file" exit 1 fi And if the parameter must be a path to a file, it probably makes sense to also verify that: if ! [[ -f $1 ]]; then echo >&2 "Not a file: $1" exit 1 fi
{ "domain": "codereview.stackexchange", "id": 43652, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
bash Let Bash raise errors on suspicious operations I start all my Bash scripts with this, to mitigate the impact of certain mistakes: set -euo pipefail This does a bunch of helpful things: -e makes the script abort on the first failing command, which can help in many ways avoid disasters by failing fast highlight that something unexpected happened make the failure easy to see, at the end of the script output encourages implementing solid error handling -u makes it an error when referencing an undefined variable; together with -e, this again can help avoid disasters -o pipefail makes the exit code of a pipeline success only when all commands exit with success (you can read more about it in man bash, search for "pipefail") Don't repeat yourself socat - "/tmp/mpv-socket" appears twice in the script. You can avoid duplicated logic using a function: socat_to_mpv() { socat - "/tmp/mpv-socket" } And then use ... | socat_to_mpv in the pipelines. Improve readability using single quotes This expression is a bit hard to read because of all the escaping of embedded double-quotes: echo "{ \"command\": [\"loadfile\", \"$1\", \"append\"] }" In situations like this you could use single quotes instead, but carefully: echo '{ "command": ["loadfile", "'"$1"'", "append"] }' Notice what's happening around the $1 there. The basic pattern here is this: echo '...'"$1"'...' That is, when you want to embed a variable in a single-quoted string, "interrupt" the single-quoted string with a ', double-quote the variable as recommended for safety, and then start again the single-quoted string for the remaining part. Indent the body of if-else statements In the posted code the if-branch is not indented, which makes it a bit harder to read. That is, instead of this: if [[ "$pid" ]]; then ... else ... fi Better to write like this: if [[ "$pid" ]]; then ... else ... fi
{ "domain": "codereview.stackexchange", "id": 43652, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash", "url": null }
c++, algorithm Title: Maximum number of words found in sentences Question: You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence. Example Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] Output: 6 Explanation: The first sentence has 5 words, second sentence has 4 words, third sentence has 6 words, so the maximum number of words is 6. My program: int mostWordsFound(vector<string>& sentences) { int n = sentences.size(); int max = 0; for (int i = 0; i < n; i++) { int counter = 0; for (int j = 0; j < sentences[i].size(); j++) { if (sentences[i][j] == ' ') counter++; } if (max < counter) max = counter; } return max + 1; } My program's output is correct, but the time complexity is O(n^2), are there any other ways to improve this program? Thanks. Answer: Time Complexity First of all, your time complexity is not O(n^2). You only have one loop going from 0 to n and then loop over each character. So your time complexity rather looks like O(n*k). I don't think it can be any faster, since you need to check every string and every character. Using namespace std I think it's really terrible that leetcode does this by default. Read this link on why it's considered bad practice. ref vs const ref You're taking the array as a ref, but not as a const ref. Since you're not altering it in any way, you should take it as a const ref. .size() does not return an int int n = sentences.size(); the return type of std::vector::size() is std::size_t. Converting it to an int might narrow it (for long vectors) and the size can never be negative anyway. Use range-based for loops You do not even need to store the size, just use range based for loops: #include <string> #include <vector> int mostWordsFound(std::vector<std::string> const& sentences) { int max = 0;
{ "domain": "codereview.stackexchange", "id": 43653, "lm_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++, algorithm", "url": null }
c++, algorithm int mostWordsFound(std::vector<std::string> const& sentences) { int max = 0; for( auto const& sentence : sentences ){ int counter{0}; for( auto const& character : sentence ){ if( character == ' '){ counter++; } } max = counter > max? counter : max; } return max+1; } A Bug? You are assuming that the input somehow makes sense. But consider the following code: int main(){ std::cout << mostWordsFound({"Hello World!", "Hello World\n"}) << "\n"; } This will output 5, because of all the consecutive whitespaces. A way to improve this program would be to check, if the previous character was a whitespace also, and then not count the current whitespace. Also, trailing or leading whitespaces will give a wrong result (or imagine a string of only spaces!).
{ "domain": "codereview.stackexchange", "id": 43653, "lm_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++, algorithm", "url": null }
python, csv, xml Title: Translate SOAP response into a CSV using Python Question: I have this XML from a SOAP call: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header/> <soapenv:Body> <SessionID xmlns="http://www.gggg.com/oog">5555555</SessionID> <QueryResult xmlns="http://www.gggg.com/oog/Query" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Code>testsk</Code> <Records> <Record> <dim_id>1</dim_id> <resource_full_name>Administrator, Sir</resource_full_name> <resource_first_name>Sir</resource_first_name> <resource_last_name>Administrator</resource_last_name> <resource_email>username@mailserver.com</resource_email> <resource_user_name>admin</resource_user_name> </Record> <Record> <dim_id>2</dim_id> <resource_full_name>scheduler, scheduler</resource_full_name> <resource_first_name>scheduler</resource_first_name> <resource_last_name>scheduler</resource_last_name> <resource_email>username@mailserver.com</resource_email> <resource_user_name>scheduler</resource_user_name> </Record> My goal: To parse each Record's sub-elements <dim_id> ... <resource_user_name> and save each record as a row in a CSV. My Code: dim_id_list = [] full_name_list = [] first_name_list = [] last_name_list = [] resource_email_list = [] resource_user_name_list = [] root = et.parse('xml_stuff.xml').getroot() for dim_id in root.iter('{http://www.gggg.com/oog/Query}dim_id'): dim_id_list.append(dim_id.text) for resource_full_name in root.iter('{http://www.gggg.com/oog/Query}resource_full_name'): full_name_list.append(resource_full_name.text) for resource_first_name in root.iter('{http://www.gggg.com/oog/Query}resource_first_name'): first_name_list.append(resource_first_name.text)
{ "domain": "codereview.stackexchange", "id": 43654, "lm_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, csv, xml", "url": null }
python, csv, xml for resource_last_name in root.iter('{http://www.gggg.com/oog/Query}resource_last_name'): last_name_list.append(resource_last_name.text) for resource_email in root.iter('{http://www.gggg.com/oog/Query}resource_email'): resource_email_list.append(resource_email.text) for resource_user_name in root.iter('{http://www.gggg.com/oog/Query}resource_user_name'): resource_user_name_list.append(resource_user_name.text) rows = zip(dim_id_list, full_name_list, first_name_list, last_name_list, resource_email_list, resource_user_name_list) with open('test.csv', "w", encoding='utf16', newline='') as f: writer = csv.writer(f) for row in rows: writer.writerow(row) Is there a better way to loop through the Records? This code is terribly verbose. I tried this: for record in root.findall('.//{http://www.gggg.com/oog/Query}Record'): dim_id = record.find('dim_id').text # Extract each attribute, save to list. etc. But I am getting attribute errors trying to access each record's text property. Answer: It makes little sense to slice the data into "vertical" lists, then transpose them back into rows using zip(). Not only is it cumbersome to do it that way, it's also fragile. If, for example, one records is missing its resource_email child element, then all subsequent rows will be off! You can use writer.writerows(rows) instead of the for row in rows: writer.write(row) loop. Furthermore, you can pass a generator expression so that the CSV writer extracts records on the fly as needed. It's customary to import xml.etree.ElementTree as ET rather than as et. Suggested solution import csv from xml.etree import ElementTree as ET fieldnames = [ 'dim_id', 'resource_full_name', 'resource_first_name', 'resource_last_name', 'resource_email', 'resource_user_name', ] ns = {'': 'http://www.gggg.com/oog/Query'}
{ "domain": "codereview.stackexchange", "id": 43654, "lm_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, csv, xml", "url": null }
python, csv, xml xml_records = ET.parse('xml_stuff.xml').find('.//Records', ns) with open('test2.csv', 'w', encoding='utf16', newline='') as f: csv.DictWriter(f, fieldnames).writerows( { prop.tag.split('}', 1)[1]: prop.text for prop in xr } for xr in xml_records ) If you are certain that each <Record> always has its child elements in the right order, you can simplify it further by not explicitly stating the element/field names: import csv from xml.etree import ElementTree as ET ns = { '': 'http://www.gggg.com/oog/Query', 'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', } records = ET.parse('xml_stuff.xml').find('soapenv:Body/QueryResult/Records', ns) with open('test2.csv', 'w', encoding='utf16', newline='') as f: csv.writer(f).writerows( [prop.text for prop in r] for r in records )
{ "domain": "codereview.stackexchange", "id": 43654, "lm_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, csv, xml", "url": null }
javascript, jquery, validation Title: validating form before uploading files Question: This function below return true/false. How I could possibly improve the code quality? function uploadcontrolhasError() { if (dialogisVisible === true) { let uploadcontrol = $("#upImport").data("kendoUpload"), files = uploadcontrol.getFiles(); console.log(files); let FileLink = $("#txtFileLink").val(); if (files.length === 0 || FileLink.length != 0) { let dialogcontrol = $('#Dialog').data("kendoDialog"); dialogcontrol.open(); return true; } else { processuploadControl(); return false; } } else { processuploadControl(); return false } } function processuploadControl() { let uploadcontrol = $("#upImport").data("kendoUpload"), files = uploadcontrol.getFiles(); if (files.length != 0) { var counter = 0; $('.k-file-success[data-fileManagerIds]').each(function (kfile) { let filemanagerid = this.dataset.filemanagerids; let hdfilemanagerid = $('<input>').attr({ type: 'hidden', name: 'fileManagerIds[' + counter + ']', id: 'fileManagerIds', value: filemanagerid }); $("#permissionsRequestForm").append(hdfilemanagerid); counter++; }); } } function processsubmitForm() { dialogisVisible = false; var dialog = $("#Dialog").data("kendoDialog"); dialog.close(); $("#permissionsRequestForm").submit(); } function closeDialog() { dialogisVisible = false; var dialog = $("#Dialog").data("kendoDialog"); dialog.close(); } function materialsconfirmhasError() { let materialsconfirm = $('input[name="ckmaterialsconfirm"]:checked').length > 0; let uploadcontrol = $("#upImport").data("kendoUpload"), files = uploadcontrol.getFiles();
{ "domain": "codereview.stackexchange", "id": 43655, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, validation", "url": null }
javascript, jquery, validation let FileLink = $("#txtFileLink").val(); console.log(FileLink); if (files.length != 0 || FileLink.length != 0) { if (materialsconfirm == false) { $("#lblConfirmError").show(); return true } else { $("#lblConfirmError").hide(); return false } } return false } function uploadcontrolsizehasError() { var hasError = false; $('.k-file-name-invalid').each(function (kfile) { console.log('uploadcontrolsizehasError'); $("#lblFileSizeError").show(); hasError = true; }); return hasError; } Answer: You asked: How I could possibly improve the code quality? first things: use camelCase for function names (or else kabob_case) to separate words for readability. It is also recommended by numerous style guides (e.g. google JS, airBnB, etc.) to use camelCase for variable names. use const for any variable that doesn't need to be re-assigned - e.g. FileLink, dialogcontrol. This helps avoid accidental re-assignment and other bugs. If you determine that you need to re-assign a variable then switch it to let. when calling the jQuery .each() method utilize the first argument (currently named kfile but could be changed to index, counter, etc.) instead of manually creating and incrementing a separate variable counter. just as materialsconfirm is assigned in materialsconfirmhasError() based on the length of a jQuery collection, hasError in uploadcontrolsizehasError() could be assigned in a similar fashion instead of calling the .each() method to loop over each element, which calls the show() method on a single element The first three lines of processsubmitForm() appear to be identical to the three lines of closeDialog() so instead of duplicating those three lines processsubmitForm() could simply call closeDialog(). in JavaScript many values are considered false-y - e.g. 0 so conditions like (files.length != 0) can be simplified to (!files.length)
{ "domain": "codereview.stackexchange", "id": 43655, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, validation", "url": null }
javascript, jquery, validation Simplifying logic Looking at uploadcontrolhasError it appears that there are two else blocks which both contain a call to processuploadControl() and return false. The first else could be eliminated if the else keywords were removed: function uploadcontrolhasError() { if (dialogisVisible === true) { let uploadcontrol = $("#upImport").data("kendoUpload"), files = uploadcontrol.getFiles(); console.log(files); let FileLink = $("#txtFileLink").val(); if (files.length === 0 || FileLink.length != 0) { let dialogcontrol = $('#Dialog').data("kendoDialog"); dialogcontrol.open(); return true; } } processuploadControl(); return false } Global variables I happened to notice that in the original version of the post there was concern about global variable dialogisVisible. Yes it is wise to avoid using globals though for a small site it isn't the end of the world. There are alternatives - e.g. using the revealing module pattern calling a function to check the status of whether the dialog is visible encapsulating the variable as a property of an object (potentially with the es6 class syntax - possibly with private class fields)
{ "domain": "codereview.stackexchange", "id": 43655, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, jquery, validation", "url": null }
rust Title: App for grabbing data from some APIs (electricity usage & solar panel production) & putting them into a DB Question: I made an app for my internal use that collects some metrics & puts them into a DB. I'd be happy if someone could comment on my code, commenting, design choices and so. I hope I did enough commenting, aside from the code quality - the app run pretty well! I apologize for only including the initial commit - it's a small app, my other apps, which are unfortunately private, have their commits (I hope) separated better. Thank you nice people of Code Review! main.rs (Initial impression!) #[tokio::main] async fn main() -> Result<()> { dotenv::dotenv()?; let solax = SolaxApi::init(&env::var("TOKEN_ID").unwrap(), &env::var("SITE_ID").unwrap()); let power = solax.get_inverter_power().await?; let mut db = Db::init(&env::var("MYSQL_DB_URL").unwrap())?; db.write_inverter_power(&power)?; let wa = WattAnalyticsApi::init( &env::var("WA_USERNAME").unwrap(), &env::var("WA_PASSWORD").unwrap() ).await?; let data = wa .get_power_meter_data( &env::var("METER_ID").unwrap(), 1, 1, Local::now(), Local::now().checked_add_signed(Duration::milliseconds(10000)).unwrap() // smaller from-to differences give off just an empty array ) .await? .power_data; db.write_home_power_usage(data.first().unwrap())?; Ok(()) } The GitHub repository Answer: Your solution looks good! Here are my suggestions for improving the structure to make it a bit easier to maintain and extend: As far as I can tell dotenv is not actively maintained so it might be better to switch to its fork dotenvy
{ "domain": "codereview.stackexchange", "id": 43656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust Do not call Local::now() twice as time will pass between the two calls and your range will be inconsistent or even incorrect if the second call is delayed too much. let from = Local::now(); let to = from.checked_add_signed(Duration::milliseconds(10000))?; Extract the names of the environmental variables and magic numbers into consts so that they are easier to find and update when needed. const TOKEN_ID: &str = "TOKEN_ID"; const SITE_ID: &str = "SITE_ID"; const WA_USERNAME: &str = "WA_USERNAME"; const WA_PASSWORD: &str = "WA_PASSWORD"; const MYSQL_DB_URL: &str = "MYSQL_DB_URL"; const METER_ID: &str = "METER_ID"; const DELAY: i64 = 10_000; Separate the creation and initialization of objects from their usage to increase readability. struct PowerApp { solax_api: SolaxApi, watt_api: WattAnalyticsApi, db: Db, } impl PowerApp { pub async fn new( solax_token_id: String, solax_site_id: String, watt_api_username: String, watt_api_password: String, db_url: String, ) -> Result<Self> { let solax_api = SolaxApi::init(&solax_token_id, &solax_site_id); let watt_api = WattAnalyticsApi::init(&watt_api_username, &watt_api_password).await?; let db = Db::init(&db_url)?; Ok(Self { solax_api, watt_api, db, }) } pub async fn execute(&mut self, meter_id: u32, depth: u32, num_of_readings: u32) -> Result<()> { let power = self.solax_api.get_inverter_power().await?; self.db.write_inverter_power(power)?; let from = Local::now(); let to = from.checked_add_signed(Duration::milliseconds(DELAY))?; let data = self .watt_api .get_power_meter_data( meter_id, depth, num_of_readings, from, to, ) .await?.power_data; self.db.write_home_power_usage(data.first()?) } }
{ "domain": "codereview.stackexchange", "id": 43656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust self.db.write_home_power_usage(data.first()?) } } User builder pattern to create the PowerApp. This gives you the flexibility to use different methods for initializing the PowerApp, for example with command line arguments, while still defaulting to reading them from environmental variables if nothing else is provided. struct PowerAppBuilder { solax_token_id: Option<String>, solax_site_id: Option<String>, watt_api_username: Option<String>, watt_api_password: Option<String>, db_url: Option<String>, } impl PowerAppBuilder { pub fn new() -> Self { Self { solax_token_id: None, solax_site_id: None, watt_api_username: None, watt_api_password: None, db_url: None, } } pub fn solax_token_id(&mut self, solax_token_id: String) { self.solax_token_id = Some(solax_token_id) } pub fn solax_site_id(&mut self, solax_site_id: String) { self.solax_site_id = Some(solax_site_id) } pub fn watt_api_username(&mut self, watt_api_username: String) { self.watt_api_username = Some(watt_api_username) } pub fn watt_api_password(&mut self, watt_api_password: String) { self.watt_api_password = Some(watt_api_password) } pub fn db_url(&mut self, db_url: String) { self.db_url = Some(db_url) } pub async fn build(self) -> Result<PowerApp> { PowerApp::new( self.solax_token_id.unwrap_or(env::var(TOKEN_ID)?), self.solax_site_id.unwrap_or(env::var(SITE_ID)?), self.watt_api_username.unwrap_or(env::var(WA_USERNAME)?), self.watt_api_password.unwrap_or(env::var(WA_PASSWORD)?), self.db_url.unwrap_or(env::var(MYSQL_DB_URL)?), ) .await } }
{ "domain": "codereview.stackexchange", "id": 43656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust Final Code: const TOKEN_ID: &str = "TOKEN_ID"; const SITE_ID: &str = "SITE_ID"; const WA_USERNAME: &str = "WA_USERNAME"; const WA_PASSWORD: &str = "WA_PASSWORD"; const MYSQL_DB_URL: &str = "MYSQL_DB_URL"; const METER_ID: &str = "METER_ID"; const DELAY: i64 = 10_000; struct PowerAppBuilder { solax_token_id: Option<String>, solax_site_id: Option<String>, watt_api_username: Option<String>, watt_api_password: Option<String>, db_url: Option<String>, } impl PowerAppBuilder { pub fn new() -> Self { Self { solax_token_id: None, solax_site_id: None, watt_api_username: None, watt_api_password: None, db_url: None, } } pub fn solax_token_id(&mut self, solax_token_id: String) { self.solax_token_id = Some(solax_token_id) } pub fn solax_site_id(&mut self, solax_site_id: String) { self.solax_site_id = Some(solax_site_id) } pub fn watt_api_username(&mut self, watt_api_username: String) { self.watt_api_username = Some(watt_api_username) } pub fn watt_api_password(&mut self, watt_api_password: String) { self.watt_api_password = Some(watt_api_password) } pub fn db_url(&mut self, db_url: String) { self.db_url = Some(db_url) } pub async fn build(self) -> Result<PowerApp> { PowerApp::new( self.solax_token_id.unwrap_or(env::var(TOKEN_ID)?), self.solax_site_id.unwrap_or(env::var(SITE_ID)?), self.watt_api_username.unwrap_or(env::var(WA_USERNAME)?), self.watt_api_password.unwrap_or(env::var(WA_PASSWORD)?), self.db_url.unwrap_or(env::var(MYSQL_DB_URL)?), ) .await } } struct PowerApp { solax_api: SolaxApi, watt_api: WattAnalyticsApi, db: Db, }
{ "domain": "codereview.stackexchange", "id": 43656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust struct PowerApp { solax_api: SolaxApi, watt_api: WattAnalyticsApi, db: Db, } impl PowerApp { pub async fn new( solax_token_id: String, solax_site_id: String, watt_api_username: String, watt_api_password: String, db_url: String, ) -> Result<Self> { let solax_api = SolaxApi::init(&solax_token_id, &solax_site_id); let watt_api = WattAnalyticsApi::init(&watt_api_username, &watt_api_password).await?; let db = Db::init(&db_url)?; Ok(Self { solax_api, watt_api, db, }) } pub async fn execute(&mut self, meter_id: u32, depth: u32, num_of_readings: u32) -> Result<()> { let power = self.solax_api.get_inverter_power().await?; self.db.write_inverter_power(power)?; let from = Local::now(); let to = from.checked_add_signed(Duration::milliseconds(DELAY)).some; let data = self .watt_api .get_power_meter_data( meter_id, depth, num_of_readings, from, to, ) .await?.power_data; self.db.write_home_power_usage(data.first().unwrap()) } } #[tokio::main] async fn main() -> Result<()> { dotenvy::dotenv()?; let mut app = PowerAppBuilder::new().build().await?; app.execute(env::var(METER_ID)?).await }
{ "domain": "codereview.stackexchange", "id": 43656, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
c, socket, library, client Title: Send and receive functions for telnet client Question: I am using libtelnet to design a telnet client by sending text commands to a telnet server and receiving text responses. I am utilizing telnet-client.c. For simplicity, I made send and receive functions. The complete code is shown below: #include <arpa/inet.h> #include <ctype.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <poll.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <termios.h> #include <unistd.h> #ifdef HAVE_ZLIB #include "zlib.h" #endif #include "libtelnet.h" #define BUFFER_SIZE 512 static telnet_t *telnet; static const telnet_telopt_t telopts[] = { {TELNET_TELOPT_ECHO, TELNET_WONT, TELNET_DO}, {TELNET_TELOPT_TTYPE, TELNET_WILL, TELNET_DONT}, {TELNET_TELOPT_COMPRESS2, TELNET_WONT, TELNET_DO}, {TELNET_TELOPT_MSSP, TELNET_WONT, TELNET_DO}, {-1, 0, 0}}; static void _input(const char *buffer, int size) { /* printing here only for debugging */ char msg[size + 1]; strncpy(msg, buffer, size); msg[size] = '\0'; printf("request: [%s]", msg); static char crlf[] = {'\r', '\n'}; int i; for (i = 0; i != size; ++i) { if (buffer[i] == '\r' || buffer[i] == '\n') { telnet_send(telnet, crlf, 2); } else { telnet_send(telnet, buffer + i, 1); } } fflush(stdout); } static void _send(int sock, const char *buffer, size_t size) { int rv; /* send data */ while (size > 0) { if ((rv = send(sock, buffer, size, 0)) == -1) { fprintf(stderr, "send() failed: %s\n", strerror(errno)); exit(1); } else if (rv == 0) { fprintf(stderr, "send() unexpectedly returned 0\n"); exit(1); } /* update pointer and size to see if we've got more to send */ buffer += rv; size -= rv; } }
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c, socket, library, client static void _event_handler(telnet_t *telnet, telnet_event_t *ev, void *user_data) { (void)telnet; int sock = *(int *)user_data; char msg[ev->data.size + 1]; switch (ev->type) { /* data received */ case TELNET_EV_DATA: strncpy(msg, ev->data.buffer, ev->data.size); msg[ev->data.size] = '\0'; /* printing here only for debugging */ printf("response: [%s]", msg); break; /* data must be sent */ case TELNET_EV_SEND: _send(sock, ev->data.buffer, ev->data.size); break; default: /* ignore */ break; } } static void try_send(int sock, const char *cmd, size_t cmdlen) { fd_set writefd; // timeout 1 second struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; // clear the set ahead of time FD_ZERO(&writefd); // add our descriptors to the set FD_SET(sock, &writefd); int rv = select(sock + 1, NULL, &writefd, NULL, &tv); if (rv == -1) { perror("select"); // error occurred in select() } else if (rv == 0) { printf("timeout occurred!\n"); } else { /* send the request */ if (FD_ISSET(sock, &writefd)) { _input(cmd, cmdlen); } } } static void try_recv(int sock, char *buffer) { fd_set readfd; struct timeval tv; tv.tv_sec = 1; tv.tv_usec = 0; FD_ZERO(&readfd); FD_SET(sock, &readfd); int rv = select(sock + 1, &readfd, NULL, NULL, &tv); if (rv == -1) { perror("select"); // error occurred in select() } else if (rv == 0) { printf("timeout occurred!\n"); } else { int rv; /* receive the response */ if (FD_ISSET(sock, &readfd)) { if ((rv = recv(sock, buffer, BUFFER_SIZE, 0)) > 0) { telnet_recv(telnet, buffer, rv); } else if (rv == 0) { printf("connection has been closed.\n"); return; } else { fprintf(stderr, "recv() failed: %s\n", strerror(errno)); exit(1); } } } }
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c, socket, library, client int main() { char buffer[BUFFER_SIZE]; int rv; int sock; struct sockaddr_in addr; struct addrinfo *ai; struct addrinfo hints; const char *servname = "50000"; const char *hostname = "192.168.102.85"; /* look up server host */ memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(hostname, servname, &hints, &ai)) != 0) { fprintf(stderr, "getaddrinfo() failed for %s: %s\n", hostname, gai_strerror(rv)); return 1; } /* create server socket */ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "socket() failed: %s\n", strerror(errno)); return 1; } /* bind server socket */ memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) { fprintf(stderr, "bind() failed: %s\n", strerror(errno)); close(sock); return 1; } /* connect */ if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) { fprintf(stderr, "connect() failed: %s\n", strerror(errno)); close(sock); return 1; } /* free address lookup info */ freeaddrinfo(ai); /* initialize telnet box */ telnet = telnet_init(telopts, _event_handler, 0, &sock); /* our server returns "welcome\r\n" upon a successful connection */ try_recv(sock, buffer); try_recv(sock, buffer); /* the second recv is needed */ /* define our commands and length */ const char *cmd[] = {"INIT\n", "READ PT3\n", "READ PT4\n", "REM PT3\n"}; const int len[] = {5, 9, 9, 8}; int i; i = 0; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); i = 1; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); i = 2; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); i = 3; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); /* clean up */ telnet_free(telnet); close(sock); return 0; }
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c, socket, library, client /* clean up */ telnet_free(telnet); close(sock); return 0; } Run The server returns "welcome\r\n" upon a successful connection. Please see below the complete log displayed on the terminal. ravi@dell:~/telnet$ ./my_client response: [Welcome ]response: [ ]request: [INIT ]response: [OK ]request: [READ PT3 ]response: [OK ]request: [READ PT4 ]response: [OK ]request: [REM PT3 ]response: [OK ]ravi@dell:~/telnet$ Problems I plan to make a wrapper of this code which will later be called from another (main) file. Most of my issues are related to how the response is received. Nevertheless, I feel that the design/code style should be improved. To this end, below are the problems I am facing: The call to receive function (i.e., try_recv(sock, buffer)) is done twice in order to grab the welcome message. However, I expect the receive function to receive all the data in one call. Calling the receive function twice does not look nice to me. Removing the second call or adding an extra receive call makes the program stop working next time. From next time, the program prints "connection has been closed.". In this situation, I have to restart the telnet server forcefully. After every send command, the receive function is called. If I do not call receive function, the program prints "connection has been closed.". In this situation, I have to restart the telnet server forcefully. The receive function prints the response on the terminal. Instead, I would like to return it as a string.
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c, socket, library, client Answer: General Observations The code could be made more maintainable (easier to read, write, and debug) through reduction of redundant code and simplification. There is a possible bug in static void try_recv(int sock, char* buffer), the variable rv is defined twice in 2 separate scopes, it would be better to only declare it once in the function. Maintainability It would be easier to add or delete commands in the cdm array if each command was on a separate line: const char* cmd[] = { "INIT\n", "READ PT3\n", "READ PT4\n", "REM PT3\n" }; DRY Code There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well. It isn't clear why you aren't using a loop of some kind in main() for this code: const char* cmd[] = { "INIT\n", "READ PT3\n", "READ PT4\n", "REM PT3\n" }; const int len[] = { 5, 9, 9, 8 }; int i; i = 0; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); i = 1; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); i = 2; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); i = 3; try_send(sock, cmd[i], len[i]); try_recv(sock, buffer); It also isn't clear why the second array, len exists, since you can simply use the strlen() function to get the information, let the computer do as much work as it can. The above code can be simplified to: const char* cmd[] = { "INIT\n", "READ PT3\n", "READ PT4\n", "REM PT3\n" }; size_t cmd_count = sizeof(cmd) / sizeof(*cmd); int i; for (i = 0; i < cmd_count; i++) { try_send(sock, cmd[i], strlen(cmd[i])); try_recv(sock, buffer); }
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c, socket, library, client } Starting a Function Name with Underscore _ Function names that start with underscore are reserved, it would be much better if the functions _input(), _send() and _event_handler() did not start with underscores even though they are static and therefore not global functions. This stack overflow question also discusses the issue. Use More Descriptive Variable Name The variable names cmd, ai, rv, tv and others could be more descriptive. I understand that addrinfo is already the name of a struct, it would be much better if the header file included a typedef that capitalized the A and I so that you could use addrinfo as a variabble name as well. Default Action in _event_handler() The switch statement in _event_handler() doesn't handle possible errors, it might be better to list each possible case with a common break; statement and let default: handle the case where an unknown type is returned as an error. Return Possible Errors Both the try_send() function and the try_recv() function should return a status on success or failure, the initial code in main() could then loop until try_recv() completed successfully (returned a positive value). Returning Status From main() There are 2 documented system defined macros to return status from main, these are EXIT_SUCCESS and EXIT_FAILURE. These macros are defined in stdlib.h. They are also used in C++ programming. They help provide self documenting code. Complexity 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. There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c, socket, library, client 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. Suggested Additional Function and Modifications to main() static int make_connections() { int rv; int sock; struct sockaddr_in addr; struct addrinfo* ai; struct addrinfo hints; const char* servname = "50000"; const char* hostname = "192.168.102.85"; /* look up server host */ memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(hostname, servname, &hints, &ai)) != 0) { fprintf(stderr, "getaddrinfo() failed for %s: %s\n", hostname, gai_strerror(rv)); return -1; } /* create server socket */ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "socket() failed: %s\n", strerror(errno)); return -1; } /* bind server socket */ memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1) { fprintf(stderr, "bind() failed: %s\n", strerror(errno)); close(sock); return -1; } /* connect */ if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) { fprintf(stderr, "connect() failed: %s\n", strerror(errno)); close(sock); return -1; } /* free address lookup info */ freeaddrinfo(ai); return sock; } int main() { char buffer[BUFFER_SIZE]; int sock = make_connections(); if (sock < 0) { return EXIT_FAILURE; } /* initialize telnet box */ telnet = telnet_init(telopts, _event_handler, 0, &sock); /* our server returns "welcome\r\n" upon a successful connection */ try_recv(sock, buffer); try_recv(sock, buffer); /* the second recv is needed */
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c, socket, library, client /* define our commands and length */ const char* cmd[] = { "INIT\n", "READ PT3\n", "READ PT4\n", "REM PT3\n" }; size_t cmd_count = sizeof(cmd) / sizeof(*cmd); int i; for (i = 0; i < cmd_count; i++) { try_send(sock, cmd[i], strlen(cmd[i])); try_recv(sock, buffer); } /* clean up */ telnet_free(telnet); close(sock); return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 43657, "lm_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, socket, library, client", "url": null }
c++, stack Title: Stack array based implementation in C++ Question: I wrote my implementation to Stack array based. And I need a review for it to improve it and improve my coding skill. I also will but this implementation on my GitHub account. One more thing: I am not sure why my stack works after I clear it. I used free which will free the allocated array from the heap memory and I then pushed to it after clearing it and it still work as the array didn't deallocate after calling the free //====================================================== // Author : Omar_Hafez // Created : 08 July 2022 (Friday) 2:45:23 PM //====================================================== #include <iostream> #include <vector> enum InsertStatus {FailedStackEmpty = -1, FailedStackFull = -2, OK = 0}; template<class T> struct Stack { int top = 0; int MAX_SIZE; T* array; Stack(int MAX_SIZE) { this -> MAX_SIZE = MAX_SIZE; array = (T*) malloc(MAX_SIZE*sizeof(T)); } bool isEmpty() { return top <= 0; } bool isFull() { return top >= MAX_SIZE; } int stackSize() { return top; } InsertStatus push(T const& t) { if(isFull()) return FailedStackFull; array[top++] = t; return OK; } InsertStatus pop() { if(isEmpty()) return FailedStackEmpty; top--; return OK; } void stackTop(T const& t) { t = array[top-1]; } void clearStack() { top = 0; free(array); } void traverseStack(void (*function) (T& t)) { for(int i = 0; i < top; i++) { (*function) (array[i]); } } };
{ "domain": "codereview.stackexchange", "id": 43658, "lm_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++, stack", "url": null }
c++, stack Answer: #include only necessary headers Reduce compilation time. Stack being a template class should be defined in a header file. Thus, irrelevant headers would needlessly get inside translation units along with Stack definition. <iostream> and <vector> are redundant here. #include <cstdlib> is sufficient for std::malloc and std::free. Prefer class over struct for complex data structures struct is useful for aggregate data structures that do not impose constraints on data. Internal data is exposed to users, and values of mutable members may be independently changed in unpredictable ways. Data structures featured with user defined implementation constraints (e.g. invariants) must hide implementation details with private access specifier. Stack is such data structure. Its data members must be accessed only through carefully designed public methods to maintain constraints that should be initially established by class constructors. In general, if a class has a constructor, one should probably use class. class Stack { public: /* user available methods */ private: /* hidden implementation details */ int top = 0; int MAX_SIZE; T* array; }; Use simple and meaningful names Don't repeat yourself. template<typename T> class Stack { public: /*...*/ int size() const { /* ... */ } T& top() { /* ... */ } void clear() { /* ... */ } /*...*/ }; Restrict names visibility Note that InsertStatus is not a scoped enum. Placed in global scope of a header file, it may cause name ambiguity problems. #include "Stack.h" /* enum InsertStatus { ..., OK = 0 } is available */ /* and OK is accessible as is */ static int OK = -1; // error, can't redefine in global scope void foo() { std::string OK{"-1"}; // hides InsertStatus::OK cout << OK; // prints -1 } Use scoped enum enum class InsertStatus { /* ... */ } // separate type
{ "domain": "codereview.stackexchange", "id": 43658, "lm_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++, stack", "url": null }
c++, stack Use scoped enum enum class InsertStatus { /* ... */ } // separate type /* ... */ class Stack { /* ... */ InsertStatus pop() { /* ... */ return InsertStatus::OK; // OK is accessible only when fully qualified } }; or simply put enum in the class scope. /* ... */ class Stack { public: enum InsertStatus { /* ... */ } /* ... */ private: /* ... */ }; /* ... */ Stack<int> st(3); if (st.pop() == Stack::FailedStackEmpty) { /* ... */ } Stack also should be placed in a namespace to avoid possible name clash. Use member initializer lists Use member initializer lists in constructors to avoid redundant in-class member initialization. class Sentence { public: Sentence(const std::string& s) { /* text was default initialized */ text = s; // initial value is discarded } private: std::string text; }; With member initializer list, constructor looks like this. Sentence(const std::string& s) : text{s} // directly initialize text { } Always test malloc return value std::malloc returns null pointer if it fails to acquire a block of memory of required size, e.g. if MAX_SIZE is too big. array = (T*)std::malloc(/* ... */); if (array == nullptr) throw std::bad_alloc("Not enough memory"); Report the problem as soon as possible. Avoid using C-style casts static_cast, dynamic_cast and reinterpret_cast are conspicuous and functionally limited to prevent cast-related undefined behavior. array = static_cast<T *>std::malloc(/* ... */); Establish constraints in constructors Prevent using invalid objects. Here, MAX_SIZE must be positive and array must not be null. Stack(int capacity) : MAX_SIZE{capacity} { assert(MAX_SIZE > 0); /* ... */ assert(array != nullptr); }
{ "domain": "codereview.stackexchange", "id": 43658, "lm_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++, stack", "url": null }
c++, stack If throwing exception is not an option, invalid objects may be flagged accordingly. class Stack { public: Stack(int capacity) : MAX_SIZE{capacity} { /* ... */ isValid = array != nullptr; } /* ... */ bool valid() const { return isValid; } private: bool isValid = false; /* ... */ }; Test your code extensively Code that uses stackTop method fails to compile because stackTop attempts to assign a value to the const variable t. It compiles though if stackTop is not used because compiler instantiates only used template methods. For classes owning resources, define (copy/move) constructors, (copy/move) assignment operators and destructor Otherwise, some of them (maybe all) will be implicitly generated by the compiler and perform trivial behavior. Compiler generated (copy/move) constructors and (copy/move) assignment operators do simple memberwise value copy, and destructor does nothing. Such behavior causes resource (here memory) leaks. Throughout its lifetime, an object should maintain a valid and comprehensible state #include "Stack.h" int main() { Stack<int> st(3); st.clearStack(); // st is invalid because memory was freed st.push(5) // error, undefined behavior return 0; // st is destructed at the end of lifetime }
{ "domain": "codereview.stackexchange", "id": 43658, "lm_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++, stack", "url": null }
java, interview-questions, search, matrix, binary-search Title: Searching in a sorted 2D matrix Question: If I was at an interview, and wrote this code, what would you think? Please be brutal. Time it took to wrote it: 13 minutes Problem: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. For example, Consider the following matrix: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] Given target = 3, return true. public boolean searchMatrix(int[][] matrix, int target) { int lastCol = matrix[0].length-1; int row=0; while(row!=matrix.length && lastCol>=0){ if(matrix[row][lastCol]==target){ return true; } if(matrix[row][lastCol]>target){ lastCol--; if(binarySearch(matrix[row], 0, lastCol, target)!=-1){ return true; } } row++; } return false; } public int binarySearch(int[] arr, int low, int high, int target){ while(low<=high){ int mid = (low + high)/2; if(arr[mid]==target){ return mid; } else if(arr[mid]<target){ low = mid+1; } else if(arr[mid]>target){ high = mid-1; } } return -1; } Space complexity = \$\mathcal{O}(1)\$ Time Complexity = \$\mathcal{O}(\log(n!))\$
{ "domain": "codereview.stackexchange", "id": 43659, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, search, matrix, binary-search", "url": null }
java, interview-questions, search, matrix, binary-search Space complexity = \$\mathcal{O}(1)\$ Time Complexity = \$\mathcal{O}(\log(n!))\$ Answer: Your algorithm is not efficient (that's the brutal part of the answer). Searching in a list of t values is a task that can be accomplished using \$\mathcal{O}(\log(t))\$ comparisons. Here we have \$t=m*n\$ values so it should be accomplished using \$\mathcal{O}(\log(m*n)) = \mathcal{O}(\log(m))+\mathcal{O}(\log(n))\$ comparisons. I suspect your algorithm may execute the while loop about matrix.length times so it is not \$\mathcal{O}(\log(m))\$ (where m is the number of rows). The algorithm could work in the following way: If the searched value is smaller then the first column in the first row, then the searched value is not contained in the matrix. Then do a binary search on the first column of the matrix to find the largest entry smaller or equal to the searched value. If the value found matches, you are done. Otherwise, do a binary search on the row found. If the value found matches the searched value, you are done; otherwise, the searched value is not in the matrix. Another way is to treat the problem like a single dimension sorted array as it is proposed in the comment of @Azar. Even a small piece of code can have a lot of errors so it does make sense to try to use library methods to accomplish this task and not implement the binary search by yourself (but I don't know if this is the intention of the poser of the problem). This blog entry discusses an example of a buggy implementation in Java. It references the following SUN bug report because there was an erroneous implementation of the binary search even in the JDK.
{ "domain": "codereview.stackexchange", "id": 43659, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, interview-questions, search, matrix, binary-search", "url": null }
python, performance, algorithm Title: Looking for a more efficient algorithm for the sum of list of lists Question: I'm working on a fun project where I'm trying to implement Random Forest algorithm in pure Python, i.e. without NumPy. But then I'll still be dealing with arrays all the time and so I'm writing my own Array class to use in place of NumPy's ndarray. Although I'm only focusing on 2d arrays as I don't need n-dimensional stuff for this project. It's all working correctly, although it's not fully covered by tests yet. And for most part I think I have reasonably decent performance, but I'm struggling with methods for addition and multiplication of arrays. In the normal addition or multiplication of arrays in NumPy the result is element-wise addition or multiplication and my solution is O(n * m) which for large arrays will be a problem. Is there a faster algorithm to do this (the __add__ and __mul__ dunders)? Any other things I could improve? from typing import Iterable from pathlib import Path from functools import reduce
{ "domain": "codereview.stackexchange", "id": 43660, "lm_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, algorithm", "url": null }
python, performance, algorithm class Array: def __init__(self, value: Iterable[Iterable[int | float]]) -> None: self.value = value @property def value(self): return self.__value @value.setter def value(self, val: Iterable[Iterable[int | float]]): if not isinstance(val, Iterable): raise ValueError('The array must be an Iterable.') if not all(isinstance(a, Iterable) for a in val): raise ValueError("All elements of array must be Iterables. " "If creating a flat array, all elements must be length 1 iterables.") if not reduce(lambda x, y: len(x)==len(y), val): raise ValueError("Can not create array from a ragged sequence. " "Please ensure all elements have the same length.") self.__value = val @property def shape(self) -> tuple[int, int]: return (len(self.value), len(self.value[0])) def __repr__(self): return f"Array({self.value}, shape={self.shape})" def __eq__(self, other: 'Array') -> bool: if self.shape != other.shape: return False return all(x == y for x, y in zip(self.value, other.value)) def __neq__(self): return not self.__eq__ def __getitem__(self, idx: tuple[int, int]) -> int | float: if idx[0] > self.shape[0] or idx[1] > self.shape[1]: raise IndexError(f"Index out of bounds for the array of shape {self.shape}") return self.value[idx[0]][idx[1]] def __add__(self, other: 'Array') -> 'Array': v = [] if self.shape != other.shape: raise ValueError("Can only add arrays of the same shape.") for i in range(self.shape[0]): v.append([]) for j in range(self.shape[1]): v[i].append(self.value[i][j] + other.value[i][j]) return Array(v) def __mul__(self, other: 'Array') -> 'Array': v = []
{ "domain": "codereview.stackexchange", "id": 43660, "lm_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, algorithm", "url": null }
python, performance, algorithm return Array(v) def __mul__(self, other: 'Array') -> 'Array': v = [] if self.shape != other.shape: raise ValueError("Can only add arrays of the same shape.") for i in range(self.shape[0]): v.append([]) for j in range(self.shape[1]): v[i].append(self.value[i][j] * other.value[i][j]) return Array(v) @classmethod def from_text(cls, input_file: str | Path, skip_rows: int | None = None, delimeter: str = ',') -> 'Array': inp = Path(input_file) if not input_file or not inp.exists(): raise IOError("No input file provided or file does not exist.") with open(inp, 'r') as file: arr = [] for idx, i in enumerate(file.readlines()): if skip_rows is None or skip_rows <= idx: try: arr.append([float(k) for k in i.strip().split(delimeter)]) except (ValueError, TypeError) as e: raise TypeError("Input data must be castable to float. " "Found incompatible data type. Check your inputs.") from e return cls(arr) def matmul(self, other: 'Array') -> 'Array': pass
{ "domain": "codereview.stackexchange", "id": 43660, "lm_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, algorithm", "url": null }
python, performance, algorithm Answer: (Array.value does look a candidate for name mangling - I'm amazed it works as presented.) Don't write, never commit/publish undocumented/uncommented code. If you kept matmul() && __mul__() together, the difference in docstring or no docstring was obvious. Avoid multiple indexing in inner loops. Give Python iteration and comprehensions a try - def __mul__(self, other: 'Array') -> 'Array': """ point-wise product """ if self.shape != other.shape: raise ValueError("Can only mul arrays of the same shape.") return Array([[svalue * ovalue for svalue, ovalue in zip(srow, orow)] for srow, orow in zip(self.value, other.value)])
{ "domain": "codereview.stackexchange", "id": 43660, "lm_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, algorithm", "url": null }
python Title: Converting text to dataset parameters: Union of an object and the category to which it belongs Question: A task: You need to open the parentheses combined category and the object that belongs to it. The combination of categories means that we have a category and its objects, for example genre (rock, pop, hip-hop) needs to be converted to genre_rock, genre_pop, genre_hip-hop. At the input and output of the code is a string, just during operation it is converted into a list. The purpose of the code is to clear one of the dataset parameters to work with the recommender system. Question: What parts of the code can be optimized so that it works faster + does not look ugly? Example: 'Category (first ,second (1,2)) -> 'Category_first,Category_second_1,Category_second_2' 'Category (first ,second)' -> 'Category_first,Category_second'
{ "domain": "codereview.stackexchange", "id": 43661, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python 'Category (first ,second)' -> 'Category_first,Category_second' Code: def i_par_find(text, i_par_l): l_r = 0 i_par_r = i_par_l for s in text[i_par_r:]: if s == '(': l_r += 1 elif s == ')': l_r -= 1 i_par_r += 1 if l_r == 0: return i_par_l, i_par_r ​ def glue_list(text, i_par_l, i_par_r, i_comma): word_list = re.sub(r'[()]', '', text[i_par_l:i_par_r]).replace(' ', '_').split(",") word_list = [w.strip('_') for w in word_list] category = text[i_comma:i_par_l].strip() list_word = [] for w in word_list: if w != '': list_word.append(f'{category}_{w}') return ",".join(list_word) ​ def list_w(text): # If there is no comma, the category search starts at index 0. i_comma = 0 # Index i = 0 ​ while i < len(text) - 1: # Select a specific character in the text. i += 1 s = text[i] ​ # Step 1: save the last comma before the parenthesis if s == ',': i_comma = i ​ # Step 2: Check for "(" if s == '(': # Step 3: Look up the index of the leading "(" and closing ")", nested parentheses are ignored. i_par_l, i_par_r = i_par_find(text, i) ​ # If a comma is inside brackets, then its index is set to zero. if i_comma >= i_par_l and i_comma <= i_par_r: i_comma = 0 ​ # If there is "(" inside the found slice, then we use recursion if '(' in text[i_par_l + 1:i_par_r - 1]: text = text[:i_par_l + 1] + list_w( text[i_par_l + 1:i_par_r - 1]) + text[i_par_r - 1:] ​ # If processing text doesn't start at 0, add 1 to index to capture comma. if i_comma != 0: i_comma += 1
{ "domain": "codereview.stackexchange", "id": 43661, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python ​ # Adding a comma depending on the position of the processed area in the text c_or_n = '' if i_par_r <= len(text) and text[i_par_r - 1] == ',': c_or_n = ',' ​ # Step 4: Connect parameters and categories, with text before and after the treated area. text = text[:i_comma] + glue_list( text, i_par_l, i_par_r, i_comma) + c_or_n + text[i_par_r:] ​ text = re.sub(r'[()]', '', text) return text list_w(text) Answer: It looks like you are trying to parse the string character by character, mutating the text as you go along. def list_w(text): ... i = 0 ​ while i < len(text) - 1: i += 1 s = text[i] ... text = text[:i_par_l + 1] + list_w( text[i_par_l + 1:i_par_r - 1]) + text[i_par_r - 1:] ​ ... text = re.sub(r'[()]', '', text) return text I find it extremely hard to reason about this code. A clearer algorithm could be to work from the inside out. With 'Category (first ,second (1,2))', find the innermost category pattern second (1,2) and replace that with second_1, second_2, producing 'Category (first ,second_1, second_2)'. Since there are more parenthesis, repeat, which produces the desired result. Finding the innermost category pattern starts with looking for text which does not contain parenthesis [^()]+, but is surrounded by them, \( ... \). We also need to find a "word" before that, possibly with some trailing space: \b \w+ \s*. To that regex, we'll add capturing groups (...) to extract the term before the parenthesis and well as inside. \b(\w+)\s*\(([^()]+)\) Now all that is left to do it split on any commas in the second group, strip off spaces, and add the first group as a prefix to each term. Join the result with commas, and replace what what originally matched. Repeat until there are no more parenthesis. import re
{ "domain": "codereview.stackexchange", "id": 43661, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python def categories(s): def expand(m): prefix, suffixes = m.groups() return ",".join(f"{prefix}_{suffix}" for suffix in map(str.strip, suffixes.split(","))) while '(' in s: s = re.sub(r"\b(\w+)\s*\(([^()]+)\)", expand, s) return s s = 'Category (first ,second (1,2))' print(categories(s))
{ "domain": "codereview.stackexchange", "id": 43661, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
java, strings, interview-questions Title: Reversing the words order of a string Question: A couple of weeks I had a coding interview and the problem to solve was very simple: reverse the words order of a string. What did I do wrong here? public static String reverse(String phrase) { String[] words = phrase.split(" "); StringBuffer sb = new StringBuffer(); for (String word : words) { String reversed = new String(); for (int j = word.length() - 1; j >= 0; j--) { reversed += word.charAt(j); } sb = sb.append(reversed).append(" "); } return sb.toString().substring(0, sb.toString().length() - 1); } Answer: The main reason why you fail may be because your code reverse the entire sentence while only the order of the words must be reversed; Hello the world should be world the hello. If you want to reverse the whole string, there is StringBuilder.html#reverse() That put aside. Some problems I see is the usage of StringBuffer which is slower but synchronized. There is also this new String() in your loop which is useless because you can already use sb.append. And there is this ugly string building at the end where sb.toString() is abused while sb.delete can do it. For the fun I made mine which revert the words by traversing the char sequence from the end and insert the character at a given index. The index is changed when a space is found to insert at the end of the new string : https://github.com/gervaisb/stackexchange-codereview/blob/q184229/src/main/java/q184229/Sentence.java final StringBuilder target = new StringBuilder(value.length()); for (int i=value.length()-1, at=0; i>-1; i--) { char character = value.charAt(i); if ( Character.isWhitespace(character) ) { target.append(character); at = target.length(); } else { target.insert(at, character); } }
{ "domain": "codereview.stackexchange", "id": 43662, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, strings, interview-questions", "url": null }
c++, design-patterns, graph Title: C++ Graph class with multiple property maps (edit) Question: I wrote an improvement from my previous graph class: Link #include <algorithm> #include <concepts> #include <list> #include <map> #include <ranges> #include <unordered_map> #include <unordered_set> #include <stdexcept> #include <vector> namespace frozenca { template <typename T> concept Arithmetic = std::is_arithmetic_v<T>; template <typename T> concept Descriptor = std::is_default_constructible_v<T> && std::is_assignable_v<T &, T> && std::equality_comparable<T>; template <typename Derived> struct EdgePropertyTag {}; struct EdgeWeightTag : public EdgePropertyTag<EdgeWeightTag> {}; EdgeWeightTag e_w; template <typename Derived> struct VertexPropertyTag {}; struct VertexDistanceTag : public VertexPropertyTag<VertexDistanceTag> {}; VertexDistanceTag v_dist; template <typename Derived> struct EmptyProperty { void operator()() const noexcept { // do nothing } }; template <Descriptor VertexType, typename Traits, typename Properties> class Graph : public Traits::template Impl<VertexType>, public Properties::template Impl<VertexType> { public: using TraitBase = Traits::template Impl<VertexType>; using TraitBase::add_edge; using TraitBase::add_vertex; using TraitBase::adj; using TraitBase::has_edge; using TraitBase::has_vertex; using TraitBase::vertices; }; template <Descriptor Vertex, typename Derived> struct AdjListTraits { using vertex_type = Vertex; using vertices_type = std::unordered_set<vertex_type>; using vertex_iterator_type = vertices_type::iterator; using edge_type = std::pair<vertex_type, vertex_type>; using adj_list_type = std::list<edge_type>; using edges_type = std::list<adj_list_type>; using edge_iterator_type = adj_list_type::iterator; using const_edge_iterator_type = adj_list_type::const_iterator; using out_edges_type = std::unordered_map<vertex_type, typename edges_type::iterator>;
{ "domain": "codereview.stackexchange", "id": 43663, "lm_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++, design-patterns, graph", "url": null }
c++, design-patterns, graph vertices_type vertices_; edges_type edges_; out_edges_type out_edges_; const auto &vertices() const noexcept { return vertices_; } void add_vertex(const vertex_type &vertex) { vertices_.insert(vertex); if (!out_edges_.contains(vertex)) { edges_.emplace_front(); out_edges_.emplace(vertex, edges_.begin()); } } bool has_vertex(const vertex_type &vertex) const { return vertices_.contains(vertex); } std::ranges::subrange<edge_iterator_type, edge_iterator_type> adj(const vertex_type &vertex) { return *out_edges_.at(vertex); } std::ranges::subrange<const_edge_iterator_type, const_edge_iterator_type> adj(const vertex_type &vertex) const { return *out_edges_.at(vertex); } bool has_edge(const edge_type &edge) const { auto edge_range = adj(edge.first); return std::ranges::find(edge_range, edge) != edge_range.end(); } void add_edge(const vertex_type &src, const vertex_type &dst) { out_edges_[src]->emplace_front(src, dst); } }; struct AdjListTraitTag { template <Descriptor VertexType, typename Derived> using Trait = AdjListTraits<VertexType, Derived>; }; template <Descriptor VertexType, bool Directed, typename ContainerTraitTag> struct GraphTraitsImpl : public ContainerTraitTag::template Trait< VertexType, GraphTraitsImpl<VertexType, Directed, ContainerTraitTag>> { using vertex_type = VertexType; using Base = ContainerTraitTag::template Trait< VertexType, GraphTraitsImpl<VertexType, Directed, ContainerTraitTag>>; static constexpr bool directed_ = Directed; using Base::add_vertex; using Base::adj; using Base::has_edge; using Base::has_vertex; using Base::vertices; void add_edge(const vertex_type &src, const vertex_type &dst) { add_vertex(src); add_vertex(dst); Base::add_edge(src, dst); if constexpr (!directed_) { Base::add_edge(dst, src); } } };
{ "domain": "codereview.stackexchange", "id": 43663, "lm_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++, design-patterns, graph", "url": null }