instruction
stringlengths
71
95.1k
There are many template engines but my question is: Why do they still exist? Can we not achieve the same job with readily available JavaScript Template Literals? So influenced from this blogpost, I have come up with something as follows. Do you think this is reasonable in daily JavaScript? The following code is pure Ja...
/// #include <stdio.h> void ConvertNumberToBinary(int Number, int *Array) { for(int I = 0; I < 32; ++I) { int ZeroOrOne = Number%2; if(ZeroOrOne < 0) { ZeroOrOne = 1; } *(Array + I) = ZeroOrOne; Number = (Number >> 1); } } int ma...
The feature Here is a Grid class representing a 2d grid. The class will get templated once it reach a satisfactory state. At this time the cells are int values. This Grid class allow for iteration by rows using simple range-for syntax. Grid grid(8, 8); for (auto&& row_it : grid.Rows()) { for (auto&...
At the moment, it is simply massive. I already reduced the size by about a hundred lines but it still seems way too big... Would appreciate some help :) using System; class Program { static int turns = 1; static int player = 2; static char[] board = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; stat...
I need to handle different states of a complex GUI control (such as NORMAL, DRAGGING, MARKING, ...). I came upon this idea: void dispatch(auto const i, auto&& ...f) noexcept(noexcept((f(), ...))) { std::underlying_type<std::remove_const_t<decltype(i)>> j{}; ((j++ == i ? (f(), 0) : 0), ...); } There would be an ...
This is a simple Python 3 program that verifies whether a string is a valid IPv6 address or not, parses IPv6 address to its hexadecimal and decimal values, and converts an integer to IPv6 format. I am writing a webscraper, and to reduce network IO bound time complexity I need to programmatically lookup DNS records of t...
This macro calculates some basic figures from a given set of data. But it runs very slow probably due to me referencing the sheet again and again. Does anyone have a better idea on how to optimize this code: Sub Handler_Fees() Dim strFile, tarFile As String Dim Source As Workbook Dim Target As ThisWorkbook Dim ws1 ...
I'm using TypeScript for my Vue app and have a custom type I'm working with type MyCustomType = { fooProperty: string, barProperty: string /* ... other fields ... */ }; This type holds a bunch of properties acting as a "composite key". So the combination of all properties must be unique. First approach: T...
I made a custom Binance API wrapper (BinanceRestClient) which uses IHttpClientFactory in order to prevent socket exhaustion, while also ensuring that DNS changes are respected. I looked at the implementation of a deprecated API wrapper (this one) and I realized how clean they did it. For ex. my GetBalances() method is ...
Added the problem link below and my implementation of it. Took me a few hours to program. I have added comments to explain my thought process. Problem Link Goal - To implement a program that identifies to whom a sequence of DNA belongs. should require first command-line argument the name of a CSV file containing the S...
This is one of my first real projects in python. It's basically a one-way chat where the server sends away an encoded message. The logic of it is pretty simple and I know there is some unnecessary code in there. I have also made a simple client who receives the messages and decrypts it, based on if the user input == th...
The code below takes a list of users and displays two lists Refused users Admitted users Sample output: Refuse: Phil, Lola. Admit: Chris, Anne, Colin, Terri, Sam, Kay, Bruce. Any feedback is highly appreciated. const people = ['Chris', 'Anne', 'Colin', 'Terri', 'Phil', 'Lola', 'Sam', 'Kay', 'Bruce']; let refusedPe...
I've implemented a menu system where all input calls ultimately go through io_getline, a function which reads a line of input up to the max buffer size or newline (the rest of the line is discarded if it exceeds the buffer size) and returns the number of characters written, or -1 if an EOF is encountered. When an EOF i...
Code: # read file of first agrument import sys, os try: data = open(sys.argv[1]).read() except: data = open("File.txt").read() sys.argv.append("File.txt") dct = {"@": data, "E": "0"} iteration = 0 RESET = False define = False printf = False replace = False inp = False join = False Reverse = False getascii = False ge...
I've been trying to implement a simple Boost PMR allocator that has a fixed amount of memory. My first implementation (which can be found here) had undefined behavior and did not handle memory alignment. I've been doing a lot of reading around these topics and while I'm still unclear about some of it, I believe the cod...
I created a method to return a copy of List<T>, basically I convert the List<T> into an array T[], then perform the copy with the arrayCopy(T[]) method and back convert again in List<T>. I want to know if the code will be run successfully in different scenarios and it is good in performance or is there a way to do it b...
I have a collection which, after the code has ran, looks something like the following: [ { title: 'alpha', lines: [ { *some object* } ] }, { title: 'bravo', lines: [ { *some object* } ] }, { title: 'charl', lines: [ { *some object* } ] }, { title: 'delta', lines: [ { *some object*, *some object 2*, *some object...
I need to write a function to count numbers of nests in an iterable. I reached my goal but wondering if there's any more neat/faster solution (maybe even a library or so?). Besides I'm afraid that my code is error prone. Let's analyze two examples: dct_test = { "a": {1: 2, 2: 3, 3: 4}, "b": {"x": "y", "z": [1, ...
I have the following function that returns StaffQualifications where either the qualification is expiring or the qualification type is expiring, but this section doesn't seem to sit well with me as it splits up the SQL string... Should this be two separate functions perhaps even though 95% of the query is the same? ...
Let's suppose I have 2 repositories: first is responsible for creating job and return jobId second is responsible for creating log and take jobId as argument My goal is to: save Job and Log simultaneously prevent situation when in case of error only Job would be saved without Log What is the most recommended way to...
I wrote this script partly as an exercise in learning Bash and partly because I needed a tool to find specific versions of library files and copy them to a particular device. The script takes parameters that control its operation. First, it searches for the file specified by the user. Then it displays the search result...
I'm using (non-boost) Asio 1.18.1 and C++17. Forgive the boost tag, there wasn't a more specific one. I have a async_connect_with_retry composed asynchronous operation: /// Calls resolver.async_resolve(...), async_connect(socket, ...), and (on /// failure) timer.async_wait(...) to start over. template <typename Timer, ...
I'm trying to implement sum of 2 array using multi threading. I expected that when I use more threads it will be faster than when I use one thread, but that isn't the case. public static int[] a = new int[100]; public static int[] b = new int[100]; public static int[] c = new int[a.Length]; publ...
I want to edit Windows hosts file in the best way for the end user, using a batch-only solution. I ended up with this script, which works fine, but since I don't have enough knowledge, the syntax is very poor. So please, may you take a look and tell me how to improve it, especially the =999 part (for some reason I can'...
I started learning classes and operator overloading in C++. To test my skills I decided to make a Fraction class with all necessary operations. I would appreciate improvements and suggesstions on my implementation. Here is the code - #include <iostream> #include <string> #include <stdexcept> // throw std::invalid_argum...
I have a string like the one below from which I am extracting the tariff name. const url = "https://any-api/supplier/tariffSelectionG_E5449168?t=randomChars" So from the above string, I want text tariffSelectionG_E5449168 and I am using the code below at the moment, which is working fine. const supplyUrl = "https://any...
I have tried my hand with implementing simple quadrature formulas in C++. Definite integral: $$\int_a^b f(x) dx$$ Domain of integration \$[a, b]\$ divided into \$n\$ intervals of equal length \$h = (b - a) / n\$. Midpoint of interval \$h_i = b_i - a_i\$ is $$x_i = a + h / 2 + (i - 1) h$$ with \$i = 1, \dots, n \$. Newt...
My Data consists of rows containing a Length/Duration in Minutes, a Begin & EndTime. The precision is 1min (or larger). the table looks something like that: CREATE TABLE public."TimeSeries" ( "Id" uuid NOT NULL, "BeginTime" timestamptz NOT NULL, "EndTime" timestamptz NOT NULL DEFAULT '0001-01-01 00:00:00' :...
I'm learning Objects calisthenics and I was practicing with the typical Tic Tac Toe game, I was wondering if you could gimme feedback about my mistakes (Algorithmic problems, logic, and especially OOP following Objects calisthenics rules). Thanks in advance! Only One Level Of Indentation Per Method Don’t Use The ELSE ...
In this code the angle between the minute and hour hands of an analog clock are found and calculated and the smaller angle between them returned. This code works perfectly and I am getting back the results I expect. We were told to do this and any testing if necessary. I got asked this in an interview question and want...
Climbing the Leaderboard An arcade game player wants to climb to the top of the leaderboard and track their ranking. The game uses Dense Ranking, so its leaderboard works like this: The player with the highest score is ranked number \$1\$ on the leaderboard. Players who have equal scores receive the same ranking numbe...
I have implemented few functions in C language that manipulate strings. These functions are not present in the standard C library. string_library.c #include <stdio.h> #include <stdlib.h> #include "string_library.h" /* * get_input_from_stdin_and_discard_extra_characters(char *str, long size): * * Function get_in...
I have several products. A product can have 1 or more images. In each image, we have content slot. I don't want duplication per content slot in a product. My code works fine. I'm just wondering what will be a better way to do this or improvement on my code? Codesandbox is here CLICK HERE <Autocomplete fullWid...
I'm learning rust (coming from C++) and playing around with different small algorithms to understand the ownership & borrowing concepts better. Currently, I'm having difficulties finding the idiomatic way to reuse a Vector after iterating over it in a for-loop. This is the (very verbose) code I currently have: fn build...
This is follow-up on SQL (ODBC) bind to C++ classes row-wise The main idea behind this code is to minimize the number of ODBC API calls, because profiling shows significant amount of time is spent in intermediate layers (not waiting for IO). ODBC supports bulk processing, but it requires all buffers to be in-place (see...
This question is a supplement to my previous question: Counting 'absolute' nesting levels of an iterable. I would like to expand functionality of counting nests in order to get values from given nest. I created 2 examples: dct_test = { "a": {1: 2, 2: 3, 3: 4}, "b": {"x": "y", "z": [1, 2, 3, {7, 8}]}, "c": {...
I am new to react and I tried to implement a TODO application using react state and props. I need somebody to just review the code and suggest improvements in the code. Currently I have not added any CSS to it, I am focusing more on react practices. code sandbox link- https://codesandbox.io/s/adoring-archimedes-se4vm A...
I'm implementing some simple algorithms (e.g. two-sum) in OCaml and I am unsure why my OCaml solution is running much slower than the equivalent Python version. My OCaml version: open Base let two_sum_hash lst target = let rec loop tbl counter = function | [] -> failwith "No sum found" | x :: xs -> match Ha...
take an array of two numbers who are not necessarily in order, and then add not just those numbers but any numbers in between. For example, [3,1] will be the same as 1+2+3 and not just 3+1. function sumAll(arr) { let start = arr[0]; let end = arr[1]; if (start > end) { let temp = start; start = end; e...
This is my first real personal application and I'm just looking for some outside feedback. Completely built in Python, this is a Pokédex for the Pokémon Mystery Dungeon series. I hope to eventually publish to the Android app store. If you choose to check it out... don't be nice. Tell me how bad it is, (just make sure y...
I have implemented a library which makes Java Swing programming easier. I am just posting the library. There is a program that uses this library to implement examples of many Swing components but I cannot include that program here because the total size will become more than the allowed limit of 65K characters. I will ...
This is in continuation of my previous post for code review of Java Swing Library: Java Swing Library Since the limit on total number of characters is 65K, I split my program in two parts. The first was Java Swing Library and the second one is this one. I have implemented a program that uses my Java Swing Library to sh...
Background: Hello, I'm a student (since 2 months) and I've created a small MVP of a weather application. So now I'm refactoring my code because it looks hideous and it is hard to work with. The problem: In the snippet I will provide you will see that I repeat code for a .map(), which I know is not the best practice. Bu...
As already written in the title I want to count the numbers in the range (x+1, y) where x and y are integers, in which the sum of the digits in odd places have the same parity of the ones in even places. I made this code: def findIntegers(x, y): count = 0 for k in range(int(x)+1, int(y)+1): odd_sum...
For a program I'm writing, it requires a lot of printing and receiving user input. I've found it cumbersome to keep specifying the type strings in printf, and having to write another printf before using scanf to receive input. I've decided to write two macros, print and input, that achieve exactly what I want. A simpli...
Modules for FPGAs for generating a pseudo-random bit sequence are presented. The first module generates a bit sequence. The third module speeds up the generation by transferring the bus to, for example, a multiplexer which is controlled by a faster device. Hence this bus is serialized into a bit sequence. prbs.sv `time...
I want to simplify some code I have written but not sure how to go about doing it. When my workbook opens it checks the current date and compares it to dates I have on a sheet. If the current date is <= date on sheet it writes the date range to a cell. My issue is I have 13 If statements and would like to simply/neaten...
This project is based off the shunting yard algorithm and has additional features such as negative value parsing. It's like a scientific calculator. I am looking to improve this project by getting rid of potential errors and optimizing code. I have tried many cases and have fixed the broken ones I've seen. However, alt...
I'm developing a REST API using Azure Functions with .NET 5 (Isolated) and I want to add an OpenAPI spec for each route. But it looks like this: namespace AzureFunctionsREST.API.Functions { public class ReporterFunction : BaseFunction { private readonly IReporterRepository _reporterRepository; ...
I needed to pass a const reference to part of a std::vector without copy. I posted the previous version in my earlier question, thank you for the great support! As far as I know this version supports not only std::vectors but any kind of iterator based continuous containers! Some research, particularly this SO question...
I have created a simple abstract class called expr_node which will serve as a base class for any expression-related nodes. My goal is to create a simple deleter that can delete the allocated memory from the derived class in which would be recursive in some cases. Rules and constraints (NOTE: for practice purposes only)...
Here is my A* algorithm. I tried hard to implement it generically, but come up only with one idea to use lambdas for heuristic and next nodes (neighbours / successors) functions. I know that using good heuristic function is the key to speed up, but here i'm trying to squeeze everything from current implementation not t...
So I tried implementing a easily extendable solution for Sqrt decompostion, I deduced that only identity value, operation and block update logic change and rest of the code is same. So i created 3 functions T identity() T operation(const T&a, const T&b) T block_update_calc(const T old_block_value, const T, const T &o...
I have a web server that can send websites, images, mp3 and other things and I was wondering how I could improve the code and make the server more efficient. //this is where you enter the default file directories char *defaultDir1 = "/Users/rowan/Desktop/webServer(Mac)/website/displaySite/"; char *defaultDir2 = "/Users...
This query is a part of Conway’s game of life. Currently, this program takes about 70 lines of code in Python to return the functionality of the game, which can be simplified to fewer lines of code and it ends when a keyboard interrupt occurs. I eventually want to eliminate the keyboard interrupt and improve this code ...
The program is designed to take data from a MySQL database, using mysql-connector-python, and print it as a table in Python using the texttable module. The program also plots charts based on the data from MySQL database using the matplotlib library. For those who don’t have any data in MySQL, the program will assist a ...
I am having trouble with applying to 3 steps needed to proof correctness, most likely because I did not formally study CS or Mathematics and am still learning about loop and class invariants. The three steps: Initialization Maintenance Termination My understanding of the invariant is that, at the end of the partition...
I have completed my project which simulates the path of a particle trapped in a device known as a magnetic mirror. I would like your thoughts and improvements on my implementation. Here is the code: from numba import jit import numpy as np import matplotlib.pyplot as plt # Plot attribute settings plt.rc("xtick", lab...
Rules: You should create a function that receives a string with brackets, parentheses, or curly brackets, an example: test('{A}') The function must check that the opening and closing of the brackets are correct. If they are correct it should return true, else it should return false. Examples: '{A}' // true '[A]' /...
My implementation of the lowest common ancestor (LCA) algorithm for my tree data structure. I selected the non-preprocessed (naïve) implementation for this first implementation. Support for any number of input positions (1+) seemed appropriate. The tree is not binary and a node-based implementation. Any aspect of the c...
Predeclared class instance tracks the number of regular instances In VBA, predeclared class instances can act as object factories, and in general, it makes sense to keep this instance stateless. However, I needed to count non-default instances and execute reset code whenever all of them were destroyed. I came up with t...
The code below will generate an HTML select tag and options using a text file having list of countries. If the file doesn't exist or contains only empty / white space lines then generate an input box instead of select tag. generate_select_tag_and option_from_list_of_countries.php <?php $file = "countries.txt"; ...
This program takes x numbers and displays the mean, median and mode. My goal here was to use classes and class properties the best i could to make the code shorter (honestly i may have just made it longer), so i would like to get some feedback on that. import tkinter as tk from typing import Callable, List from statist...
Terminology usage: I will use chunk, page, partition, or subrange interchangeably. I frequently use and promote using the System.Collections.Concurrent.Partitioner class (see link). For my particular usage, I always use it for a full indexed collection, i.e. IList<T>. Sometimes I may use it for single-threaded proces...
I've built this complex form or at least what I would consider a complex form and it feels really dirty. It felt dirty while I was programming it but I wanted to get it working and then go back and refactor it. The form consists of the days of the week and for each day there are three options (breakfast, lunch, dinner)...
I'm currently learning python with an udemy course. I wrote this code, which is meant to be a higher lower game, where the second answer always stays. As far as i tested it my code is working fine, but i feel like many solutions are bad. Its just felt weird coding some of the solutions, but i cant come up with better s...
I want to use shell scripts to consume kafka messages and return to status. I found that my script wasn't efficient enough. Can I write this script better? I want to output kafka-console-consumer.sh execution time, how do I write it? The input result can be kafka_Check|consumer:0|consumer_time:0.3s #!/bin/bash result="...
I have the following piece of code. someFunction = async () => { let boolean = await this.someFetchFunction(); if (!boolean) boolean = this.someOtherFunction(); return boolean; } I was wondering what would be a cleaner/better solution to this code. Was thinking in a more ES6 way and to avoid reassigning variab...
I'm trying to take a raw byte array of audio and trim it. The user selects a start and end value using a range slider. // args are doubles from 0.0 - 1.0 // audio is uncompressed, 16-bit, 44,100hz, MONO public static byte[] trimBytes(byte[] fullLength, double from, double to) { int startingByteIndex = (int) ((doub...
strcat_new() function, not present in standard C library. Syntax: char *strcat_new(char *delim, long num_args, ...); The code is below. Can someone please do the code review? UPDATE: This version of strcat_new() has a bug. This bug has been fixed in the newer version. The newer version is called str_join(). You can fin...
I have written a Python3 program that looks for matching strings and removes them from files. import os path = os.getcwd() ignore_files = ["remove-lines.py", "to-remove"] with open("to-remove", "r", newline="") as pattern_file: remove_patterns = [l for l in (line.strip() for line in pattern_file) if l] for ro...
Resolving circular references in VBA via ObjectStore class and CleanUp cascade I have been working on a VBA database library and realized I had a few circular reference loops in my class hierarchy, as illustrated in the figure (left panel). I recalled reading an RDVBA blog post about the circular reference issue and th...
Checking return flags is generally very important. But, when you don't need to based on meeting pre-conditions, the syntax gets unnecessarily ugly. This class allows returning a value with flags that the caller can ignore. #include <tuple> template <class T, class U> struct retval { T val; U flags; ~retval...
I have a vector of values vals, a same-dimension vector of frequencies freqs, and a set of frequency values pins. I need to find the max values of vals within the corresponding interval around each pin (from pin-1 to pin+1). However, the intervals merge if they overlap (e.g., [1,2] and [0.5,1.5] become [0.5,2]). I have...
I'm interested in how I can improve my HTML and CSS? I didn't yet learn JS, even though I used it for onclick function, so I'm not currently interested in how to improve the JS in this code. I was wondering: Is it alright to use spans inside button for accessibility? First I had all divs, than made the parent div into ...
I am using a KeyNotFoundException to check if an item exists in a Dictionary, creating it when the exception is thrown: public Section GetSection(int plankNo, int sectionNo) { if (plankNo < 1 || plankNo > NumberOfPlanks || sectionNo < 1 || sectionNo > SectionsPerPlank) { return Section.UNKNOWN; } ...
Given the current table: +------------+-------+ | date | value | +------------+-------+ | 01/01/2000 | 1 | | 03/04/2000 | 3 | | 05/08/2000 | 4 | | 07/11/2000 | 2 | +------------+-------+ For each date I'm looking to get an average of the values for the preceding dates where each value is discount...
I was looking for C++ versions of the machine learning metrics implemented in Python's sklearn, but they were surprisingly hard to find. I came across a website that had most of the loss functions implemented in Python, so I did my best to translate them to C++. Below is what I have so far. I plan to implement most of ...
I have a function general_statistics that takes a dict as input and get the wanted information. the function is working without any problem, but I want to know if I can do it with a pythonic way because I'm trying to improve my skills. def general_statistics(input_data: dict): result = {} if 'general' i...
I have two large arrays of objects, which look something like: [ { key: "prop", Email: "someEmail@email.com" }, //... ] and [ { key: "prop", "AN EMAIL": "SomeEmail@emailcom" }, //... ] To compare the array of objects by email, I first map the arrays to only grab the emails, then I format the emails as follows...
I have some code that needs to return a datetime of the next 9am or 9pm, UTC. I've figured out some code to do this, but it feels unnecessarily complex to me. Is there a way to simplify this? from datetime import datetime, timezone, timedelta class NineOClockTimes: @staticmethod def get_next_nineoclock_time(cu...
https://www.hackerrank.com/challenges/absolute-permutation/problem I know that if you work out the math and logic first, the algorithm can be simplified greatly (shifting indices), but is that the only way to solve this and pass all test cases? Checking if a value is in a list can be slow, but I don't know how to optim...
Consider the following two classes: public class Person<P extends Comparable<P>> { private List<Person<P>> following = new ArrayList<Person<P>>(); private List<Person<P>> friends = new ArrayList<Person<P>>(); private P id; public Person(P id) { this.id = id; } public P getId() { ...
I have invented the fastest string search algorithm. It is called ""Choudhary String Search Algorithm (choudharyStringSearchAlgorithm)"". I have compared my algorithm with Brute Force Algorithm, Boyer Moore Algorithm, Rabin Karp Algorithm, and Knuth Morris Pratt Algorithm and my algorithm is the fastest. You can copy t...
I was doing the Magic 8 Ball project (its task is to read a user's question and output a prediction) on Python and wrote the following code: from random import choice from time import sleep list_of_predictions = [ "Undoubtedly", "It seems to me - yes", "It is not clear yet, try again", "Do not even think", "A...
I am learning Python and for practice I have written this function which sorts a list. Can you please provide feedback on how I have structured it and what better ways could be there to write it for optimization/structuring? originallist=[5, 4, 0, 3, 2,1] lowervalue=int() duplicatelist=originallist[:] ## This list is ...
I have the following vue component which all works fine <template> <div class="sales-agreements"> <nav class="sales-agreements__navigation"> <ul class="sales-agreements__navigation-list"> <li class="sales-agreements__navigation-item"> <router-link :to="{ path: '/' }" class="sales-agreeme...
I have a long switch statement and it would be great if someone know how to make it cleaner. Code is available on Github: https://github.com/Rabbit-Company/Passky-Server/blob/main/php/index.php And for those who don't want to visit Github here is the code: switch($_GET['action']){ case "getInfo": if(Dat...
This is a command line application which displays the text of an EPUB one sentence at a time. I am going to make it more robust, including: make the segmentation more accurate, because it currently groups together unrelated text sometimes make it faster, so that the segmentation occurs a first time, then the segments ...
I'm learning Java in a MOOC right now and this is my solution for exercise grade statistics. This is the exercise: In this exercise we create a program for printing statistics for points in course. The program receives points (integers from zero to one hundred) as input, based on which it prints statistics about grade...
I want to find if all of a list of substrings exist in a string, in the correct order (with or without spaces between them), it seems to be a good use for regex. I think I need to build a regex filter of "a.*b.*c" and use search to find that anywhere in my string. Are there any other approaches I could consider or bui...
This is the code I came up with for the Rust pig latin exercise. I am looking for suggestions on how to make it more idiomatic. I think working with iterators instead of chars and Strings would be a step in the right direction? I was unable to figure out how to use .map to reach the same result. I would have liked to i...
I recently faced this following question in a Java coding round, needless to say I did not get a callback. So I want to know where I am going wrong in my solution and also what can be done to improve it. The Problem statement was as follows: Create a java program, with two components, a supplier and consumer. Supplier...
Just solved Euler Project Problem 2 using JavaScript and I would like to know how I could improve my code. I do think it looks good, but you never know. Problem Statement Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3...
I'm trying to improve this wrapper by replacing the Newtonsoft.Json with System.Text.Json in its BinanceWebSocketClient class and more specifically the HandleObjectMessage method. It is a message handler, which is supposed to parse the JSON results returned by the combined stream. Combined stream events are wrapped as...
I am trying to solve a needle in haystack using Rabin-Karp algorithm, but for large inputs my code takes way too long time. Here is the part which apparently is too slow: char_map = dict(zip(list("abcdefghijklmnopqrstuvwxyz"), list(range(1, 29)))) def hash_function(s): hash = 0 n = len(s) for i, ch in enum...
On web pages, obviously large photos (e.g. 4000x4000px) cannot be served with a reliance on CSS to do the resizing: it would be too slow for end users and too bandwidth-consuming for the server. So it's important to rescale photos to the desired size that will be actually used on the website. For this reason I usually ...
I wrote a method that lets me retry RestSharp requests when a specific exception is thrown. Here's the code for that method: private async Task<T_Out> RunRequestWithRetry<T_In, T_Out>(Func<SignatureAccount, T_In, T_Out> request, SignatureAccount signatureAccount, T_In requestBody) where T_Out : Task { try { ...
This is a popular question on LeetCode: 76. Minimum Window Substring Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". The test...
I am doing the Advent of Code challenge to learn Rust (obviously there may be spoilers if you still want to do the challenge). The instructions are too long to include verbatim so I will link them and give a summary for the two parts. In part 1, the programme must compare a user-provided list of integers and count ever...