instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I would like to do a refactoring of web API implemented in .NET Core. The Goal is to simplify Get method and to implement this to be more according to REST philosophy. I would appreciate any advice. As you can see the logic has many invalid combinations and too much code in one method. namespace Api.Treatments.V2 ...
stackexchange/codereview
I'm trying my hand at an address book and the goal is for it to have a bit more of error prevention. For instance, for the key "phone" to have 10 digits, and not allow alpha characters at section 4. I believe I have formatted this properly to the best of my ability. I understand this is very elementary as I'm new to an...
stackexchange/codereview
In order to grow potatoes I'm implementing the retry pattern. If I fail to grow them, I'd like to try it again later. The first part I've implemented is a collection of delay generators. Their base type is the DelaySequence: public abstract class DelaySequence : IEnumerable<TimeSpan> { protected DelaySequence(int c...
stackexchange/codereview
I'm trying to implement properly search functionality for database table. I tried this approach: Controller: @GetMapping public Page<TransactionDTO> find(TransactionFilterDTO filter, Pageable page) { return searchRepository .findTransactionsByFilter(mapper.toFilter(filter), page) ...
stackexchange/codereview
I'm developing an internal API using Flask, although due to limitations with our platform the endpoints will be accessible over the public internet. It will only have a very small number of users and it's not likely that this will increase much in the future. They will query the service programatically from a backend. ...
stackexchange/codereview
Goal: make this code as efficient as possible. Given a finite dataset (Colors - this isn't Crayola here :D) how do I know what colors are not assigned to a given user? Additional requirement - the final result should output a single column of comma-delimited colors. Spaces do not matter, but it'd be nice. This current...
stackexchange/codereview
I've written code that deletes a "post" the user has sent with my Android app. A "post" is made of an image (stored in Firestorage) named A, of a Firestore document named B which is the user UID (this document contains a field that is the sum of all the posts' number of likes), and of another Firestore document named C...
stackexchange/codereview
Simple class to simpify runtime file loading of ressources. The class reads all files from a given directory including all subdirectories and stores the name together with the path in a simple struct. If a file needs to be used by the program just pass the name to GetPath() and the class returns the location of the fil...
stackexchange/codereview
I know I haven't implemented many methods, and haven't specialized it for T[], but I just want to see if what I coded is good or bad. template< class T > class unique_ptr { private: T* ptr; public: unique_ptr() noexcept : ptr(nullptr) {} ~unique_ptr() noexcept { release(); } explicit unique_ptr(T* data)...
stackexchange/codereview
A bit of background. In the application I work on there are emails sent to notify users about articles they need to review. Each email+recipient pair is stored in database and may be assigned a different creation date ( called DateCreated ) due to emails being generated over some time. I needed to calculate how many ti...
stackexchange/codereview
One of many aspects of a project I am responsible for is generating an abbreviation, that is no more than n characters, for a given string. We use this in the organization for a couple things, and it only happens once for each "thing", so performance isn't hyper-critical. An example is something like "The Main Test Com...
stackexchange/codereview
I am currently in between semesters at school and am using that time to improve on my knowledge of C++ classes by making a node class and a linked list class that inherits from the node class. There is a list of areas in need of improvement at the start of the code, but I was also hoping to get some external input on t...
stackexchange/codereview
I have created a non-owning view of some spatial data that organises the data into cells. The data is split into a grid of cell size 100, and the key to the underlying HashMap is the index (top left corner) of the grid cell. Each grid cell contains a Vec of Point2D. The purpose of this data structure is for efficient ...
stackexchange/codereview
The profile tells me it took ~15s to run, but without telling me more. Tue Aug 19 20:55:38 2014 Profile.prof 3 function calls in 15.623 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 15.623 15.623 15.623 15.623 {singleLoan.genLoan} 1 0....
stackexchange/codereview
I've made the following program that takes a list of email addresses from a table in MS Access and sends each a test email. 'Send email to mailing list Function SendNotificationEmail() 'Handle any errrors On Error GoTo ErrHandler: 'Create Outlook object Dim olApp As Outlook.Application 'Namespace D...
stackexchange/codereview
This was part of a code challenge. I use them to help me learn c++/c# along with tutorials and guides. Basically I was taking a string... The quick brown fox jumps over the lazy dog. ...and reversing the words in the string like this. ehT kciuq nworb xof spmuj revo eht yzal .god The following code works and compi...
stackexchange/codereview
This is a simple app for taking down a user's home and work address, the days of their commute, and the times they go to work and go home. The times and workweek are entered via TimePicker dialogs with additional buttons. An IntentService runs in the background with setRepeating alarms that call per the user's set time...
stackexchange/codereview
Over the weekend I was curious about efficiently merging multiple sorted iterators together, and for them to be in sorted order. This is quite like a challenge on HackerRank: You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next...
stackexchange/codereview
I wrote a class that generates combinatorial necklaces with fixed content as per Sawada: A fast algorithm to generate necklaces with fixed content. The class is instantiated with an input list that states the occurrence of each value that is to appear in the necklace. The execute method is called to run either Sawada's...
stackexchange/codereview
In a docker compose environment there are several apps that communicate with each other. One of these apps is a logger (a centralized logger). Every part of the system that needs to log something, will call the logger's APIs (which is written with gRPC). The logger adds these log requests to a queue (a BlockingCollecti...
stackexchange/codereview
That's gonna take long. This program solves 8 puzzle game (mini version of 15 puzzle) using A* algorithm. Program consists of 2 parts: Board.java - which serves as a representation for the board (N-by-N grid, not limited to 9 tiles) Solver.java - as the name implies, this class solves the given puzzle (if it is solvab...
stackexchange/codereview
I have two code snippets, doing exactly the same thing and both get the job done: use defaults use from config Which is cleaner to use in golang and why? first option: package main import ( "fmt" "strings" ) func main() { fmt.Println(getShCfg(Cfg{}), "\n================") fmt.Println(getShCfg(Cfg{...
stackexchange/codereview
After receiving some great feedback on my original program, I tried to implement everything that was shared and I just want to see if there's anything else that I can change to make my program clean and efficient. This program: Scans all of the words in a web page into a string (using jsoup) Filters out all of the HTM...
stackexchange/codereview
I'm trying to do a SPOJ problem called twosquares where you check whether the current number can be obtained by adding two squares together. However, I'm getting a "time limit exceeded" message. I'm creating a Sieve of Eratosthenes program. If the number n is prime and n ≡ 1 (mod 4) then the number is a sum of two ...
stackexchange/codereview
My Python-based web server (Tornado module) is pretty complex and keeps going down (seems like usually in the middle of the night), so here's a bash script that kills the process, restarts and emails and txt messages me: #!/bin/bash NOTIFYEMAIL=<my_email_address> SMSEMAIL=<cell_phone_number>@<carrier> # ie. pm.sprint.c...
stackexchange/codereview
Here is the code I am using it works fine; however, it obviously takes forever when there are a lot of files to check. exact shell is cmd.exe. I am really just looking to make it more efficient. Here is my run.bat file: setlocal enableDelayedExpansion setlocal enableextensions :: date variable set theDate=%date%-%tim...
stackexchange/codereview
Motivation In my web app (React, Redux, TypeScript) we have a common need to write paginated API calls, with various UI interactions (infinite scroll, prefetch pages in the background, or manual page navigation controls). Rather than re-write pagination handling in every case, I wanted to create a re-usable method to u...
stackexchange/codereview
I have implemented the Caesar Cipher in Swift and incorporated it into an iOS-app. I guess it's formally correct. Please see the attached images, which show how the usage of the app is meant. Here's the relevant code: struct ContentView: View { @State var input = "" @State var output = "" @State var shi...
stackexchange/codereview
Since Python 3.6 and PEP 525 one can use asynchronous generator: import asyncio async def asyncgen(): yield 1 yield 2 async def main(): async for i in asyncgen(): print(i) asyncio.run(main()) I created a function which is able to wrap any asynchronous generator, the same way you would wrap a bas...
stackexchange/codereview
I decided to create simple blog app by using Ember.js which should has the following interface For this purpose I created blog route which contain the following code: import Ember from 'ember'; export default Ember.Route.extend({ setupController: function (controller, model) { controller.set('currentPost', 0); ...
stackexchange/codereview
I want to implement a directed graph which has 3 main kind of edges: self referencing edges non directional edges between two nodes directional edges between two nodes Also I want to be able to do global operations on the graph, like e.g. counting or removing all edges fulfilling certain criteria. The easiest progra...
stackexchange/codereview
I'm trying to write game server core that I can easy extend to use for various games. From simple online Blackjack session, to MMORPG. Long story short, I came up with this solution: Firstly, we have common classes for both Server and Client. Those are simple data structures, probably will need to wrap them with Builde...
stackexchange/codereview
I am a new .NET/C# developer and one issue bugs me ever since I've wrote code the first time. How can I improve this code? Program.cs: class Program { static void Main(string[] args) { App(); } public static void App() { BankDetails bankdet = new Bank...
stackexchange/codereview
In PHP, I'm getting multiple series and dumping various bits of information into an array. I will be left with 180 items (if I put in 30 series details that have 6 events per series) $eventsArray = explode(',', $events); // This gets passed in via a param \load_curl(); $array = Array(); $curl_array = array(); $ch = cu...
stackexchange/codereview
I have below unstructured but valid JSON which need to be converted to structured format using any C# library or newtonsoft- { "root_id": { "Path": "InsertCases", "MainContract": "CreateCaseParameter" }, "root_tittel": { "Path": "InsertCases", "MainContract": "CreateCasePara...
stackexchange/codereview
I have some fascination with terrain generators, so I whipped up this generator in Python. The way it works is pretty simple, but I figure that I should give an explanation for those who don't want to try and figure it out. The initial 2D terrain array is generated with a provided width and height, and then filled ent...
stackexchange/codereview
Simplified from https://github.com/132nd-vWing/tacview-splitter. External dependencies: zip crate The code would do the following: read a file from disk (determined at runtime) analyze the content, split it into a header and a body divide the body into two categories (here blue and red) for each category, write the he...
stackexchange/codereview
I would like to know if this is a good way to make sure the user enters a valid number. #include <stdio.h> #include <ctype.h> void clear_stream(FILE *in) { int ch; clearerr(in); do ch = getc(in); while (ch != '\n' && ch != EOF); clearerr(in); } float retreive_input() { float input = 0; ...
stackexchange/codereview
I've put together a function in Delphi XE7 which returns the Dropbox directory path on my machine, as this path can be customized by the user. This function currently works on my computer, but it could have many defects preventing it to work for other users on different machines. So I would be very grateful if anybod...
stackexchange/codereview
I am trying to create an API wrapper for recharge (A Shopify subscription service), I am using the HTTParty gem module RechargeAPI require 'httparty' BASE_URI = 'https://api.rechargeapps.com' API_TOKEN = 'my_token' class Client include HTTParty base_uri BASE_URI headers 'X-Recharge-Access-Token': A...
stackexchange/codereview
I am filtering out a List<Car> based on the brand. Since each car is made by one brand, I want to make sure my method getCar() is called and just a single car is returned. If it returns more than one car, throw an exception. This is a simplified example, my current implementation is as follows: I have a list of cars st...
stackexchange/codereview
How can I optimize and shorten this code that I am using to display Woocommerce custom fields? function fields() { global $product; $value1 = get_post_meta( $product->id, 'storage', true ); $value2 = get_post_meta( $product->id, 'delivery_date', true ); $value3 = get_post_meta( $product->id, 'mpn', true ); $value4 = ...
stackexchange/codereview
Code: import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * Created by IDEA on 16/11/14. */ public class TestStream { private final static Pattern pa...
stackexchange/codereview
I come more from a frontend background and have been reading up on more backend approaches and algorithms while solving a TicTacToe grid to see if there are any wins normally, I'd probably use something like this for (let i = 0; i < rows; i++) { if (arr[i][0] === arr[i][1] && arr[i][0] === arr[i][2]) { but with wh...
stackexchange/codereview
The following is an implementation of a tree in C++ designed for keys which do not have an order (otherwise a std::map could be used). T is a key type and H is a hash for T. #include <iostream> #include <memory> #include <utility> #include <unordered_map> template<typename T, typename H> class tree; template<typenam...
stackexchange/codereview
I am not very experienced in Entity Framework, I previously used ADO.Net and Dapper for data persistence. For now, I only read Microsoft docs and watched a few video tutorials. I tried to stick to well accepted advice and have built a generic repository infrastructure with the help of from here and there. IEntity publ...
stackexchange/codereview
I wanted to get some stats on who has done the most edits on Code Review, so I wrote the following query on SE Data Explorer. All improvement suggestions are welcome. Note that I used a cursor to partition top users by year because at first there was a fundamental flaw in my logic trying to get the top users overall a...
stackexchange/codereview
I am learning Graphs on my own and want to use a graph for a personal small project, so I decided to take a look here in Code Review for some cool implementations and came across this one by Maksim Dmitriev I found it really great, so, heavily inspired and based on his implementation, I present you my own implementatio...
stackexchange/codereview
I want to improve my algorithms and data structures in C++ understanding and also learn how the standard library containers are implemented. This resizing_array is based on the std::vector. My questions are: Are there any memory allocation/deallocation errors in this implementation? Is the design ok? Can it be impr...
stackexchange/codereview
I wrote a function to find all the possible permutations of a list in Haskell. I know it can definitely be optimized, but I'm not sure how. I'm pretty sure foldl or foldl' can be used, but I'm not sure how. It gets kinda slow when the size of the argument for perms is more than 6 items, but I don't know if this is avoi...
stackexchange/codereview
I am using the code below trying to replicate the mobile phone feature that displays one or more contact names according to the numbers typed. This code is intended to be used on a JavaScript course I am teaching, so I try to keep it as simple as possible in order to walk the students through a possible scenario and th...
stackexchange/codereview
This code adds the following functionality to the basic tkinter.Tk() class... settings-file interaction for persistent application settings fullscreen functionality using F11, can remember last configuration or be defaulted removes the need for multiple root.configure() statements removes the need for root.title() and...
stackexchange/codereview
To solve a polynomial equation I have written following program, is there any way to optimize this program. Following code is working code: Program takes input n,x where n is the deg of polynomial and x is the point at which the polynomial is to be evaluated. #include<stdio.h> int power(int x, int y); int ma...
stackexchange/codereview
I have some functions and structs for loading and drawing an image with OpenGL. The two main places I would like feedback are: I've tried to separate the OpenGL-specific code into the implementation so the caller doesn't have to know what rendering API I'm using. Can I do a better job of separating the OpenGL-specific...
stackexchange/codereview
I wrote an example program about UNIX semaphores, where a process and its child lock/unlock the same semaphore. I would appreciate your feedback about what I could improve in my C style. Generally I feel that the program flow is hard to read because of all those error checks, but I didn't find a better way to write it....
stackexchange/codereview
I was reading this code where author claims that its the fastest implementation which I doubt, hence I decided to write my version of the same problem. 'use strict'; module.exports = function unique(arr) { if (!Array.isArray(arr)) { throw new TypeError('array-unique expects an array.'); } return arr.filter(f...
stackexchange/codereview
I wrote a script to save comments and submissions from Reddit using Elasticsearch. Is there any way to improve the speed of inserting new items into Elasticsearch? import praw import sys from elasticsearch import Elasticsearch subreddit_queue_file = "subreddit_queue.txt" def pop_task(): task = "" with open(s...
stackexchange/codereview
I had an online coding test yesterday. The question is not hard to solve, but I could not achieve the required running time. The question is as follow: Given \$1 <= M\$, \$N <= 10^5\$ find the count of pairs A, B: 1 <= A <= M and 1 <= B <= N \$(A^{1/3} + B^{1/3})^3\$ is an integer Here was my solution: I notice that ...
stackexchange/codereview
I have written a cryptography NPM package called kruptein. The code is also hosted on GitHub. Having used multiple "best practices" with regards to key management, algorithm selection, key size, iv size etc. I could use someone with experience in this area to help validate the implementation. I could use some help det...
stackexchange/codereview
This is my first Go program. I would like to know what could be improved, what is done wrong, and anything else that I should know. The CSV contains 10 questions with the 10 answers separated by a comma. For example: 10+10,20 4+5,32 If you want the full context this is from gophercises which are some exercises to prac...
stackexchange/codereview
I'm a little puzzled about a procedure inside my Android app. It's actually working but it looks like bad practice and probably it lowers performances. Short explanation: I'm running a separate Thread inside a Service. Inside the thread I fetch a list of files and the main purpose of the thread is to query the file to ...
stackexchange/codereview
Inspired by and created because of python3 utility: convert safely to int and driven partly by the 'refactor' in my answer. The aforementioned question and my answer drove me to go and do a thing while bored at work - I created a new object class called StrictInt that behaves much like the function created by the ori...
stackexchange/codereview
A while back I wrote a simple little PHP script that searches the Steam community market for any TF2 strange weapons with strange parts on the first page of results for that weapon type. It works by retrieving the listings for each weapon using curl, runs a regex to retrieve the internal JS variable containing the item...
stackexchange/codereview
Attempted to use strtol() to parse a string into an integer and to output any appropriate error messages for failed conversions. How did I do? How could/should it be done? Code works as intended if I did not miss anything. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h>...
stackexchange/codereview
Friends, It's been several years since I last worked with the ASP.NET Web API framework. Even then I had developed with it minimally. I have a requirement for a service that will allow for the creation of a new question, retrieval of all questions, and then retrieving a question by an eventId. The following code is my...
stackexchange/codereview
I wrote the following split function. It takes a list, an element and an Ordering (LT, GT, EQ). For LT, the list will filter out all items that are >= the element argument. split' :: (Ord a) => [a] -> a -> Ordering -> [a] split' [] _ _ = [] split' (x:xs) a LT | x < a = x : split' xs a LT | otherwise = split' xs...
stackexchange/codereview
I've just released a jQuery plugin that conditionally displays elements based on form values. I would appreciate any suggestions on how to improve both the code and its usefulness. Here's the demo page Would this be useful to you? What other functionality should I include? Any refactoring or structure changes that I s...
stackexchange/codereview
Implement an algorithm to print all valid (e.g. properly opened and closed) combinations of n pair of parentheses. Following is my implementation and I think it works. Is the algorithm efficient? Do you see any coding issues? def compute_all_parens (n, left, right, s): if right == n: print (s) r...
stackexchange/codereview
I am looking for as much criticism as possible. Specifically I am trying to institute BEST PRACTICES for OOP and game design. Enjoy! Github hangman repository Each Class is in a separate file and imported. BASIC LETTERS CLASS from enum import Enum class Letters(Enum): a = ('', 'A') b = ('', 'B') c = ('',...
stackexchange/codereview
The following is a daytime client written in C that uses Tor to connect to a given daytime server. It assumes a Tor daemon is running on the system and that Tor can be reached via a specified UNIX domain socket. This uses the SOCKS5 protocol to talk to Tor, and then uses the daytime protocol to display the current date...
stackexchange/codereview
I'm wondering how this code could be improved. I especially don't like the use of mutable Buffer but not sure what the best way to get it out cleanly. def find(service: Service): Traversable[Long] = { def loop(lastId: Option[Long]) (acc: mutable.Buffer[Long]) (quota: Int): Traversable[...
stackexchange/codereview
I have some code that needs to branch depending on if a value from a database is absent. Essentially our database contains some key value pairs from a dictionary. If the key is absent from a set, we should append zero as the value for that key. Otherwise, we should append the value from the database. values = [] known_...
stackexchange/codereview
I have a simple Model class that represents a calculator. Header file: @class MMCalculator; @protocol MMCalculatorDelegate <NSObject> @required - (void)mmCalculator:(MMCalculator *)mmCalulatorFinishedCalculatingValues; @end @interface MMCalculator : NSObject @property (nonatomic, weak) id <MMCalculatorDelegate> de...
stackexchange/codereview
I am currenly contributing to a Chat-Bot to be used across the whole SE-Network's chat which is implemented in Java 8. This bot is supposed to have commands. These commands again are supposed to be as flexible as possible, and based on chat messages. To allow easy and extensible implementation of arbitrary commands I h...
stackexchange/codereview
Could you please review the following code, and point out how I can make it cleaner, more idiomatic and easier to understand? module Cabbage ( solve ) where data Place = Here | There deriving (Eq, Show) data Pos = Pos { cabb :: Place , goat :: Place , wolf :: Place , fa...
stackexchange/codereview
I have a list of Workshops, each having open days (Monday, Tuesday etc.) and open time and close time (which will be same for each day). Now, Based on the current time, I need to find out next 7 days available slots. A slot is of 2 hour and is available if any of the workshop is open in that 2 hour time. The first slot...
stackexchange/codereview
I am trying to create a horizontal accordion using jQuery. The code works fine, but I just want to know if my approach is correct and if there are any improvements I could make to the existing code. $(document).ready(function () { $("ul li").children(".Acc_Content").animate({ width: '0px' },{ duration: 1000, queue: f...
stackexchange/codereview
I am building a website that uses Amazon S3 to host its image (and other) files. I require that images displayed on the website look like they come from my site and not from Amazon (so we are talking on the request/response level). What I have done is created a controller which all these files will pass through. The ...
stackexchange/codereview
I've gotten fed up of writing boilerplate code for managing Ajax calls, and this is the manager class I've come up with The concept is that it standardizes the interface for RESTful calls, prevents duplicate calls from firing via a request key, also simplifies waiting for a call to complete. function AjaxManager() { ...
stackexchange/codereview
I was tasked with this assignment with almost no time and I cannot stand up a new environment to test this. The risk is pretty high with what is the request is for so I'm asking for as much peer and code review as I can get. I'm tasked to check all the web.configs that have a certain DB Server and change it to a new va...
stackexchange/codereview
I have been playing around with numpy and matplotlib. My little project was to create a scatter plot ranging from -1 to 1 on both X and Y, but where the shading is done with the XOR scheme. The following is the code that I have implemented (it is in a cell of a jupyter notebook, hence the trailing ; after plt.scatter):...
stackexchange/codereview
This code works as follows : It accepts number of test case T. For each test case, it accepts length of sequence of integers N and the sequence (or list) itself L. The goal is to sort the list by checking every three consecutive elements, but only comparing the ends. L[i] and L[i+2]. If the right side is less than left...
stackexchange/codereview
The goal of this function is to an invert an income tax function. That is, given the tax paid and the financial year, the function should return the taxable income for that year. I would prefer to invert the income tax function rather than create a new function (so that changes to the income tax function will not requi...
stackexchange/codereview
I'm developing a web app that will be used privately by a company (no need for SEO and old browsers support). I made some interactive components (calendar, file manager, etc) that I am not sure if I implemented them properly. I use the simplest of them (contact picker) as an example here. I'm wondering if I should make...
stackexchange/codereview
I am trying to create all possible character combinations of a given word. For example, “laptop” will include the following possible combinations: l la lap lapt lapto laptop lp lpa lpat lpato lpatop Here is what I have tried: #!/usr/bin/env python import argparse import sys def parse_args(argv): """parsing argum...
stackexchange/codereview
Similar to the previous post Brainfuck Interpreter: Slower than a Snail?, it runs BF in java. The only difference is that the converter will convert the BF code into a compilable and fairly readable Java code, and run it. Example: BF code: ++++++++++[>++++++++++<-]> Initialize 100 (number of times to perform FizzBuzz)...
stackexchange/codereview
I have a project where the user supplies a date, time, and timezone, and my code will calculate a bunch of coordinates on the Earth. There are four sets of coordinates setA, setB, setC, setD. Coordinates setA and setB make up a great circle around the Earth. Likewise for coordinates setC and setD. The user is intereste...
stackexchange/codereview
The code does the following: Gets an array of objects and filters them according to some properties Returns the array of objects with the filtered data I'm using the following code which is working and I wonder if there is a way to write it better. By the way, I can use LodashJS if it's helpful here. filterNullUndefi...
stackexchange/codereview
This is a remote validation method for a registration form, fired when the user enters an email address. It checks that the domain portion exists in a given list of valid domains, and then also checks the email address has not already been registered. [AllowAnonymous] [AcceptVerbs("Get", "Post")] public asy...
stackexchange/codereview
I've created some custom code that will capture how long a user spent viewing a picture. The timer will stop when the user clicks or escapes from the fancybox view. Is there an alternate way for me to implement this functionality without using the counterStop setInterval() variable? The specific reason why I added an...
stackexchange/codereview
Description: Design a book library which maintains the book inventory. The library should allow an user to favorite/un-favorite book. The library should allow an user to rent a book for a given period of time, no other user can rent the same book for overlapping period. There can be multiple copies of a book. At presen...
stackexchange/codereview
This is a follow-up to Extracting lines from a bytearray ; I got a pretty good answer to the narrow question I asked there, but was invited to show more of the code in case there was a simpler way to solve the larger problem. So here's my entire module. Note that the use of PollSelector instead of DefaultSelector is ...
stackexchange/codereview
I've tried to implement merge sort in c with varying degrees of success, one was correctly sorting the array but leaking memory, one was neither sorting the array and leaking memory. The following was an attempt at implementing the algorithm again with these points in mind: Memory must be freed in the scope it was all...
stackexchange/codereview
In this code, I generate the coordinates of a tube made of multiple rings. Finally, I write those x,y,z coordinates in a .csv file. I want to simplify this code (maybe using a for loop?). import numpy as np import matplotlib.pyplot as plt bLength=1.6 numPoints=10 radius = bLength*numPoints / (2 * np.pi) theta = np.lin...
stackexchange/codereview
I made the following class to handle 2D animation through GIF images. This is made using JME 3.1, Java 8 and this GIF library. Is what I'm doing optimal? Are there already other available libraries or methods that do this? public class Animation2D { private final GifDecoder decoder = new GifDecoder(); private ...
stackexchange/codereview
Short (Non-Explanatory) Summary of Code I just started learning Python a month or 2 ago, and this (small) 955 line mess is what I've worked on since summer started in June. I am basing it on Dungeons and Dragons, and so far, the coding has gone relatively smooth. I used Enthought Canopy to code this, as it allows me to...
stackexchange/codereview
This java answer made me wonder whether it would be possible to implement the builder pattern in C++ in a way that checks at compile-time whether all necessary members of the constructed object are actually set before the object is constructed. This is what I came up with: struct Foo { int x_; int y_; int z...
stackexchange/codereview
WeatherForecastRequest is only simple HTTP parameters wrapper. It is using to get forecast from the openweathermap. At first here is utility class (used to simplify actions to post http request, receive response from server and convert it to String): // import packages from org.apache.http.*** public class HttpRequest...
stackexchange/codereview
Learn You a Haskell shows the lines function: It takes a string and returns every line of that string in a separate list. Example: >lines' "HELLO\nWORLD\nHOWAREYOU" ["HELLO","WORLD","HOWAREYOU"] Here's my implementation: lines' :: String -> [String] lines' [] = [] lines' xs = lines'' xs [] where lines...
stackexchange/codereview
I've been learning Java for 4 weeks now twice a week and I wanted to test myself to see what I could do. I'd love to see what you think and how I can make it better. public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); char a1 = ' '; char a2 = ' '; char a3 = ' '; char...
stackexchange/codereview