instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have trouble understanding recursion, so I'm trying to implement algorithms using it. I wrote this code that calculates the length of the longest increasing sub-sequence. How can I improve this? int _lis(int arr[], int n){ if(n==0) return 1; int m=1, temp; for(int i=0; i<n; i++){ if(arr[i]<arr[n]){ ...
stackexchange/codereview
In the database, I have a table with name photographs with the following columns: id filename type size caption I want to create two classes - one is Domain Model named photo.php and the other one is a Repository class (photorepository.php). So, I started like this: photo.php: class Photo { private $id; priva...
stackexchange/codereview
I have written a powershell script that will scan a directory for any *mkv, *.mp4, *.avi files, and will parse the filename to get Name, Season Number, Episode number. Then will check against destination directory to determine If Name exists (if not create it) If season number exists (if not create it) Once both these...
stackexchange/codereview
Problem statement Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], a solution set is: [ [-1,...
stackexchange/codereview
I wrote a Player package in Go. It builds correctly, but I would love a review on what I did and did not do "the Go way". I'm new to coding in the language, although I've gotten about halfway through Ivo Balbaert's "The Way To Go". The code consists of a struct and a bunch of setters and getters for the struct. packag...
stackexchange/codereview
I have a set of Excel data which I read and assign to corresponding columns of an Excel table. In our Excel we have provided the user the option to rearrange the Excel column fields at runtime. int rowIndex =int.Parse(ExcelSettingManager.ItemLine); int lastItem = numberOfFilledRows(); numberOfFilledRows(); int maxI...
stackexchange/codereview
I was doing 3sum question on leetcode Question 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. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4] A...
stackexchange/codereview
I'm currently going over Robert Sedgewick's Algorithms book. I implemented a Symbol Table using two parallel array one for keys and one for values. The keys array is ordered and the Symbol Table uses binary search to find the position of the elements in the array. In the practice section, the implementation of the dele...
stackexchange/codereview
I am creating an API for consumption by other developers to interface with an internal framework. My goal is to be able to have the developers type something like: profile.setPreference(new GroupPreference(id)); or UserPreference preference = new UserPreference(); preference.setDefaultInbox("nameOfInbox"); // set any...
stackexchange/codereview
I took some code and reviewed it, but it got me thinking, so I re wrote the code a little bit and would like to ask what you think of it and why it's bad to do this, even though it works. public class FizzBuzz{ public static void main(String[] args){ for(int i = 1 ; i < 101; i++) if(i % (5*3) ==...
stackexchange/codereview
This Review Request evolves into this Review Request now with a custom UI and other changes. I wrote a program to simulate the drinking card game Kings. This is my third Java Project. I didn't quite understand how to create the classes Card and Deck. I was struggling to create them so I went ahead and used someones c...
stackexchange/codereview
I am quite new to Java, and I am trying to read a file into a string (or should I use byte arrays for this?). File can be anything, such as a text file or executable file etc. I will compress what I read and write it to another file. I am thinking of using this code: public static String readFile(File f) { StringBu...
stackexchange/codereview
I was reading about the MIDI spec and I challenged myself to implement a function to convert an int32 to a variable length quantity uint32. I didn't look it up or anything so there might be a way more efficient or tricky way to get the same result, but as far as doing what I set out to accomplish the following code wor...
stackexchange/codereview
This code reaches time limit on 1 test case, solving this challenge. The approach that I'm using is from the book Algorithms Functional Programming Approach, which is a backtracking depth searching method. How do I improve speed of this code? Or is there better way to do it? searchDfs :: (Eq node) => (node...
stackexchange/codereview
I am trying to fill values based on group, in my case id. I would like to fill the missing values according to the available date info for each id. id date 1 1 23-04 2 1 23-04 3 1 <NA> 4 1 <NA> 5 2 24-04 6 2 <NA> 7 2 <NA> 8 2 <NA> 9 3 23-04 10 3 <NA> 11 3 <NA> 12 3 <NA> 13 4 <NA> 14 ...
stackexchange/codereview
What? I have a reference counted dynamic byte array written in C. I'm currently using this implementation in a FIFO fashion. Particularly reading data from files into the arrays, then parsing the data in the array byte by byte. I'm looking for feedback on anything! Even the decision to use a dynamic byte array versus ...
stackexchange/codereview
N.B. The next stage of this project, which covers parsing filenames and checking numbers against the list produced in this question, is covered here. I have a list of company numbers (UK companies registered at Companies House) in an Excel spreadsheet. A CRN is an 8-character unique identifier attached to a specific r...
stackexchange/codereview
I am working as a validation technician for excel spreadsheets in a pharma company. Sadly & interestingly I don't know much about VBA and Excel. To validate those excel spreadsheet, I developped with macro-recording the following code, which helps me identifying the cell properties. The goal is to quickly obtain releva...
stackexchange/codereview
I'm doing a daily reward system on my site. Users can pick up the reward only once a day. The next reward can be picked up the next day, also, only once. When a user visits the site to pick up a daily reward, I put a timestamp in the database (e.g. "2023-09-15 15:36") when the user picked it up. The number of consecuti...
stackexchange/codereview
What do you think of this idea? It's supposed to be a dict that makes a reasonable guess at the key you were trying to access for getters and deleters. Setters should be untouched. Similar to how tab completion in bash works, if some command you are typing only has one reasonable completion then pressing tab will fil...
stackexchange/codereview
I am a system admin, not a developer, so this might be pretty horrible code. This is a password generator. The point of the attempt was to become more familiar with Django at a lower level. I current host Django sites other developers write and sometimes it would help to have a better understanding of how the sites wor...
stackexchange/codereview
I wrote a simple function that converts an array of words into proper case (using bitwise operations) and returns the array. I performed a simple test using std::chrono to check how fast it was able to perform the conversion. Using a vector of 1000 words the function was able to do it in an average of 27 microseconds. ...
stackexchange/codereview
I have implemented a "Guess number game" using Swing. The idea is that the user enters a range and the program makes guesses of the number. This is the first time I'm implementing this kind of application. If there are any improvements I should make to the code let me know. I will be grateful for any suggestions. publ...
stackexchange/codereview
this is the second version of this project, you can check previous post here: Terminal Graphical Visualizer, using a queue of different matrices I implemented bare-bones version of ncurses library (without using it obviously), and using it I implemented 3 visualizations: falling sand simulation - drop a line of sand p...
stackexchange/codereview
For my current job, I've been told that soon I'm going to be porting our Python code to Cython, with the intent of performance upgrades. In preparation of that, I've been learning as much about Cython as I can. I've decided that tackling the Fibonacci sequence would be a good start. I've implemented a Cython + Iterativ...
stackexchange/codereview
I wanted to update some properties of my UriString but since this type is immutable, it wouldn't work. Actually, I just wanted to update the Path property but I don't want to have a constructor with several parameters like in the other question because this is too much work and sometime not desireable. Instead, I requ...
stackexchange/codereview
I have 'n' microphones placed in square fashion and I want to make sure that all the channels must be aligned in time exactly the same if the signal is equidistant from all the 'n' microphones i.e. in the center of the square. I have written this script to do the difference in zero crossing timings for only two signals...
stackexchange/codereview
This is the first time I have programmed something that I will actually personally use, so I am happy about that. I tried to write good code whilst applying functional programming concepts. So no state, and a concise function. I know that when making the lists it pulls information from the JSON that doesn't get used l...
stackexchange/codereview
I recently came to write a regex to parse URLs. Now I wonder, did I miss something? Did I make a mistake or could I have written it cleaner? That's why I'm here. In order to write the regex, I took this paper as a reference (together with some Wikipedia articles about URIs/URLs). //According to http://www.ietf.org/rfc...
stackexchange/codereview
I am writing a c++ class of "A simple least squares approach" by Longstaff and Schwartz. I have only finished writing a function for creating the stock price paths using geometric brownian motion. I am still a bit of a novice when it comes to writing classes in c++ and I just want to see if there is anything I can impr...
stackexchange/codereview
I've implemented abstract module for fields validation according to this MVP clean architecture repo. In a nutshell I've created ValidationGateway protocol containing signatures for validate methods. Then created ValidationUseCase protocol and implementation to wrap called exact method on validationGateway like this: t...
stackexchange/codereview
The following class is used for handling sessions: class DBHandler implements SessionHandlerInterface { protected $exists; public function open($save_path, $name) { try { DBCxn::get(); return true; } catch(PDOException $e) { return false; } } ...
stackexchange/codereview
My first time writing anything significant in CUDA. This kernel takes two arrays representing square matrices and compares them pair-wise. It takes into consideration large input arrays, and calculates the appropriate number of threads on the GPU to spawn. Currently takes ~1 second to compare 10 million 2x2 matrices (s...
stackexchange/codereview
This is my bare-bones Brainfuck interpreter in C using lots of unixisms. What improvements can I make (with respect to the clarity of code, or obvious features to add)? #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #incl...
stackexchange/codereview
I have code that parses through web pages finds commentaries and saves commentary info in DB. I have an array where all necessary pages are stored. I iterate through all these pages one by one and find HMTL element which contains all the info about commentary if there are multiple pages with commentaries I iterate thro...
stackexchange/codereview
A Java service that connects to MongoDB in production, but opened connection count is too much. It affects on MongoDb performance, so I have come up with a solution that provides only one MongoClient instance so which will reduce the connections. Here is my code, is it a good way to provide a singleton object from 3rd ...
stackexchange/codereview
The purpose of the code is to see if a form element would get data from internal react components and it did. It was also to see how clean I could make an autocomplete component. The autocomplete has 4 states and I use bind excessively (is this bad?). I also added a function updateSpecificState, because I found it inco...
stackexchange/codereview
I made this code for simple leveling game. I think this code may have some issues with security. Also, are there some way to make this code more efficient and reliable? For level scaling I will use this method. Should I make lvl, xp and nxtlevel variables to array or is that a bad idea? class LevelingSystem { privat...
stackexchange/codereview
I receive messages from a MessageWebSocket connection frequently, which are compressed with zlib. The following code decompresses them to a stream which can be read with JSON.Net's JsonReader. I'm pretty sure there are some improvements to be done, but can't quite put my finger on what: private MemoryStream _compressed...
stackexchange/codereview
I created a function to do that, and I want to know if there is a problem I'm overlooking about it .. void replaceStr(buffer, haystack, needle, rep) char *buffer, *needle, *rep; const char *haystack; { if (!buffer || !haystack || !needle || !rep) return; size_t rep_length = strlen(rep); lon...
stackexchange/codereview
I have created a QuadTree in Java and would like a general code review or suggestions. import java.util.ArrayList; public class QuadTree { private QuadTree root, parent, northEast, southWest, northWest, southEast; Point center; Double halfDimension; Double northBound, eastBound, southBound, westBound;...
stackexchange/codereview
I worked on this for a software engineer interview as the take home challenge. The company came back with this constructive feedback: You made a slight mistake in ace handling that led to the inability to handle multiple aces You hard-coded global variables for player1 and player2 state (why is this bad?) There wa...
stackexchange/codereview
I've got the following schema, which can not be modified since it's a problem taken from an exam: Player ------- player_id (PK) player_name player_games_total player_games_won Competition ----------- comp_id (PK) comp_player1 (FK references Player.player_id, NOT NULL) comp_player2 (FK references Player.player...
stackexchange/codereview
Please review this Android UnitConverter App which has been designed using Strategy Pattern. public class UnitConverter extends Activity implements OnClickListener, AdapterView.OnItemSelectedListener { /** Called when the activity is first created. */ private Spinner SpinnerUnit; private EditText inpu...
stackexchange/codereview
I decided that I wanted to add some spice to my bland looking city maps, so I created a couple of algorithms to add water to the map. I also added a "marshlands" setting that would just randomly sprinkle water throughout the map. Here is an example of the river generation: Here is the world generation method in its en...
stackexchange/codereview
This script is running indefinitely as the Linux background process. I have put an enormous effort to make this POSIX shell script containing an infinite loop shut down tidily along with the operating system (TERM signal) and by me sending it a HUP signal. Ok, we don't call it exception-handling, but I didn't find any ...
stackexchange/codereview
I made a simple program in which I compare two images pixel by pixel and determine if the pictures are the same. I'm trying to adapt it to MPI, but I'm afraid that the communications are taking too long, making it way more inefficient than its sequential counterpart. I have tried with images of very big resolution and ...
stackexchange/codereview
I know the difference between the Entity Framework connected mode vs disconnected mode. In connected mode we do all the stuff inside one single DbContext instance. In disconnected mode we do the stuff and then attach the Entity to a new DbContext instance. My problem is that I - for a specific reason - had to create th...
stackexchange/codereview
I want to check some timing of my (pre-C11) C++ and wrote a class: class ScopedTimer { timespec start_,end_; std::string name_; /// name of this timer (used in output) bool active_; /// if not active, no output is printed clockid_t clock_id_; /// clock type used for this timer public:...
stackexchange/codereview
I'm working on an important project. We're an IT services provider and we have a project where we have to build a new system to process data from a specific client. The problem is that usually we process their data, but they send us a pre-processed data that's easy to parse, but this time around, they're trying with a ...
stackexchange/codereview
I just coded an object-oriented Sudoku solver, but I don't have any possibility to check whether I have written good code, so I thought I would just post it here for review. I have looked for other solutions online but they mostly use different approaches so it's hard for me to compare. I'm just getting started and try...
stackexchange/codereview
How idiomatic is my code? Since Lua does not have classical inheritance such as in OO languages. Feedback on the test and implementation are both appreciated/welcomed. The rules are: If the phone number is less than 10 digits assume that it is bad number If the phone number is 10 digits assume that it is good If the p...
stackexchange/codereview
I have been doing this test task for C# Developer role at UBS.London recently and have been rejected. No reason stated yet. Was wondering if you can take a look and provide feedback on what I can do to improve solution. The task description is below and solution itself is on GitHub. Also attached code for two main clas...
stackexchange/codereview
What do you think of my script to make an immediate DB and document root zip backup? Any flaw you might find. Please inform me of it: #!/bin/bash mysqldump -u root -p --all-databases | zip ${drt}/db-$(date +\%F-\%T).zip zip -r all_zipped-$(date +\%F-\%T).zip ${drt}/ -x "*/cache/*" rm -rf ${drt}/db-$(date +\%F-\%T).zip...
stackexchange/codereview
Question Any way I can optimize this further using new C++11 or C++17 features? Would also like feedback on my variable naming, memory management, and style (notice my placement of varible_name++ in some areas), and how I've abstracted the sort into a recursive_merge_sort function and a merge function. Code #include <i...
stackexchange/codereview
I have implemented a static_for loop to iterate over the elements of an std::tuple using C++17 features. Here is what I have currently: #include <iostream> #include <utility> #include <tuple> template <std::size_t I> struct wrapper { static constexpr std::size_t n = I; }; template <class Func, std::size_t ...Is> ...
stackexchange/codereview
I'm learning Javascript and created the below to take input from a user. If the number is between 150 and 300 it will print out the numbers from that number up till and including 300 in sequential order. var num1; conDition(); function conDition(){ num1 = prompt("Please enter a number: "); if(num1 >= 150 && ...
stackexchange/codereview
I'm developing a Rails-based web interface/API for a large, vendor-supplied, legacy Oracle database. One of the constraints is that I can't change the schema other than adding views, because it still has to support the vendor's application. The table for customer data has a limited number of columns, and extended attri...
stackexchange/codereview
I have a feature for users to be able to export the database information. But if the user choose all options to export it takes 1 minute or more to download the .csv file. I'm only including 1 part of the if statement, where I'm pulling in all the data. here it is: function exportTheData() { //get the data f...
stackexchange/codereview
Created the following method: public static int max(int[] array) { int max = Integer.MIN_VALUE; for (int value : array) { if (value > max) { max = value; } } return max; } Question(s): I believe the Big O Notation for this implementation is O(n), am I right? Since this is ...
stackexchange/codereview
I [believe that I] wrote foldl in terms of foldr: myFoldl :: (a -> b -> a) -> a -> [b] -> a myFoldl f base xs = foldr (flip f) base (reverse xs) Is this an idiomatic implementation?
stackexchange/codereview
I wrote a simple class to cache data on a filesystem. The class also provides an internal cache using a static variable to avoid reading from disk for each request. <?php /** * object caching system */ class cache { /** * The *Singleton* instances * @staticvar cache */ private static $instance...
stackexchange/codereview
It's my first exercise involving the well-known binary search. The problem goes as follows: we are given a sequence of n numbers and we have to answer to t questions, each of which is: “How many numbers in the specified sequence are greater than the i-th element of the sequence?” For example, we have n = 3 and t = 3. O...
stackexchange/codereview
The following code is a conversion from some old java I wrote to python. It shows the beginnings of a simulation of an ant colony. I am finding the animation speed very slow - and I'm wondering if I am doing something wrong - or if it's nothing to do with the animation, and everything to do with not exploiting the vect...
stackexchange/codereview
Trying to make a little 2D engine I can play with. The end goal is a simple multiplayer PVP game just using shapes. I will make one version using ECS and one using OOP for learning. This is the shell of the ECS version using Pong as a demo. Before I jump into the user interface I am wondering what people smarter than m...
stackexchange/codereview
I am displaying menus and submenus in my WinRT app, and I think I am doing it wrong. I have thought I was doing it wrong for a long time, so here it is for review. This is the section in my ViewModel. Probably needless to say, both Remove() and NewSelectionWS() have had large quantities of nearly identical code remov...
stackexchange/codereview
I have an assignment to encrypt files (+- 1 gb) and speed is an important factor. I am also kinda forced to the C# language since nobody in my group knows C++. The time now recorded for 100 mb is 12 seconds could somebody give me advice if it is possible to improve the speed my encryption function below. private void b...
stackexchange/codereview
I thought I'd give it a shot. What I came up with is from a culmination of my last two submissions, incorporating most of the feedback from this community, including better naming of variables, initialization, and making my program a bit more user-friendly. I'm not sure which optimizations I can make or if there are an...
stackexchange/codereview
I wanted to learn how to create awesome parallax scrolling effects so I decided to look up how to do it, after some searching I put together this test. It works fine to some extent but it feels a bit messy, especially if you would expand it with more effects and elements. You can see it in action here (had to replace ...
stackexchange/codereview
This is basically a straightforward heap implementation. I am just moving from C to Python and I wanted to make sure that I follow Python's best practices in general. This heap is supposed to support data from any data type with any comparing function. class Heap(object): """" Attributes: heap: List rep...
stackexchange/codereview
Inspired by this blogpost I decided to try and make it possible to have ranges of enum members that dwim, aka. that contain the actual members and not a stringified form. This is the result. I'm looking for comments and wether I overlook a pitfall. Also, maybe EnumMember subset can be expressed in a more performant wa...
stackexchange/codereview
Today, my project was to make a matrix in my web browser. It is really slow, so help with optimizing it would be nice. It runs slow on my PC, yet alone my iPod 4 which this is going to be for. <html> <head> <title>Matrix</title> <style type="text/css"> body { background-color:black; ...
stackexchange/codereview
I made a search page at the beginning of a work book. This page has a drop down that allows you to choose what category to search in, then you type your phrase or keyword into the search box and it finds all of the results. It then takes those results and pastes them in in the chart at the bottom of the search page. Yo...
stackexchange/codereview
Since I'm a big politics nerd, I wanted to write a little script that would analyze the frequency and content of political fundraising emails. I signed up for the e-mails of 6 campaigns, donated a dollar to each so I'd get hit up for more money often, and let it sit. Unfortunately you won't be able to run the script ...
stackexchange/codereview
I'm completely new to C and my first project is to create a simple cURL-like HTTP request client... but first, I need to create a function that can parse a URL. I've created this function, and it seems to work quite well, but since I'm so new to the complexities of C, can someone check for any errors or to see if I can...
stackexchange/codereview
When I was working in Rust this week, I missed kotlin's fun <T> Sequence<T>.single(): T. Basically, calling this function means that you are asserting that the sequence contains only one element and that you want that one element back. The most common use case is you've filtered a sequence down to one element. It's als...
stackexchange/codereview
Input is two strings, the first string being the long string and the second smaller string being the permuted string. The output should return the starting indices of all occurrences as well as the permutation of the substring in the longer string. Case 1) permutationsInString('abcdcbadefbac', 'abc') sample output: { '...
stackexchange/codereview
I am creating my first game using Phaser and it is running fine in desktop. But it is lagging on Android phones. Can anyone tell me what could be the reasons? The game is very small -- smaller than 2MB. The images used in the game are also very tiny .png files. Is there any way to find out any leaks in my code? My main...
stackexchange/codereview
Please review my solution for the following problem. I am interested in: Maintainability Usability Logical correctness Efficiency Problem: It has 1+ objects each in separated thread and between the objects has an 1:N relations in the emitter side and N:1 relations in the receiver side. The connection has to be remova...
stackexchange/codereview
I'm giving the repository + UoW patterns my first shot on the server side, so bear with me. Also, it's worth mentioning that I haven't used an IoC container on the server side before either, so I'll post its setup too. I'm using simple injector at the moment. All kinds of feedback is appreciated, especially for UnitOfW...
stackexchange/codereview
These IDs seem like they should be a table as, there are several queries that use the same list of IDs. The following needs to be refactored. SELECT SUM(CASE WHEN s.TypeID IN(1,2,3,4,7,8,10) THEN 1 ELSE 0 END) FROM Sales s The problem is a subquery can't be used in an aggregate function. I'd like to write it as foll...
stackexchange/codereview
I am trying to do some translation of text files. I have a translation .csv file and a file I need to translate (tab delimited). The translation is creating a file with an extra column of the translation. I'd like to hear any suggestions on this. import com.google.common.base.Joiner; import com.google.common.base.Split...
stackexchange/codereview
Follow up question to: Utilizing OOP when creating a web browser After I received help on the question above, I've created 3 classes for my Browser. Browser is my "View"-class that handles the GUI, Model is self-explaining and History contains the lists and their functionality. First of all, is this an OK solution from...
stackexchange/codereview
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. P is an index of an array A. Input: A[0] = -1 A[1] = 3 A[2] = -4 A[3] = 5 A[4] = 1 A[5] = -6 A[6] = 2 A[7] = 1 Output: 1 3 7 1 is an equilibrium index of this array, because...
stackexchange/codereview
I recently began to learn Python and encountered this problem. The condition: You and your friends are playing the next game. Friends write natural numbers in a row on the board. Your task is to find as many consecutive numbers as possible that are divisible by the same number greater than 1. Since it is difficult to ...
stackexchange/codereview
I am writing a script that is supposed to retrieve some data from a MYSQL database but I need to make it happen live and after lots of research I learned that this thing can be done using something called "Web Sockets" but since it seemed too complicated and I haven't even learned javascript that well, I chose to keep ...
stackexchange/codereview
A while back I had to do a project for school in Python, creating a game or something interesting. I decided to make a memory game. The code isn't really nice and neither are the variable names. It's not supposed to look good, and all that matters is the functionality. I had done a lot of movements with the Turtle so g...
stackexchange/codereview
Basically, you just run main and it allows the client to "log in", and extract their number from a map, increment their own number, and log out. It all compiles and works fine, but how can I decouple this code, and make it more composable? I'm finding it's difficult to separate concerns, ex between the logic, and the ...
stackexchange/codereview
Here is the sender and handler interfaces: public interface ISender { Task SendAsync(object e); } public interface IHandler<in TEvent> { Task HandleAsync(TEvent e); } So I register in IoC container a sender service implementation, which dispatches events to all the compatible IHandler<in T> implementations. I...
stackexchange/codereview
I have a CSV file that I would like to split up by row, do some whitespace processing on the string data in each row of the document column, and then output the processed data into separate TXT files in a new directory. The whitespace processing is to standardize the documents by removing newlines, carriage returns, an...
stackexchange/codereview
I'm wondering if this code can be made more clear and fluent: using System; using System.Threading.Tasks; using Windows.Data.Json; using System.Collections.ObjectModel; using System.Net.Http; using System.Collections.Generic; using Newtonsoft.Json; using System.Linq; using eTest.Space.Log; using eTest.Space.Interface; ...
stackexchange/codereview
I have code which gets data from a POST request (request.form dict), compares with corresponding attribute in object accident and does some action. The code looks needlessly verbose. How can I optimize it? if accident.status == 1: if request.form.get('reason') \ and request.form['reason'] != accident.reaso...
stackexchange/codereview
For integer A, the base level of 1 is "XYZ" For subsequent levels, the levels become "X" + Level (A - 1) + "Y" + Level (A - 1) + "Z". So for level 2, the string would be "XXYZYXYZZ" The objective is to return the substring from the Level string using the Start and End Index. Example: If entering 2 3 7, it would Level 2...
stackexchange/codereview
I have to write a program that reads a word to the char array and next display it reversed. I must find best own optimal solution. My solution of this exercise: #include <stdio.h> #include <stdlib.h> #include <string.h> char* reverse(char* str); int main(void) { char word[50]; printf("Podaj slowo: "); sca...
stackexchange/codereview
In the previous post I presented the MVC architecture, but all we saw of the View was the pretty bits. From the outside everything looks innocently pretty: The guts of the worksheet's code-behind is a bit more... chaotic. Maybe not chaotic-evil, but chaotic nonetheless, despite the fact that it's really doing nothing ...
stackexchange/codereview
I have started dabbling with golang. I wrote up a binary search tree implementation. I was wondering if there is a cleaner way. Here is my implementation: type BNode struct { left *BNode right *BNode data int64 } func insert(n **BNode, data int64) { if *n == nil { (*n) = &BNode{data: data, le...
stackexchange/codereview
I am creating a website that collects volunteer registrations for events (also called races in the code). I am using PHP CodeIgniter (which follows the MVC model). I created a control panel that has lots of tools and reports. Right now, my models generate EVERYTHING that is needed for that model to be complete. That p...
stackexchange/codereview
I'm trying to design a database model for an API. So far, here's my attempt to do so: I have a package called models that contains all of the models. Here, User is the database model and UserStorer is an interface that should be implemented by any store (e.g. postgres, mongodb etc.) package models //User represents a...
stackexchange/codereview
I've written a function to calculate all the distinct substrings of a given string, that are palindromes. The string is passed as the argument to the function. For example, the string abba is a palindrome because reversed it is also abba. If the function takes the string aabaa it returns 5, because the distinct substri...
stackexchange/codereview
This is a program I made as I am currently living in Japan with a British bank account, so exchange rates matter to me. On the first time run, you run the script with two arguments (two currencies) and it will track those currencies. You can add as many exchange rate trackers as you like. It emails you daily (automated...
stackexchange/codereview