instruction
stringlengths
71
95.1k
import random import string LENGTH = 5 LIST_SIZE = 1000000 def generate_word(): word = [random.choice(string.ascii_lowercase) for _ in range(LENGTH)] word = ''.join(word) return word list1 = [generate_word() for _ in range(LIST_SIZE)] list2 = [generate_word() for _ in range(LIST_SIZE)] intersection = [w...
I would like to share with you the code from the application I just finished. It is a web application written in HTML, CSS, JavaScript and jQuery. It uses LocalStorage to store your tasks. The application also displays the date of adding and completing the task. You can add, edit, delete and mark tasks as done. I would...
I would like to improve my code style and its efficiency. I'm just moving beyond the standard recursive approach to a lot of simple algorithms. This post has two code snippets with slightly different but related problems. They're both in Python. The first snippet is just to produce Fibonacci numbers. I think I've do...
I set out to write a small Python script to tell me cheapest domains. I manually scraped for data from iwantmyname.com into a plain text file as follows: .COM Commercial $14.90 The most registered domain extension on the planet. .CO 48% off! Colombia $19.90 then $39.00/year It's .com without the m. .APP Generic $29.00 ...
Inspired by and created because of python3 utility: convert safely to int and driven partly by the 'refactor' in my answer. The aforementioned question and my answer drove me to go and do a thing while bored at work - I created a new object class called StrictInt that behaves much like the function created by the ori...
The following routine is the block-allocation procedure in a fixed-size allocator being written for library use. It is designed to be accessed from C++ (the un-mangled symbol name is void * Superblock::alloc_block()). The performance of this routine is the critical to the library; and I, with almost no prior experience...
Below is a portion of the code i have written to scrape the bikesales.com.au website for details of bikes for sales (The full code is here). This finds all the 'href' attributes on each search page and tries to request the html for each href corresponding to each bike for sale. My code works correctly, however I had to...
I'm facing the following problem: I have a row of cells. Some cells are available, some are not. Every cell is associated with a cell_id. I want to determine the length of cell. This length of a cell c is defined as the length of the chain c, c1, c2, c2, ... where c1 has the next cell_id after c, c2 has the next cell_i...
I'm pretty new to Java and programming in general and I'm doing practice problems from my textbook over the summer to try to get ahead. This is a simple program that finds the largest value in a 2D array. I'm just looking for feedback on the organization of my code as well as any improvements I can make so that I can b...
I wrote implementation of unix console program word count "wc" in Java. Please evaluate it. Is there any better solution? import java.util.ArrayList; import java.io.*; import java.util.HashMap; import java.util.Map; enum CountMode { LINES, BYTES, SYMBOLS, LONGEST_LENGTH, WORDS, DEFAULT } enum ...
I wrote a function that takes a number and finds the next palindromic number. Time complexity is currently O(n2), which is really bad. How could one make this function more efficient? function nextPalindrome(n) { // first we create a function to check if a single number is a palindrome function isPalindrome(num) {...
I'd like to make parsing small samples of data more efficient (from the developer point of view). This means, instead of writing the parsing logic each time from scratch when I encounter something as simple as Car4 or Ticket#123/22APR It'd be great to have something that I can reuse. So I was experimenting with dynamic...
I made a custom linked list implementation. I am trying to improve my coding style, any remarks or suggestions are welcome. template<typename T> class LinkedListElement { private: T *content_; LinkedListElement<T>* next_; LinkedListElement<T>* previous_; public: T* getContent() { return content_; ...
This is a thread I started from here. I organized my code to make it more organized. Everything works well, but I have not made all the changes from the last link (namely namespace since I am exactly sure why or what to do). Overall I just wanted to show my generic single linked list I made and see if there are any er...
I have created a simple tool that takes in a dictionary of cryptocurrencies and finds the ones with the highest % differences between exchanges. I would be grateful if someone could help me optimize this code and perhaps make it less complicated. The structure of the code is: for coin in data: for market in coin.m...
This is a follow up from a post I made here. I am creating a generic vector class. I have changed the code around considerably since I had so many errors (decided to just re-do it from scratch). I just want to check to see if there is additional errors I made or certain parts that I can improve or add upon this class I...
I am solving interview questions from here. Problem : Write a program to validate if the input string has redundant braces Return 0/1 : 0 --> NO 1 --> YES Input will be always a valid expression and operators allowed are only + , * , - , / Example: ((a + b)) has redundant braces so answer will be 1 (a + (a + b)) doesn...
I read the solution to this question, which seems to be the same target. My solution is (I'm sure) not the quickest, but some test case is apparently taking longer than 4s. I did a test case with 10,000 random integers and it completed in just over .33 seconds, so I'm trying to find what would result in this code hangi...
I'm working on a solution for validating Apple receipts. Here's the repository as whole. I based it mostly on the gdx-pay-server library. In my implementation, one of the classes I want to improve is AppleReceiptValidator. Some questions I have are as follows. First, should I change the System.out.println statements to...
I have the following functions for polling some function periodically with a timeout export function promiseTimeout(ms: number): Promise<NodeJS.Timer> { return new Promise<NodeJS.Timer>((resolve) => { return setTimeout(resolve, ms); }); } export function poll(predicate: () => boolean, delayMS: number, timeoutM...
GDAX is the cryptocurrency exchange owned and operated by Coinbase. This code is intended to be the basis for an order-book-strategy trading bot. I'd love feedback on my use of data structures, my concurrency handling (specifically how I'm signaling threads, and how I'm busy-waiting in a few places), how to optimize ...
The following code simulates the card game Crazy Eights. Some of the methods seem a little clunky or superfluous (although I've yet to come up with a better solution). I'm specifically referring to the convert method used in EightsCard which is called as a helper method in a number of EightsPlayer methods (play, search...
I'm using some old USA Computing Olympiad (USACO) problems to help teach me. This is the "Milking order" problem: Farmer John has \$N\$ cows (\$1≤N≤10^5\$), numbered \$1…N\$. He has made \$M\$ observations about his cows' social structure (\$1≤M≤50,000\$). Each observation is an ordered list of some of his cows, indic...
I have a number of images that were cropped and their backgrounds removed. I've tried to write a function that will search the original unmodified image for the cropped image so that I can restore the cropped image's original size and position. One confounding factor is that the cropped image has a line drawn through i...
Description: An array-based Queue class. Since this class is designed using an array the size of the Queue is limited to whatever the program gives you. MAX_SIZE is made public to let a user know about MAX_SIZE. In Constructor, frontIndex and rearIndex set to 0. A point can be raised what if front() or remove() gets c...
I've a web service class to handle all requests to the external service. All the methods are very similar, so I want to refactor this into DRY code. This is an app in Xamarin.Forms. I'm making the external api so if anything should be changed there I can. class WebService : IWebService { public WebService(IRestClie...
This is my first attempt at writing some reusable OOP code. The problem I'm trying to simplify is the confusing (at least to me) structure of VBA string manipulation. Example Dim SomeString As String SomeString = "1234abc" SomeString = UCase(Left(StrReverse("1234abc"), 3)) I've been using VBA long enough, that I get i...
I am new to Java and not quite familiar with its design patterns. I have tried to implement a CSV-File reader from scratch. The CSVFile constructor accepts the path to the file and a class which represents each datapoint (line in file). This class must implement the "fromLine" method (which accepts an array of Strings...
I have the following code that works correctly on small data-sets, but times out and crashes on large data sets. The goal of this code is to take a tabular view of data on one sheet and transform it to a vertical view. Excel crashes due to the performance issues when scaling this to 45k+ rows. The code is functional; i...
Growing more and more concerned about the real-world performance, especially the execution time, of my code (not just from the perspective of Complexity theory) I decided to build a performance metrics library to get some numbers about the execution time of code. I basically want a function which takes another function...
I am making an object-oriented python project for a smart mirror running on a raspberry pi. The code receives input from API's, formats the data and displays it on the mirror. I would like to know what I can improve on. Is my code up to industry standards? Code: from Tkinter import * import locale import threading imp...
I made a sudoku solver using backtracking in C++ and I would like to know what can I do to speed up my code. I am new to this language and I don't know all its special tricks yet! I was told to go to this website for this type of question. This is my class definition (sudoku.h) const int SIZE = 9; class sudoku { public...
I was given a homework assignment to code a console Guess the Number Game, where the user should guess a random number. Also, I had to code a simple menu with switch where I can change a random number origin/bound and attempts amount. Please, give me some tips how could I improve the code and where I'm wrong. P.S. I mu...
I've written a program that parses JSON downloaded from Facebook to calculate some stats from a conversation between two parties. It attemps to count these things: Messages grouped by day of week Amount of messages per person Messages grouped by year-month Messages grouped by month Messages grouped by distinct date Me...
I recently took a programming exam for an interview and unfortunately didn't pass it. I wasn't offered any feedback about the results. I'm looking for help on how to improve my OOP skills. The requirements for the program were: a bank has a name a bank has many accounts transactions are stored on the accounts. There ...
Given an integer $value in the range of 1, 2, 3, I want to get an array that starts with $value and proceeds with the remaining two integers from above in arbitrary order. The best I could think of was doing something like this: switch ($value) { case '1': $array = [1,2,3]; break; case '2':...
I have a function which loops over the controls on a form and checks to see if it's in a given rect, and then adds it or doesn't add it to a list<>. The parameter bContained is used to determine if we want a list of "in the rect" or "not in the rect" controls. List<Control> getControls(Control container, Rectangle rec...
On some video from CPPcon, some one said that there should be variadic overload for operator+ as it can solve allocation when there are multiple + with the containers like std::string. So I just gave it a try, but I am not seeing a major performance boost. Are there any other ways to improve this? #include <string> #in...
I have written a working implementation of a Poker card that I want to be comparable. I feel that my solution is somewhat bloated in C++, and want to ask if I should have done something different to make it more concise. #ifndef POKER_CARD_H #define POKER_CARD_H enum Value { Two, Three, Four, Five, Six, Seven, Eight, ...
I am trying to write a binary search using recursion in C on a sorted vector that we can assume comes from a uniform distribution between the start and end values. What I am trying to write is an algorithm that performs best in expected time. I am having some issue with picking the correct index to 'split' at and while...
I have built a tiny script count the word frequencies of all text files with a specified directory. I would be glad to receive any suggestions and feedback. import re, glob,os from collections import OrderedDict, Counter class CountWords: def __init__(self,dir,ext): self.dir = dir self.ext = ext ...
I am solving interview questions from here. Problem : Given an integer n, generate the nth count and say sequence. The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as one 1 or 11. 11 is read off as two 1s or 21. 21 is read off as one 2, then on...
The algorithm comes from wiki. The output from the algorithm is correct but not something that a person could (easily) understand. See the wiki link above. Each team play every other team. Optionally play every team twice and reverse home / away. Assume an even number of teams. I need to add a test for even. Please ...
This is my first real attempt at unit testing. This is an area I'm currently focused on improving. I say this because I would greatly appreciate any and every improvement! Stack code: class Stack: def __init__(self): self.items = [] self.size = 0 def is_empty(self): return not self...
Problem Statement Design a system which helps calculate the TotalCost of the items in the Cart. You will be given a list of items in the Cart with Discounts like in the example below. The list would contain either items or discounts and the sequence matters: Sample cart: $10 Book xyz, 10% Discount on all items, $20 st...
It's been nearly a year I've been working with C++ and now I am diving in Python and its libraries and frameworks. I am currently creating a website for my portfolio that gathers news articles from a wide range of news websites. I am using Django framework for web development and the Beautiful Soup library for web scra...
This is a question from GeeksForGeeks Given an array of integers, find a combination of four elements in the array whose sum is equal to a given value X. Input: First line consists of T test cases. First line of every test case consists of an integer N, denoting the number of elements in an array. Second line consists...
I have an UITableViewCell class that written in Swift. And it seems to me that I did it the wrong way. It works fine, but I want improve the code or refactor it somehow to make it look better. Any ideas will be helpful! Here is the code: class cwCell: UITableViewCell { //MARK: - Outlets @IBOutlet weak var nameLbl ...
This is a follow up to my last review request. I made three major changes: I had it fully implement ISeq and IPersistentStack, meaning it's now compatible with all of the core sequence functions. The queue now stores a custom comparator so it can be treated as a min queue, a max queue, or any other sorting method need...
I am new to learning code, and would love some feedback on how this little game could be improved and/or tidied up. import random num = random.randint(1, 100) def user_guess(): guess = input("Guess a number between 1 and 100: ") print("Your guess is", guess) guess = int(guess) while guess != num: ...
Below is code modified from the source code for python.exe. The motivation is to be able to build a suite of python applications that can be distributed with an installer, that share an isolated run-time, but run with their own executables so that they have proper taskbar integration, icons and task manager identifier...
I've written a program to get the names along with the titles of some practitioners out of a webpage. The content stored within disorganized HTML elements (at least it seemed to me) and as a result the output becomes messier. However, I've managed to get the output as it should be. The way I've written the scraper serv...
I have written the following function to process images. Now I am not sure if it's pythonic or considered as spaghetti code. I know being flat is better than nested, but I don't see a way around it. I could easily apply list comprehensions if the "if" statements are only resolving true/false, but each step depends on t...
Module 1: ;******************************************************************************* ; A generic Linked List ADT for any datatype. ; ; Author: William .386 .MODEL flat, stdcall .STACK 4096 PUBLIC push_front, print_list ; Win32 function prototy...
I am trying to find a vectorized (or more efficient) solution to an iteration problem, where the only solution I found requires row by row iteration of a DataFrame with multiple loops. The actual data file is huge, so my current solution is practically unfeasible. I included line profiler outputs at the very end, if yo...
I was writing a Python script that starts with a random string and then using Genetic Algorithm tries to find the target string. Although I have successfully implemented the algorithm but it's taking too much time to execute, even for a string of length 21 it took around 2mins. # A utility function that decide which t...
I made a small app that revolves around coloring tiles - I am a newby to Python so I am unsure whether I followed the general guidelines correct (use of functions and classes, format, syntax) You can probably figure out the functionalities of the app if you test around a little :) In order to run it, you need to paste ...
I'm currently creating a small server back-end. My goal is to write an (efficient) packet parser in C++17 using the command pattern. The packets are given by: type: value in {0, 1, 255} size: value in {0, 1, 65535} data: array[size] Each packet is processed by a packet_operator. The packet_registry is a packet_operato...
Motivated by some SO quesitons [1, 2] I made an attempt at implementing a custom container with a bi-directional custom iterator for iterating over all combinations of elements from multiple sets. I am quite unfamiliar with the topic, so any feedback on design (including naming) and performance is very appreciated. Som...
Today I had some time and tried to improve my own Bitmask adapter class. It's common practice to eliminate sets of boolean variables with something like a flag system. The old fashioned way was to create a enum and store those values in an unsigned int with some bit operations. It isn't a very complicated task, but at ...
The following piece of code averages the ante-diagonal elements of a 2d array x of size (m,n) with, for my purpose, m > n. import numpy as np def average_adiag(x): """Average antidiagonal elements of a 2d array Parameters: ----------- x : np.array 2d numpy array of size Return: ------...
I often have the need to take some type and stream it to something as a sequence of character byte values, so I came up with this to accomplish the task: #include <iostream> #include <iterator> /// This provides a way of getting the byte representation of an /// object of underlying type T. /// /// This is an alternat...
I have found the answer to the problem I am trying to solve, but I am curious if there can be any improvements made to my code. #include <iostream> #include <limits> #include <cmath> using namespace std; unsigned long pythagoreanTriplet(); int main() { cout << pythagoreanTriplet() << endl; } unsigned long pythagorean...
I have done sequential and parallel addition of 2 vectors that I have filled with some dummy values. I am also measuring the time of execution for both, sequential and parallel execution. #include <iostream> #include <vector> #include <iterator> #include <algorithm> #include <functional> #include <chrono> #include <cas...
I’m making a “counting iterator” which emulates a constant container of consecutive values of some integral type. It is mostly boilerplate, going through the list of requirements for different iterator types and making sure all the functions are there to be a bidirectional random-access iterator. That is why all the f...
I made a function that writes all the data from a hashtable to a .txt file and another to read the said data. The data comes from a this type of struct and it should be read into it when called typedef struct user{ char nick[6]; char name[26]; int n_messages; int n_following; int n_followers; h...
I'm using some old USA Computing Olympiad (USACO) problems to help teach me programming. This is the second one I've posted, I hope that's okay -- let me know if this is considered abusing the system. You can find my first post here. As noted there, I'm essentially a beginner at programming in general, so any suggesti...
I started writing a new framework in C# which can be used for any server development. It contains the basic stuff, such as database, TCP and configuration. I did write the configuration last night and I would love to get some constructive criticism and tips on it. I know I didn't document the code yet, planning on doin...
For an e-commerce web application I have written a shopping cart, and some tests for it. I have used a course on Lynda.com, on building an e-commerce website, as inspiration on how to build the shopping cart. So it shares a lot of code with the one being thought there. The shopping cart is obviously not finished, but I...
I intend to send validating message to User's email to complete a registration with the following codes: def register(request): """1. register a new user 2. generate activating code 3. send validating email 4. prompt to check activating email. """ if request.method == "GET": fo...
I used the std::chrono library for computing the timing of a function and need some review on it. Here is the code: namespace gstd { #ifdef GTIME inline namespace gtime { template<typename type, typename period> using duration = std::chrono::duration<type, period>; std::function<std::ch...
I love to post here on codereview my code to have a feedback from developers that have more experience than me, to improve my coding skills. During these days I'm working on a webapp for a small business who need to manage internally the production cycle of handmade hats. While I'm analyzing all the clients needs, I've...
This function is called by a sub that feeds it lines that the function needs to print for all the elements in an array. This function retrieves a string, line_to_print that contains a substring replace_this_keyword_0 called "replace_this_keyword_0" (sometimes occuring twice in the same string) when it is called. It als...
I am using Elasticsearch v6 and NEST to search the advertisements that I create on my website. This is my Document (from which I build the Index): [ElasticsearchType(Name = "document")] public class Document { public long Id { get; set; } [Text(Analyzer = "english")] public string Title { get; set; } ...
I've written some SASS code to generate a Pygments syntax highlighter style sheet (which are, by extension, compatible with Rouge). Such a stylesheet is normally generated by the pygmentize command-line tool from predefined styles defined in Python classes, the code below reflects the Pygments token hierarchy, recordin...
I get the coprime numbers less than n with the following algorithm: int n = 15600000; int j = n - 1; while (j > 1) { if (GCD(n, j) == 1) Console.WriteLine(j); j--; } My GCD method, which calculates the greatest common divisor of two numbers, looks like this: static int GCD(int A, int B) { if (B != 0) ...
I am new to ReactJS as a fun alternative to the old boring JS and for practicing I tried to make a sort of "tabby cat" app similar to the browser extension one (tabbycats.club) where you get a new random cat image/name/background color for every new tab or page reload. But I feel like my current code is quite messed up...
This came from this question. Find all the positive divisors of an integer >= 2. Can stop when i * i >= number. Please review for speed and style. public class IntWithDivisors { public override int GetHashCode() { return Number; } public override bool Equals(object obj) { if(obj ...
This is code that solves partial differential equations on a rectangular domain using partial differences. fd_solve takes an equation, a partially filled in output, and a tuple of the x, y, and t steps to use. eqn_parse turns a representation of an equation to a lambda equation that can be easily used. in __main__, I h...
This code is trying to find the sum of prime numbers below 2 million. The code does work as intended, but it takes a very long time ( 6 minutes) for the code to execute completely. What is the problem and how can I make it more efficient? #include <iostream> using namespace std; unsigned long summationOfPrime(); bool ...
My problem is to Determine if number n contains the same number 3 times and if yes, print it. I have presented number in array form. for this a, this algorithm prints 2 on console. My algorithm looks like this: // a = 542383272 int[] a = { 5, 4, 2, 3, 8, 3, 2, 7, 2 }; for (int i = 0; i < a.Length - 1; i++) { int c...
I'm writing a typical client-server architecture for a chat program. My goal is to make the protocol flexible so that I could add more functionality in the future. (Any good software should allow that) Both applications should be able to wait for a response from a particular request that has been sent. I'm currently us...
I have previously asked A library of books to demonstrate C++ to a C programmer and I took some of the advise from user: JDlugosz and this is what I've managed to come up with so far: My question(s) are relatively the same as in the original, however I would like to know if the changes that I've made based on some of t...
I decided to refactor my code based on this review. Eclipse: class Eclipse(): def __init__(self, eclipse_date, eclipse_type, eclipse_location): self._validate_str_parameters(eclipse_date, "Eclipse date") self._validate_str_parameters(eclipse_type, "Eclipse type") self._validate_lst_paramet...
I'm working on this challenge: Given an array of integers of size N. Assume ‘0’ as invalid number and all other as valid number. Write a program that modifies the array in such a way that if next number is valid number and is same as current number, double the current number value and replace the next number with 0. ...
I need an operator to allow a stream of booleans to act as a gate for another stream (let values pass when the gate stream is true, drop them when it's false). I would normally use Switch for this, but if the source stream is cold it will keep recreating it, which I don't want. I also want to clean up after myself, so ...
This is a function intended to take an XML element (in closure XML format) and a name and find a piece of simple data by that name (either in a tag or attribute) within that XML element. It works, but I'm still new to LISP - can it be written more elegantly? (defun find-data-inside-xml (element name) ;; Maybe there's...
For a side project I'm working on, I need to be able to generate permutations. Instead of relying on an existing library like math.combinatorics, I decided to write my own implementation, and arbitrarily decided on Heap's Algorithm. Example: (permutations [1 2 3]) => [[1 2 3] [2 1 3] [3 1 2] [1 3 2] [2 3 1] [3 2 1]] I...
I think I just made a very simple way to implement both builder patterns: Bloch builder (for solving telescoping problem). introduction@Medium, Telescoping problem@SO Go4 builder pattern (The most difficult one among those 23) Characters in Go4 builder: Director: Pizza.Maker ConcreteBuilder: Pizza.Recipe I'm also t...
This is an attempt to create interfaces holding the boilerplate code of basic JPA interactions. Code in question/review JPAInteraction.java package personal.learn.jpa.jpa_all.config; import javax.persistence.EntityManager; public interface JPAInteraction { default void close(EntityManager entityManager) { ...
I implemented a Date based on the Gregorian calendar as an exercise. I'm looking mainly for how to make it more readable and easy to test, but any feedback is welcome. public interface Date { GregorianDate addDays(final long offset); boolean isLeapYear(); int getYearDays(); DayOfWeek getDayOfWeek(); ...
Below is my code to maintain a session timeout globally in Java spring configuration and to load the session timeout value from a properties file. Do you have any suggestions to improve my code? public class MySessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionE...
After a little bit of troubleshoots, I've finished this simple users registration and login class. It uses PDO to connect to a mysql database, I've tried also to manage the session when an user do the login or logout. The main objective of this code form me was to make an exercise for using correctly the PDO and relate...
The program should (and does) the following (paraphrased assignment): There is a catalogue with a list of motorcycles. They have a - Name (spaceless string of 20 chars) - Price (int < 99 999 999) - Weight (int < 99 999 999) - Speed (int < 99 999 999) I have to output two lists, the first list is ordered...
I implemented my own LinkedHashMap in java. public class LinkedHashMap<K,V> { private Entry<K,V>[] buckets; private int capacity=4; private Entry<K,V> head; private Entry<K,V>tail; static class Entry<K,V> { K key; V value; Entry<K,V...
I have put together a CSS snippet to responsively display a Show more / Show less button if content of list cannot fit 1 line (1em) when you resize the window using pseudo-elements. Currently, I have added an ul:after element with a solid white bg to hide the Show more/less button when content does not overflow 1 line....
Three weeks ago I posted Multiplying big numbers using Karatsuba's method where I made reference to my version of the classical long multiplication. That's what I'm posting today so people can compare for themselves. At the same time I'm hoping someone still sees ways to further improve this code! The multi-precision m...
This question is NOT about passing a Comparison to a Sort. The question is how to pass a Comparison to an object for object to object (1:1) Comparison. Some users must be able to pass in a Comparison. They want 2 as want be able to tell when they give different comparison. The way this solution approaches it is t...
I'm new to refactoring and I have just refactored an old Rails project that had bloated controller methods. I spun off the bloated methods into its own separate controller following this logic, since the quiz functionality can be considered a separate resource compared to the vocab controller's responsibilities (Single...
I am working on a (personal) light weight distributed project for the Rpi platform. Making it distributed requires P2P communication between the nodes, and I thought it would be a good time to learn sockets and UDP. The end goal is to get to a point where nodes can do things like leader election, and distribute tasks ...