instruction
stringlengths
71
71.9k
I am looking for a way to optimize this code so that it runs faster. I am trying to calculate the total items used, if for every x items used, you get one additional item to use. This is the code I currently have. I get the correct result, but with a large amount of items, it is taking too long to calculate. public s...
This is a problem that I had in mind for a loong time and today I decided to give it a go, the basic idea is you enter a number/sum and the program outputs all the possible ways this sum can be formed let's say we have 3 as input the output will be (1, 1, 1),(1, 2) I don't think that the code is really efficient so any...
I am just beginning to learn JavaScript and although I feel I am starting to grasp the language, I don't feel I know how to structure an app properly. I decided to start small and build a "TODO"-app using a modular pattern. I am aware that I should use more validations, there are unused functions, and there may be a m...
let deltaF: TransformBlock = { f in let transformation = (f > pow((6.0/29.0), 3.0)) ? pow(f, 1.0/3.0) : (1/3) * pow((29.0/6.0), 2.0) * f + 4/29.0 return (transformation) } Says here that this expression is too complex to be solved in reasonable time. Is there any way to simplify it? This code is m...
Note: Since my time has passed for this challenge, I do not remember exactly the stipulations but will attempt to recapitulate them to the best of my knowledge. Essentially, the challenge was this: Given a list (from 1 to 2000 elements) of random integers (from 1 to 999999) write a function, answer(l) that accepts a l...
I'm intern and work on a project where I develop DRF API that need to interact with mobile app written by my colleague with Ionic framework. We are creating new user. My view method is following: class NewUser(generics.CreateAPIView): model = User permission_classes = [permissions.AllowAny] serializer_clas...
I have written a simple window event capture wrapper that gets events that happen to the window, and can be checked anywhere in the program through a global class. I wanted to be able to create a callback anywhere in the program with any event that I have asked to be checked. To hold the data that is returned from the ...
My use case is to dispatch multiple long-running tasks to execute concurrently. The expectation is that the tasks will be IO-bound (e.g. network requests), but importantly each task is different. This is not a question about data parallelism. I've written a simple pool type that wraps a sync.WaitGroup and collects any ...
Below are two examples of arrays (with a special ordering with odd numbers on one side, and even number on the other side) I have, with some given len: 9 7 5 3 1 2 4 6 8 11 9 7 5 3 1 2 4 6 8 10 For some value z, I want to find the column the value is in. MATLAB code I wrote: if z == 1 column = ce...
The problem here , requires me to find the best possible combination of values in an array which is nearest to 0 and are adjacent to each other , here is an little excerpt from it, The government of Siruseri has just commissioned one of the longest and most modern railway routes in the world. This route runs the e...
Sadly enough I have a bit of code that is really slow and being a newbie in programmation, I don't have the faintest clue on how to optimize. Is there any way to make those calculations faster? This code calculates the worst case of some parameters cycling through AktBeam and FileCounter (those cycles contain a LOT of ...
I'm new to Android programming and this is my first project so I'm not sure if this is the correct method of rendering the toolbar or the navigation of the drawer on the screen: So I have a BaseActivity class that has the methods displayToolbar() and displayDrawer() to display the ToolBar and the Navigation Drawer resp...
I’m new to Java programming and uncertain if I used the right approach to solve my job. This little program uses the iText library to split one big PDF into smaller documents. The trigger for this is a text on every page in a specific region (found with a RegionTextRenderFilter). In all the smaller documents I also ha...
Here is my case I made list of items when I click at any item it should navigate to certain activity. Here is my I am done First I set number of constants to distinguish between each activity // constants to show activities onclick event private static final int LOC = 0, SERVICES = 1, PRE_APPROVE = 2, CLAIMS = 3, BENE...
I'm trying to catch WPF using MVVM pattern, where my set of models is implementing ObservableCollection as well as Entity Framework's DbContext. My project is quite simple movies database (looking for movies on disc, getting info about these movies from web, and so on...). I will be glad for any notes and recommendati...
With a few experience of python and golang, I tried to make (simple) thread pool executor. Tasks of the executor must be copy-constructible std::function<void()> and the result of tasks are required in the main thread. My Header and Implementation File: #include <iostream> #include <queue> #include <chrono> #include <...
I have an array that I am shifting by a certain number of spaces. I am wondering if there is an better way to do the shift with less touches. Here is my code function rotate_array(array, shift){ if(array.length -1 <= shift){ shift %= array.length; } for(var i =0; i < shift; i++){ var firs...
This code is intended to choose the best poker hand of five out of a set of cards. The cards are represented by a list of strings, where each string contains the rank and suit (e.g., 'AC' represents an ace of clubs). The code also handles numerical ranks for the face cards, so the string could also be '14C' for ace of ...
Although TI-83/84 calculators support multiple data types, such as real numbers, complex numbers, 1D and 2D lists, fuctions, etc., there is no data type for vectors. This program is my attempt to take the sequence three sequence functions (u v w), which are rarely used for their intended function, and transform them i...
I've created a "simple" function that receives a MySQLi resource and, using a custom where query, will fetch random IDs from a provided table. Some caveats on this: No object-style! This needs to be understood by people who only know the old mysql_* procedural API; No order by rand()! It is slow, but very tempting; It...
I'm a novice C++ coder, taking my first class this semester, and we have a project coming up. I get the program done early and it works as expected, but I don't know if it's too messy and can be cleaned up. It's a simple ATM program that allows you to create multiple accounts and withdraw or deposit money in them. Any ...
I have an assignment where I need to find out if any of the meetings in a list of meeting class object have overlapping datetime ranges. What I have so far is this: public class Meeting { public DateTime Start { get; private set; } public DateTime End { get; private set; } public Meeting(DateTime start, Da...
Why will this code work for a smaller multiple like 10 but time out for anything over 13? Can this code be revised to work for larger numbers? (I have an alternate solution but wanted to see if this code could be fixed to work for more multiples.) #2520 is the smallest number that can be divided by each of the numbers...
I decided to make a simple tic-tac-toe game in C++ as a small project. All help and suggestions are greatly appreciated! main.cpp: #include <iostream> #include <string> #include "TicTacToe.hpp" TicTacToe game; void turnPlayer1(); void turnPlayer2(); bool gameOver = false; int main() { std::cout << "**************...
In the SplashActivity of my Android Application, the following sequence of events occur: Check if Google Play Services is installed If Google Play Services are available, start the InstanceIDListener service Check if app needs to be updated Load country info using network IP Previously, I'd implemented this logic usi...
I have the following class structure: public class CustomDAOImpl implements CustomDAO { public List<Organization> getOrganizations() { List<Organization> results = new ArrayList<Organization>(); Client client = ClientHelper.createClient(); Resources<OrganizationResource> response = clie...
I wanted to restart the big-float project I had paused the moment I suddenly realized that the implementation of the main four rounding modes (which I postponed so long, that I got all of the IEEE-754 functions implemented in the meantime) needs three guard bits. And it needs them from the beginning. Which needs a comp...
SmallVector is almost same as std::vector except it keeps its data inside a large array. Similar to std::array, its size can not get bigger than the SIZE parameter. However, unlike std::array it may hold less than SIZE elements. I try to made it constexpr, but it is not really possible, because push_back need to throw ...
I made a program in C++ where it calculates the distance between two coordinates. Is there anything to improve? Add? Make it more user-friendly? Code: #include <iostream> #include <cmath> using namespace std; int ch; double x; double y; double a; double b; double answer; double distanceBetweenTwoPoints(double x...
I want to create a shopping cart project with discounts for products. For instance, if you buy 2 books, you can get 10% off Parker pens. I created a shopping cart example, but without exception handling in this version. Are my classes Product, Basket, Offers and Discounts properly structured, or what changes do I need ...
I found this question online as an example from a technical interview and it seems to be a flawed question in many ways. It made me curious how I would answer it. So, If you were on a technical Python interview and asked to do the following: Write an algorithm that receives a dictionary, converts it to a GET string, ...
A little bit of background; I'm a high school student in my junior year and I attended a tech competition last year when I enrolled in my high school's CS I course. Below is what I submitted to the competition and even though I won in my category, I remember the judges telling me that I could do better by implementing ...
I have n indexed socks, each of which has one of k colors. I also have a list that states which two socks I must wear at each of m days. Of course I want always wear same color socks. But unfortunately I must follow the list. What I can do is to re-color some socks. The paint is expensive so I want to re-color the leas...
I got bored and decided to write my own function to verify if a string contains another string. I was wondering if there's any major difference between these two function except the one I wrote being more complicated. bool Contains(string str, string find){ for (int i = 0; i < str.length() - (find.length()-1); i++)...
This is a program I made to practice using turtle graphics. I am looking for pointers specifically on how I handle the game board. Currently it holds all of the grid objects in a nested list. Sorry if the documentation in the program is unconventional. This is one of my first projects and I'm excited to see what I can ...
Input: The first line contains the number of vertices \$n\$. The second line contains \$n\$ integer numbers from the range \$\left[−1, n − 1\right]\$ representing the \$0\$-based index of the parent for each vertex. An index of \$-1\$ designates that vertex as a root without a parent. It is guaranteed that there i...
I have a method that retrieves information relating to a Contact that was made between two Companies. I am looking to improve my code in any way and am intrigued in hearing any recommendations you may have on how this method can be improved. I use it throughout my program but modify it according to the DataModel I am a...
Brief summary: The vanilla GoF visitor is great for altering items within a tree of elements, but when the visitor visits an element it can only change the children of that element not the element itself. For example, a visitor altering the DOM of a webpage could search for everything that contains an image and replace...
In the old days when C was the predominant language under the hood and STL/templates were Alex Stepanov's dream, in order for programmers to achieve generality for functions and data-containers, the void* was used as input argument or underlying container type respectively. A typical example is qsort which is located i...
I am currently reading Michael Kerrisk's book, The Linux Programming Interface. This is one of the exercises from the end of chapter 4 (I'm working in Rust, not C). A Rust implementation of the tee program on UNIX systems. According to it's man page The tee utility copies standard input to standard output, making a co...
I'm working through a course now, and was tasked with the following: Write a function, no_repeats(year_start, year_end), which takes a range of years and outputs those years which do not have any repeated digits. You should probably write a helper function, no_repeat?(year) which returns true/false if a single year do...
I am trying to solve the scenario involving 1 producer and 5 consumers. The producer puts data to queue and waits till all consumers have finished before adding more data. Please review and let me know if there is room for improvement. import java.util.LinkedList; import java.util.Queue; public class ReadUpdate { ...
I am coding on codingame.com, where one of the 'easy' challenges is to assign MIME type strings to input strings of file names based on their extensions. My code passes four out of five of the test cases, and the last one is an optimization test. A big data set is inputted, and my approach times out. I started coding ...
The program below basically reads configuration data from an .ini file in ini format. The exemplary configuration file was also added to this post . Let me know how I can improve it, please. using Sahara.Core.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Syste...
I need to organize the following objects in a array applying the following rules: Group all object by source In each group order them by order property Rewrite each order property keeping their order starting from 0 I have drafted an initial solution below, the final result is present in the code comment and the scri...
For playing a Poker tournament, I wanted to create an application which should calculate the pot and the money of all players at every time. PokerBank class: public class PokerBank { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("---------------Spiel...
I have a program where users can add integers to a list and then I want to check the list to see if any three consecutive integers in the list sum to a specified value. I have been told that it is taking too long when ran with a large number of integers in the list. The timing test that I am not passing is based upon l...
I created a script to import several CSV files from various sources and one CSV file with a list of systems in it. the script searches each CSV file to see if the system exist in the file and if it does then write the property information to a variable. The challenge that I have ran into is there are 26,000 systems to ...
There are good penetration testing tools in the market in which we can perform various activities gather information from the hosts effectively. But those tools are not helpful always like if we are using some public computers we need administrative rights to install wireshark,social engineering toolkit etc., and at th...
Is there a more efficient/performant way to accomplish this with vanilla js (no libs please) as the looping is slow? Also, how can I make it more flexible, so the HTML option values can vary a little, if need be? I need to cover different option values in HTML but they mostly follow the same format. Here are some other...
This is implementation of a Datepicker by our outsource colleagues. I want to get an objective criticism of code style and approaches used. I see: Global variables with popular names Styles inside JS Not allowed attributes like cellpadding Please help me find other problems. I believe that this code is not ready for...
I have a Product entity and a ProductCategory entity. Given the Product entity, my application checks the database via a repository to see if the ProductCategory already exists. If the category is not found in the database, then the application should persist it. Currently, I have this code in the service layer as foll...
Over the past year I've found myself moving from back-end development to something more akin to full-stack development. I've created the following jQuery plugin as a test of my hopefully-not-so-fledgling JavaScript/jQuery skills. The plugin is used to inject <option> tags into the element(s) specified, and should follo...
I was inspired by a solution in Think Python: How to Think Like a Computer Scientist. I structured mine (into two functions) according to it, and used the technique used in rotate_letter. It's here if you're interested. How can I make this better in all aspects (documentation, algorithm, variable names, and etc.)? Is m...
I'm working on a parser library for substituting strings in dictionaries, with things like globals etc. Wanting to get opinions on the direction I'm taking and where I can improve the script. This currently works class DictParser(object): def __init__(self, dictionary): self.working_dict = dictionary d...
The Koch snowflake is a well known fractal. Beginning with an equilateral triangle, a smaller equilateral triangle is placed halfway along each edge of the shape. This process then repeats on each edge of the new shape. Here is my attempt to plot this in MATLAB. clc, clearvars, close all; length = 1; % Original side ...
Update: git repo: https://github.com/muhsinali/picture-example-minified This is my first project that I've written using Scala and the Play framework. It's a simple application that allows the user to store pictures and see them (no edit/delete functionality, just to keep the code review simple). I have included a coup...
Here is the task from a beginner's course: Write a method that takes an array of numbers. If a pair of numbers in the array sums to zero, return the positions of those two numbers. If no pair of numbers sums to zero, return nil. This model solution does not use idiomatic Ruby, because at that point in the course, we...
We have a JavaScript function declaration as such: function itemIncludesTotal(item){ var includeItem = false; if (item.lineItem.hasOwnProperty("details") && item.lineItem.details.hasOwnProperty("total") && item.lineItem.details["total"] && !item.lineItem.restricted ){ includeItem = t...
I've decided to learn a bit of C++, and so I've started with a simple linked list. There's no input to the program and should always output hlo. This is as in main I build a list consisting of hello, and use Get and last to get the data. I don't know C++, or C, and so this is mostly a stab in the dark. I don't know if ...
The task: Write a method that takes in a number and returns true if it is a power of 2. Otherwise, return false. You may want to use the % modulo operation. 5 % 2 returns the remainder when dividing 5 by 2; therefore, 5 % 2 == 1. In the case of 6 % 2, since 2 evenly divides 6 with no remainder, 6 % 2 == 0." Model sol...
The task: Write a method that takes in a string. Your method should return the most common letter in the array, and a count of how many times it appears. Model solution: def most_common_letter(string) most_common_letter = nil most_common_letter_count = nil idx1 = 0 while idx1 < string.length letter ...
I just had an interview for the C#.NET developer position and I was asked to find the first non repetitive char in a given string without using any library functions but just the basic constructs of the language such as fors and ifs. I presented this solution considering the quick time constraint. I request evaluation ...
I wrote this code to check the even numbers from the List. After finding even number I twice the even numbers with the help of Map and then find the sum of each even number after making it double by use of the reduce method. import java.util.Arrays; import java.util.List; public static void main(String[] args) { List<...
This is my first attempt at creating a simple Python tool that tracks the time of certain activities retrieved from a database. After stopping the timer, this tool writes the duration of the activity into the database. Can you please provide me some tricks to make this code more Pythonic? objects.py #!/usr/bin/env pyth...
I'm processing a list of files, and want to check the filenames against a list of regex, like: IGNORE_FILES = [ re.compile('^./Vendor.*'), re.compile('^./Pods.*'), … ] def in_blacklist(file): return len(list(filter(lambda r: r.match(file) != None, IGNORE_FILES))) > 0 def in_whitelist(file): retur...
I want to set flags which are given in string representation in any order. And it is intimidating, because you have to check like 2^3 possible options in my occassion. I was just wondering is there any better way to do that than just simple brute-force. Any optimization and readability improvment would be great. This i...
There are some things that smell about this code, for instance multiple checking, length both returning value and changing some other variable. But I can't for the moment figure how to make it nicer, or if that's even possible. Converting it to stack-based solution seems to be making it a bit too-complicated. Please pr...
My task is to select items from a pool to match a specific selection criteria in a browser game. My Problem: Usually my algorithm can find the desired results after 200–400 iterations. But every once in a while it does not find a result even after 1 000 000 iterations. I would be very happy to receive optimizations or ...
The requirement: search a string in a text-string (from DB) and show additional info around when presenting the result. Examples: text string = "The Quick Brown Fox Jumps Over the Lazy Dog" search ==> result: "The" ==> "The Quick ..." "Quick" ==> "The Quick Brown ..." "Brown" ==> "... Quick Brown Fox ..." "Lazy" ==> ...
I just started learning C, and got to the "for loops"—where an exercise is given to convert Celsius to Fahrenheit ( from -50 to 1000 with a step of 20 ), and print the values. I decided to play with it by adding different steps when certain values are reached. I do have some programming experience ( Python/Java/JavaScr...
As a part of a console utilities module, I created a function that takes a table in the form of an array of arrays, and generates an ASCII table with the given contents. I've also added the options of adding a header, determining the in-cell alignment, and adding a border to the table. Table cells have auto computed l...
I have 3 ToolBars that I use across my whole application The first one is just a ToolBar with a close button. The second one is a ToolBar with a close and delete icon. The third one is a ToolBar with a close and home icon. Here is my case, I use this ToolBar in many places, and I dont want to use Fragment for some rea...
So I just experimented with some code to make a huge if-else construct more human readable, extendable and configurable (switch positions of conditions). The idea was to have a vector that contains all conditions and their actions and then just iterate over the vector, executing their ConditionalAction. I solved it wit...
I have a set of functions to run according to combined options. Options are easier/harder, add/multiply, wait/nowait, 1/-1. You can see the whole module here. For now I have put all functions in an object to be able to access them according to the options. For instance: var stair = { down: 3, sameStairCount: 0, s...
I have a map of cars Map<String, Set<Car>> which can be returned by getCarsMap() method where key is model of car , and value is list of cars of same model. I would like to improve Car addCar(Car car) function. For now I wrote this a bit ugly piece of code. public Car addCar(Car car) { if(getCarsMap().entrySet().stream...
This basic function to detect negation while performing sentiment analysis. So that not good kind of words can be considered a negative. This code is working fine. Can someone help to improve it or find if any bug present? def negate_sequence(self,text): """ Detects negations and transforms negated words into "...
Is it normal to catch exception in concept of MVVM inside model? Or how should it be? How to improve this code? This is simple application that allows user to drop .pfx certificate on the label. LoginModel checks the password for validity and check the publisher. if the validation fails throws an exception that is catc...
The original task was to find the first non-repetitive character in a string. Every now and then I read questions here on Code Review and try answering them myself, and as such I stumbled upon this one. Now, I have two solutions: The first one: struct ch { int num; char c; } characters[127]; char find_first_no...
Problem statement: In Windows Workflow Foundation we have a long running state machine. We had an issue with SQL server deadlocks putting workflows into a suspended state. Since Workflow instances are independent actors, we cannot easily coordinate these calls. As part of our workflow error handling strategy, if the...
I want to refactor below code. Do() method below gets the position number from other component "_calComponent.GetPosition()" and compares the value with the pf control positions (PfControlPositions). As you can see there are many if conditions that I had to use here. I did not like this approach. I am not able to w...
I'm trying to implement the UoW pattern using ADO.NET and this is what I've achieved so far: The IUnitOfWork Interface: public interface IUnitOfWork : IDisposable { IDomainTableRepository DomainTables { get; } IVariableRepository Variables { get; } IModelRepository Models { get; } IStructur...
I have a word document which has a lot of active x checkboxes on it and I have just been told the way it has been coded and done could be improved upon a lot, so I am asking for a bit of help. To quickly explain it, the checkboxes are tied to a "completion overview" at the bottom of the document. The code on the checkb...
The following code displays a Timetable, but the code needs too long finish the whole process. <?php class showTimeTableModel { static $home = false; static $type = NULL; static $c_id = NULL; static $class = NULL; static $subjects = NULL; static $kn; static $year; static $kw; static...
I recently got in really deep on a question to find the overlapping meetings and I rewrote a bit of the code and added some things to the code, and I would just like a general review of my code and what I could do to make it even better, maybe performance wise or whatever. Here is my LINQPad 5 Code Dump, you should be ...
I am a beginner programmer and I've been trying to complete an unbeatable tic-tac-toe program, my code is below. The program itself works, but it seems rather inefficient, as I literally have to type out every case of possible victory or defeat. Any suggestions on how to make the code more efficient, or general suggest...
I tried to write this code as concisely as possible. Is this the best way to do it? def collatz(n): """ Generator for collatz sequence beginning with n >>> list(collatz(10)) [5, 16, 8, 4, 2, 1] """ while n != 1: n = n / 2 if n % 2 == 0 else 3*n + 1 yield int(n)
Can someone review my code? I am trying to implement radix sort in JavaScript. var numbers = [90, 46, 7, 12, 100, 68]; var length = numbers.length; var buckets = new Array(10); Clear(); function Clear() { for (var i = 0; i < 10; i++) buckets[i] = []; } RadixSort(); function RadixSort() { var maxElem...
The following code is a function that works. It's just slow and I don't know how to speed it up. It takes an Excel row number and the value of its headerval (string) and finds the same headerval on a different sheet then copies the formatting and applies it to our new sheet. The true false is because the source sheet h...
Motivation: Have std::vector<std::unique_ptr<T>> accessibility at std::vector<T> speed. std::vector have one inconvenience - you can't store pointers nor indexes to elements if the vector grows/alters. To overcome this problem we usually use vector of pointers / deque (if only grow) / list / etc. Having our elements in...
I use this script in amazon lambda for image processing. Script should do: download image and watermark from amazon S3 resize image to two sizes put watermark on it and annotate with text put resized and watermarked image to other bucket send to external host some metadata info At this moment it works as expected, bu...
Original question Reimplemented solution following JS1's answer. Changed bit string hack to bitwise operations to get the corresponding base64 index values. #include <stdio.h> #include <assert.h> void get_b64_quads(char *hex, char *b64quads, int pad) { char *dec_2_base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop...
I have written the following the code to complete a matrix based on data provided in a second worksheet, but the code is really slow (note that s1=12,000, s2=40 and s3 = 200,000). Any suggestions on how to make this code faster? Sub UpdateMatrix() Dim wsOverview As Worksheet, wsData As Worksheet Dim rngTable As Range ...
The code for a binary search on an ordered string by alphabetical orders seems to work. I am wondering if there is a better way to write this. function binary_search(arr, letter){ var first = 0; var middle = Math.floor(arr.length/2); var last = arr.length -1; while(true){ var test = arr[last];...
I'm working on my first NodeJS / Express application with the async module. It's been an uphill battle for me learning node (and even JavaScript) as I go along so I'm sure there's a lot of room for improvement. I've written a GET event handler for my REST API and I'd like to know: Where and how to decompose this into ...
I wrote these extension methods to provide a generic/re-usable method for saving a form's size, position, and window state. What I would primarily like to know is if there is a better way to handle storing the WindowState property. I would also like to know if there are any bugs I might have overlooked, unnecessary cod...
Problem URL This is the solution I came up with the minimax problem stated above. I did a top-down recursive approach with memoization, and I think this should be \$O(n)\$, since we are filling out a memoization table with \$n\$ elements, with constant number of operations per each recursive call. Nevertheless, I am ge...
I have recently written a Brainfuck interpreter in C#. I tested it with the examples given on EsoLang website. It does not handle errors right now. Questions: Even that it can run only one program at once, should I maybe put the variables into the class (create new class) or just leave them inside the BF method? Shoul...
I have the following code in Python which opens and closes a file in every iteration (using with keyword). In 95 % of iterations the file will be the same, so there's no need to open and close it again. Is it possible to optimize it if this optimization has sense? import sys import re def createFileName(str, index, nu...
Numbers are being stacked in the following manner: 7 4 8 2 5 9 1 3 6 10 The x-axis is horizontal and the y-axis is vertical. With that in mind, here are a few examples of the values and their coordinates: 2, 3 (coordinate) ==> 8 (value) 2, 2 (coordinate) ==> 5 (value) I need to write a function \$fn(x, y)\$ which ac...