instruction
stringlengths
71
95.1k
Question - Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight). int hammingWeight(uint32_t n) { int count = 0; while(n>0){ count+=n&1; n>>=1; } return count; } Can you come up with a bett...
So the exercise is as follows: Try modifying Cacher to hold a hash map rather than a single value. The keys of the hash map will be the arg values that are passed in, and the values of the hash map will be the result of calling the closure on that key. Instead of looking at whether self.value directly has a S...
I am currently working on an Node based Express application. I have found Express's middlewares approach quite pleasing however, we all run in scenarios where a certain route or routes don't need a specific middleware. I have found two approaches: Adding middleware globally exempting the routes it doesn't need to run ...
I want to delete files from folder, which are not stored in DB, and DB records, which no more linked to files. My code: public async Task DeleteNonExistingImagesInFolder(string imagesDirectory) { var images = _unitOfWork.Images.AsQueryable(); DirectoryInfo d = new DirectoryInfo(i...
This is from Leetcode My solution is based on Python 3. It was faster than 90% of solutions on Leetcode, but used too much memory. Please what makes this memory hungry? How can I make this more efficient? def trap(height, bound=None): storage = 0 temp_storage = 0 left_bound = None max_left_bound = 0 ...
Challenge Problem Statement - Implement a Queue using two Stacks I implemented dequeue() in \$O(1)\$ at the cost of enqueue() in \$O(n)\$ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <stack> using namespace std; struct Queue{ stack<int> s1,s2; int dequ...
Does this code follow common best practices? I tried to keep the code simple and straight forward adding comments and spacing everything to be readable. My main concern is there a common practice that I did not apply, I am looking into a career change and want to include this in a portfolio for a jr position. I am curr...
The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 → 363...
Explanation: I am working on String comparison in which I want to cross-compare the list of the same input string. For the same string, I am continuing the loop but if a single string will have similarity greater than 90% than it should not be appended to the refined Input list. The code on which I am working is down t...
To better understand how discrete finite convolution works (read educational purposes) I wrote an all-python implementation of the convolution function. The idea was for it to give the same output as numpy.convolve, including the mode options. I generalized the code so that it functions for n-dimensional convolutions r...
https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem problem statement: Consider a matrix where each cell contains either a 1 or a 0. Any cell containing a 1 is called a filled cell. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally...
Here is my attempt to implement the Ukkonen algorithm for the Finding a Shared Motif problem on rosalind.info. The code works, it produces a correct answer. It does so in 11 seconds. I am hoping to optimize it so that it runs faster. # http://rosalind.info/problems/lcsm/ from sys import stdin # A suffix tree is a tre...
I’m trying to target three words in a h1 for the organization name using to wrap each word and a unique ID to style each word via css. It looks like this: <h1 id=“orgName”> <span> <span id=“firstWord”>The</span> <span id=“secondWord”>Community</span> <span id=“thirdWord”>Space</span> ...
I'm trying to write a code where a charged particle (charge=+20 called dimers), after a certain time, will split into a neutral particle and a smaller charged particle (charge=-10 called monomer). I split position and velocity into x,y,z component matrices along with charge and fragmentation time matrices for each spec...
We had a long HTML string with information about the makers of our software. However, for i18n this was unwieldy. So I started to refactor, so only each person's description is translateable, not all HTML tags, nor contact info. I am beginner, so probably not used the best data structure, etc. This was the code before:...
I wanted to get some feedback here on my solution, because the course I am using is not allowing me to submit any answers. Objectives: Write a Java program that: Create a grades.txt file with some grades inputted in Reads these grades from the file and stores it into an ArrayList After storing all elements into the A...
I am learning C++ and I've written a text-based classic Tetris game using OOP design. I would really appreciate it if someone could take a look at it and review the OOP design and tell me if something is particularly bad (or particularly good). I aim to make my code expressive, maintainable, with good abstraction level...
The problem quoted: https://leetcode.com/problems/single-element-in-a-sorted-array/ Given a sorted array consisting of only integers where every element appears exactly twice except for one element which appears exactly once. Find this single element that appears only once. Example 1: Input: [1,1,2,3,3,4,4,8,8] Output...
I need to have my logger middlewares (nodes of a linked-list) in the right order so that they complement each other and work as desired. Any known middleware can be inserted anytime but the first and last. They will always be there. This means I'm always starting with two of them and the other ones will have to find th...
I have written a simple singly linked list in C++. I have previously had a data structure in an interview criticised for being too C-like (no iterators and using new/delete) instead of smart pointers. For the iterator, I'm not quite sure what I should do for operator->. Should its behaviour change depending on whether ...
I wrote a Snake Game in C++ and I have practiced some OOP approaches on windows 7. What I need: advice how to improve code Most important how to made what Snake on CollisionCheck method do different "things" for example if snake eats Fruit snake will grow by one. if Snake eats self or wall .game collapse etc/ Any ide...
I've written a bunch of functions that deal with handling files on a Linux system. I'm looking for critique on the whole class, in particular: Exception handling Efficiency Style I'd also like to discuss the practice on marking all these methods as static and using a class merely as namespace. As far as I'm aware, a...
I am implementing a BVH (Bounding volume hierarchy) in Cython and thought of using a doubly linked list to hold reference of the volumes that still need to be split and push new volumes at one end while popping others on the other side in a recursive manner. But I am not sure if I got the code right, it gets confusing ...
Goal My goal is to create a TCP server/client class that can be universally reused in various private projects. It should work stable and does not need to be super fast, but rather light-weight to even work on a Raspberry Pi, for example. One TCP connection at the time would be enough for me. Question Since I am somewh...
I'm wondering if there's a more Pythonic way to keep paginating an API endpoint until there's no next key in the response. The thing that bothers me the most is the for item in json_resp.get("data") (I know this can be extracted as a function). # some code is omitted, some obfuscated # attachment of token in API calls ...
I wrote a basic tic toe game. See, https://jsfiddle.net/shai1436/Lgy1u84s/4/ I am not satisfied with the way I have designed classes and how I have implemented the undo feature. Please suggest feedback. //player0 is O and player1 is X let board; class Game { constructor() { this.player =...
I am writing a lesson-based program to help teach friends and family the basics of Arabic. The program consists of different sections (letters, numbers, personnel pronouns, etc.) and each of those sections is in turn broken into different lessons. Each section has its own .py file. All of those files are then imported ...
I'm new to C++ and trying to learn by implementing data structures in it. Is the code below the most efficient way of implementing the data structure in C++? Does it conform to C++ standards, and how readable is it? #include <iostream> class Node { public: int data; Node *next; Node(int data) { ...
If you don't know what is Schelling's model of segregation, you can read it here. The Schelling model of segregation is an agent-based model that illustrates how individual tendencies regarding neighbors can lead to segregation. In the Schelling model, agents occupy cells of rectangular space. A cell can be occupied ...
This is a Haskell implementation of Conway's Game of Life. It plays on a console. It should be able to play a field of any size, but we only give it a glider on a small field to run at this point. Using a file named GameOfLife.hs: import Control.Concurrent import Text.Printf main :: IO () main = gameOfLife ( [ [0, 1...
Algorithm Bubble sort, also known as sinking sort, is a sorting algorithm that repeatedly steps through a list, compares adjacent pairs and swaps them if they are not in the right order. The pass through the list is repeated, until the sorting is complete. The algorithm, which is a comparison sort, is named for the way...
My logging adapter is using a dictionary for storing data that is passed from middleware to middleware. It is a one-liner: public class Log : Dictionary<SoftString, object> {} Since it's using SoftString (like string but case-insensitive and trimmed) for the key and there are also two different types of data there, ...
What I'd like to do is read data from a stream (like ifstream::read), but reserve N = 4 bytes from being returned. The last 4 bytes of the stream are not part of the data itself, but are metadata. In the general case, the stream is not an ifstream so I won't be able to seek, putback, or determine the size of the stream...
I created a react-auto-height library: A React component that animates height: auto children when their content is changed, using CSS transitions. It started simple, inspired by a CSS-Tricks article, but I needed to cover more edge cases, most notably to allow multiple levels of components to use <AutoHeight> without...
I have a bunch of voxel having an int value inside a 16^3 grid. I want to merge individual voxels with the same int value together in order to create the least possible amount of boxes the fastest way possible. Here is my algorithm (kotlin) : fun convert (grid: VoxelGrid): List<Box> { val dim = grid.dimension ...
The code below simulates a given Newtonian 3 body system. Each row per slice is supposed to represent a Cartesian component for the initial trajectory vector and for the distance vectors to the other two objects. What are some possible improvements to this? For instance is there any benefit to implement something to c...
Below is an implementation of a React app printing list. Are there any areas of improvement/suggestions in below code base class ListElement extends React.PureComponent { render() { return <li onClick={() => this.props.handleClick(this.props.index)}>{this.props.item.text}</li>; } } class ListComponent e...
I have the following code, which basically load some data files that I have in different folders, take an average of every repeat at each Temperature and then plot the results. The code works fine, and it was OK when I had only a couple of set of data. But now I have 9 different set of temperature each with 5 repeat ea...
I have below working code which works fine, but just looking way around if there is an another elegant way of doing this, because here i'm using else condition to print the last line or dataBlock to be printed. Note: mydudalt1 and mydudalt2 are the host names My data File: $ cat mydata_test.txt -- mydudalt1 -- ...
MemoryCache.cs public class MemoryCache<TKey, TValue> { private static readonly object Lock = new object(); private static readonly IDictionary<TKey, TValue> Cache = new ConcurrentDictionary<TKey, TValue>(); /// <summary> /// Function for setting the cache's value when the key isn't found. /// </su...
This is a follow-up from my previous question. In summary, I am trying to implement a BVH module with Cython and need a way to keep track of the volumes during the construction of the hierarchy. I was going to use a Doubly linked list for that purpose as it allows for efficiently inserting and popping items from either...
How can I improve the date format function. I have written in javascript (ES5/ES6)? This code is just a part of an exercise. function formatDate() { let bookingDate = new Date(); let dayNumber = bookingDate.getDay(); let date = bookingDate.getDate(); let month = bookingDate.getMonth(); ...
Problem Statement Given the root of a binary tree, return a deepest node. For example, in the following tree, return d. a / \ b c / d My Implementation module.exports = { deepestNode: function deepestNode(node, level) { if (!level) level = 0; node.depth = level; if...
I am looking for any refactoring tips to improve code readability. Does it feel like procedural programming? If so, how can I improve it? public class StatementJob implements Job { private static final Logger LOGGER = LoggerFactory.getLogger(StatementJob.class); private static final String JOB_IS_DISABLED = "U...
My application needs to let the user select a folder from somewhere on their local machine. Below are the interface and model pair that I have written to let the user do so. public interface IFolderPicker { // Methods // ======= string Show(); } using Microsoft.WindowsAPICodePack.Dialogs; using WinForms...
I have written this function is part of a research project that involves analyzing time-series data from stochastic processes. We have a small number (from 1 to 3) of independent observations of a scalar time-series. The observations have different lengths, and each contain about \$10^4-10^5\$ data points. The function...
Recently I've been developing a chess game in Python - using pygame - just as a project for myself. I have a class for each piece type, and in each class, I have a method called find_available_moves which returns an array representing the board showing where the piece is legally allowed to move. I've accomplished this,...
I am currently working through learning C++'s variadic templates and I wanted to create an example use of them that is less trivial than the one in my book. I decided to create a modification of printf's interface where the type of each argument does not need to be specified. Here is an example: print(std::cout, "Welco...
Can you please suggest how below code can be optimize? It takes around 2 minutes in Windows and 4 plus minutes in Excel 2016 for Mac. I think I will have to use write once method, accumulating the inserts and write all at last but I am not getting the starting point. There are initially 5718 rows and after the inserts ...
I have two dataframes: One contains of name and year. **name** **year** ram 1873 rob 1900 Second contains names and texts. **name** **text** ram A good kid ram He was born on 1873 rob He is tall rob He is 12 yrs old rob His father died at 1900 I want to find the indices of the ...
This code is a solution for CodeChef's Tree MEX problem: Minimum excludant (or MEX for short) of a collection of integers is the smallest non-negative integer not present in the set. You have a tree \$ T \$ with \$n\$ vertices. Consider an ordering \$ P=(v_1,\ldots,v_n) \$ of vertices of \$T\$. We construct a seq...
I took quite some time to implement a fully standard-conforming std::optional in C++17. It turns out more sophisticated than I initially thought. My code is just below 1000 lines (excluding empty lines), and I have tested the functions extensively. There have been some attempts to implement std::optional on Code Revi...
I've implemented Goal Oriented Action Planning (GOAP) in Kotlin. Goal Oriented Action Planning is an algorithm originally devised by J Orkin for the game F.E.A.R. and performs a state space search using A* in order to formulate a plan of actions to get from an initial state to a goal state. I've commented the code comp...
I was actually kind of bored and since I'm studying some Python data structures I decided to make some size(MB) and time(secs) comparisons between different containers when conducting the operation of adding n items to each container type. I included: List appending List initialization List comprehensions Array Set co...
Which of the 2 solutions is written better? Personally I prefer the one line method but it does make it slightly more difficult to debug. Is perhaps doing it the long way first then refactoring to the second method once we know all is tested to be working. Please note Environment var "FT_SOURCE" is set to "c:\filemove...
The cofactor of a 4×4 matrix can be used to convert a "regular geometry" matrix into the matrix that transforms the normals. It's an alternative to the common inverse-transpose pattern. In this post I use row-major matrixes. Here is reference scalar code from https://github.com/graphitemaster/normals_revisited float m...
I've created a simulator for the Premier League, which takes in all of the 20 teams and plays them against each other, recording the results and outputting a table at the end. The skill levels are based off a prediction in an article by The Telegraph. I am wondering whether or not my code can be improved, condensed or ...
Basically I'm looking for a way to improve my code, and avoid making a lot of if statements and parameter combination manually, 'cause I need to return a query result depending in the parameters that were sent. I've read some posts, and tried some stuffs but nothing that works. For each if statement and param's combina...
I have some question because in my project I have 4 models, and one of models is parent for other 3 and they are connected to parent by foreign key. Then I have view which is used for automatically fill form of those models and save them in database, this is post function in my view: def post(self, request, *args, ...
I currently have a class that I want to serialize/deserialize messages sent to this socket. My plan was to use Task.WhenAny() to monitor 2 tasks (Either watch something that needs to be written, or read from the stream). If I have a message waiting to be sent, it would write it to the stream, otherwise it would attempt...
I built this scraper for work that will take a csv list of firewalls from our network management system and scan a given list of HTTPS ports to see if the firewalls are accepting web requests on the management ports. I originally built this in powershell, but decided to rebuild it in python for the learning experience....
I just want to gather some feedback about this container, in my view it solves the problem of common data containers which don't have fast access and fast deletion. I want to admit that I have not benchmark this, as I don't understand how to do it and to compare with other containers. I tested it and it works, although...
Below is a delete job to delete 1M+ records daily and takes 13 hours to complete and sometimes more than that. I need to optimize this. The table tblcalldatastore is being inserted 24*7 through a stored procedure and is supposed to have no records older than 24 hours. Execution plan is below. https://www.brentozar...
Given \$w, h, \alpha\$ for a rectangle centered at origin with width \$w\$, height \$h\$ and itself rotated by \$\alpha\$ around origin clockwise, I wrote a code to find the intersection area. First I find all 4 corners of original and rotated rectangle, along with lines joining them. Then I find intersection with ax...
I'm working on a library that, in essence, splits a string at whitespace, with extra rules: Consecutive whitespace is collapsed, and trimmed at the start and end. Whitespace wrapped in quotes is not collapsed or split. Backslash escaping can be used to include a single quote or whitespace character (or any other chara...
I don't like the way my code is written, but at the moment, I don't see, how I should do it better. I have a class (let's say MyInvoiceType), which needs to save data to preexisting database. The database is now mapped with SqlAlchemy (initially was just created via SQL interface). I would have certain Table classes ma...
As part of an android app, I've written a simple wrapper that makes requests to an api and fetches stuff. import android.app.Activity import android.util.Log import android.widget.Toast import com.github.kittinunf.fuel.core.Parameters import com.github.kittinunf.fuel.httpGet import com.github.kittinunf.fuel.json.respo...
I am working with a spreadsheet containing a bunch of 'sections', e.g where the 'URL' column is set to 'google.com/search' in A1, and left empty while a bunch of things related to that URL are done in other columns (let's say we extract all of the tags, and list them). As this all applies to the same URL, there's no n...
I am an OOP programmer by trade (Java) who is extremely new to Haskell and the world of purely functional languages. To get my feet wet, I decided to try and write a little musical interval translator/calculator. I am immediately impressed with this language. The power of this allowed me to quickly define an algebra ca...
I have many pieces of HTML code that are used in many parts of the website (controlled by javascript), like edit forms and dialogs. Instead of include-ing the html files using php, I made a system for storing these elements in a javascript variable array such that I can choose which files to include in each page and wh...
I was recently working on some python where I was working with multiple inheritance and mixins and stuff like that, and I wanted to inherit docstrings for specific functions, from specific parents (particularly in the case of the mixins). Anyways, I came up with this recipe for inheriting docstrings and was hoping for...
I've written a python program do perform synthetic division on a polynomial. There are a few constraints (listed in the module docstring of the program) on the polynomial, mainly because I haven't had the time to work out all the edge cases. I would like feedback on everything possible, as I plan to use this to solve o...
I want to refactor this in Java to reduce my code duplication. public HashMap<String,String> setupProductsUid() throws Exception { OutputMessage actual = statusUpdaterTest.getOutputMessageWithUidOfNewProductsNode(); HashMap<String,String> map = new HashMap<>(); map.put("replaceThisProductsUid", actual.getQu...
Problem: String to integer(leetcode) Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numeri...
I have to print the number of stars that increases on each line from the minimum number until it reaches the maximum number, and then decreases until it goes back to the minimum number. After printing out the lines of stars, it should also print the total number of stars printed. I have tried using shell scripting and ...
I have two methods in my code which are using the majority of the CPU time that convert between binary and hex strings and the reverse. I use a static lookup map to convert the individual characters but it's still slow given the amount of data I'm working with. public static String hexToBin(String s) { StringB...
The problem of 3sum is described as: Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Here is my code, am I right to say its complexity is O(N2), and how can I further optimize my code? Here I am using Has...
I have a query I am writing where I want output if a person has some service provided, then I want all the services they had provided after that and I don't want the individual returned if that is the only service they had (the criteria service) I have some example data: In this instance above I would not want the las...
I'm learning Rust at the moment, I've read the book and been just playing around with the language. I wrote this simple Brainfuck interpreter, because I think that it's always a fun exercise. The interpreter uses a tape size of 30000 and cell size of one byte. Decrementing a cell's value under 0 will wrap it to 255 and...
This code aims to make very easy to train new models in SageMaker and quickly decide whether a new feature should be introduced in our model or not, getting metrics (recall, accuracy and so on) for a model with and without certain variable, or simply make quick experiments. My specific case is a fraud detection model. ...
My C++ code accomplishes the following: It consists of a class called ParticleGenerator which has three important configuration options: spatialGeneratorType, angularGeneratorType and energyGeneratorType. The user would choose a value for each of these options from the possible values. I am trying to make my code as ti...
I'm working on a webapp and I'm using js/php (php and jquery latest versions). Is there anything I should do to improve security? I'm not super worried about safety as the current users are using a very buggy (pretty much every exploit works) and outdated (php 4) platform and never attempted anything. But better be saf...
I have a Feather M0 basic paired with a OLED FeatherWing. I am making an instructions page but the code is quite repetitive. How can I make my code shorter? import board from busio import I2C from adafruit_ssd1306 import SSD1306_I2C from time import sleep from digitalio import DigitalInOut, Direction, Pull i2c = I2C(b...
A hashmap is a data structure that implements an associative array abstract data type using keys and values and has a hash function to compute an index into an array, from which the desired value can be set and get [reference]. Based on some tutorial, I wrote this hashmap class: class HashMap(): def __init__(self)...
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversio...
I'm trying to write a constructor function that generates instances of a user. One of the properties of the user class is an array of the user's hobbies. I'd like my constructor to have a method that generates a string representation of the array of hobbies provided to the constructor function. The goal is to create a ...
I had the need to prefix the price for certain product categories on only the shop page (because the price can be higher depending on extras that the customer might want). These were my requirements for this code: Add the prefix only on the shop page, not on the product page; Only add the prefix to certain (hardcoded)...
I have an Android project that queries the BART train API. I was curious if updating the UI inside the Retrofit onResponse method is correct or if there is a better way. Below is my code. Also, here is the GitHub link if you want to look at a different file. If there are any other issues you see please let me know. I w...
I've written a small program that calculates Arithmetic and Geometric Partial Sums. I'd like feedback on anything possible, since I intend on writing a cheatsheet that encapsulates all PreCalculus equations. partial_sum.py """ This is a program that calculates arithmetic and geometric partial sums """ from fractions ...
I have implemented selection sort in java using arraylist. This selection sort is only for integers . Please have a look and give feedback. can we improve it ? package selectionSort; import java.util.ArrayList; import java.util.Scanner; public class SelectionSort { private ArrayList<Integer> num_sort=new ArrayList<>(...
I have written a filter that intercepts http calls and logs request parameters. public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpS...
I wrote a general purpose file compression program out of curiosity, but I am concerned about readability. I don't know if the variable names are useful, and whether most of the comments are unneeded or not, so any advice/criticism is welcome. You can check the repo, for more information. const.h #ifndef CONST_GUARD ...
I would like to merge two double arrays and remove from the result array approximately equal items. My two input arrays have length up to 100000 and are sorted. Them self they don't contain approximately equal items. What are approximately equal items, see System.Double documentation and there the example IsApproximate...
I have a requirement to implement this simple table from one of the DVB S2X standards. The table is relatively small that contains no more than 28 rows. I need to use the key for the table as the second column from the structure below i.e. the kbch value. typedef struct __attribute__((packed)) { float ldpcCodeId; ...
The idea here is that we have some resource that is relatively very expensive to generate, but once we have a bunch of them in a pool, we can keep reusing them instead of generating new ones. "HTTP connections" would be an example. In my particular use-case, it's "2048-bit RSA keys" (let's pass over the obligatory what...
I have the following challenge problem for which I was able to get a solution working, but not in \$O(1)\$ time as the problem asks for. Could someone point me in the right direction to optimize this? I am also open to other criticisms of my coding style. QUESTION: Implement an LRU (Least Recently Used) cache. It sh...
I want to differentiate between comments I make for (1) myself, (2) team members, (3) on business rules, (4) on watchout notes for hardcoded constants, (5) on ideas for improvements, and (6) on general flow of the code. Right now all my comments look the same. I'm open to any other tools. I don't know how bookmarkin...
I wrote a server-client application in Python where the server sends a never-ending stream of messages to connecting clients. I was in need for such an architecture since I want to retrieve and process data from a public streaming endpoint, however the company limits the number of active connections to one per user. ...
I am creating an iOS game with In-App purchases for "Coins" and I wish to prevent (or make it very difficult) for the user to simply edit the save-game file and increase the number of "Coins" without paying for them. I am only concerned with non-jailbroken devices. I have created a GameData class that roughly follows t...
This is my take on the first challenge on the cryptopals crypto challenges list. I think that i made it quite simple but i feel like it is possible to optimize it further. Any suggestion? The code: import qualified Data.HashMap.Strict as HM import qualified Data.IntMap.Strict as IM import Data.Maybe import Data.Char (...