instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have a struct of integers and I am trying to increase them based on rules. For example, rule_1 is the max limit that the first increase should reach. I want to change the order of additions based on priorities map (a=1,b=2,c=3), increase first "a", then "b", then "c". If I change the priorities (a=3,b=2,c=1), the ad...
stackexchange/codereview
(Inspired by this question) The digits of the cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permu...
stackexchange/codereview
In an interview I was asked to solve two JavaScript questions. I thought I did pretty well because I: Covered the edge cases Wrote comprehensive tests Documented the code using jsdoc The interviewer responded with this exact feedback: Overly Complex Solution, Strange Coding Conventions, Poorly Structured, Hard to ...
stackexchange/codereview
Write a function that a receives file name of a txt file, which contains unknown number of words of max length 10 each. Print the word with the most occurrences. Assume the input is correct and contains at least one word. Code #define MAX_CHARS 11 int mostFrequentWord(char* filename) { char ch; int i, j, k, occurr...
stackexchange/codereview
This is roughly what my data file looks like: # Monid U B V R I u g r i J Jerr H Herr K Kerr IRAC1 I1err IRAC2 I2err IRAC3 I3err IRAC4 I4err MIPS24 M24err SpT HaEW mem comp Mon-000001 99.999 99.999 21.427...
stackexchange/codereview
I've recently been assigned to write up a CSV writer with "as much flexibility" as possible concerning pretty much all (output stream, string fields with potential new line characters, separator collisions, etc. you name it...) No specification, no design guidelines, no nothing and I'm not expecting any any time soon (...
stackexchange/codereview
I have made a simple tic tac toe game and need help tweaking it to fit the bill of object oriented design. Any suggestions most welcome. I basically want it safer, and more "best practice-like" It is a game consisting of four classes, and I'm pretty happy with it as I am new to programming, but maybe it is worthless se...
stackexchange/codereview
Now that I have some infrastructure in place to test it (see my Battleship test framework and the updated GitHub project for the full context), I have finally written a non-trivial bombing strategy class for the May 2015 Community Challenge. The SmartRandom class guesses randomly until it gets a hit. It then checks fo...
stackexchange/codereview
I have a button that will validate the textbox for the service provider and the dropdown list for the locations. I have 3 tables: Locations, Service_Providers, and Service_Providers_Locations with a many-to-many relationship. But the tables that are affected are mainly Service_Providers and Service_Providers_Locations....
stackexchange/codereview
I have input of a string containing a single number (like: \$3\$) or a range (like: \$1-5\$). Sample input, all together, looks like: "1-5,3,15-16", and sample output for that input looks like "1,2,3,4,5,15". Output doesn't need to be sorted. I built something to parse this, but it's ugly. How can I improve this? from ...
stackexchange/codereview
I have written a basic REST endpoint in Ktor and would like some pointers. Application.kt @KtorExperimentalAPI @kotlin.jvm.JvmOverloads fun Application.module(testing: Boolean = false) { install(Authentication) install(ContentNegotiation) { gson {} } val materialRepository = MaterialRepository(...
stackexchange/codereview
I have some scripts to automate software install, apply some configurations and so on after installing a new system. I used to have them as bash scripts but it was generally a poor idea. I have rewritten first segment into a ruby script. I am generally happy about it. But three global variables for loggers are awful an...
stackexchange/codereview
I am trying to create a Fixed Point Arithmetics library : I call fixed point a number which has bits reserved for decimal part. Here is the code : #ifndef FIXEDPOINTNUMBER_HPP #define FIXEDPOINTNUMBER_HPP #include <type_traits> #include <cstdint> /////////////////////////////////////////////////////////// ///////////...
stackexchange/codereview
This class has a Log function that appends text to a log text file. It takes a format string and a variable amount of arguments, much like a printf sort of function. It then writes the formatted string with the interpolated arguments to the file. I wanted to know if there are any edge cases I might've missed, or if any...
stackexchange/codereview
In order to keep my coding skills fresh, I am going to be implementing a simple D20 RPG engine/library to use in creating a text-based game. I am coding in with IntelliJ using Java 8. I'm focusing on best practices, especially testing and documentation as I'd like to start contributing to Open Source projects. I finish...
stackexchange/codereview
I'm trying to speed up this code that loops over an entire spectrum range. It's using a Raspberry Pi, and a rtl-sdr dongle that covers up to around 1.7 GHz. My goal is to be sweep over that spectrum and gather data from it in a timely manner. #!bin/usr/python #gathers from the rtl library needed for this program from ...
stackexchange/codereview
I have folder1 that contains other folders (which may contain other folders etc). This process stops at some point where a folder contains only files, and some of them end with the string "img". I would like to write to a file for each line: the complete path of the file (if ends with, say "img") the immediate folde...
stackexchange/codereview
I wrote a function to implement a generalised version of binary search that can find the minimum or maximum index in a given sorted list that satisfies a provided predicate. My Code def xbinsearch(pred, lst, type = "min", default = None): """ * Finds the minimum or maximum index of a sorted list such t...
stackexchange/codereview
I have been trying to get the problem Quadrant Queries correct for a while now. Although my approach is an optimal one, I am getting a TLE on 3 test cases. Please help me optimize my approach so that I can pass all test cases for the problem. #include <iostream> #include <cstdlib> #include <cstring> #include <algorithm...
stackexchange/codereview
Hello I am making a code in C to find the value of the last sequence of palindromes of a specified size (d) and I need to optimize this code as it is for an exercise platform called URI Online Judge and is giving Time Limit exceeded. https://www.urionlinejudge.com.br/judge/en/problems/view/1686 Given a string s[1..N],...
stackexchange/codereview
I just implemented code to add two ints together as strings and I'm sure my method is inferior. I've looked up other methods too but I'd appreciate criticisms specific to my code. I really want to make sure I don't develop bad habits in C++ and I think leveraging the knowledge of brighter individuals than myself on thi...
stackexchange/codereview
A lucky number is defined as a positive integer whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. I need to check if a given number is evenly divisible by any lucky number or not. Now, suppose I want to add all Lucky Numbers under a g...
stackexchange/codereview
For practice, I tried implementing Bubble sort in Ruby. I wasn't very sure how nested for loops would look like in Ruby. Is this the 'right way' to do this in Ruby? I found this question, but it looks much more complicated with stacks. def bubble_sort(list) n = list.length n.downto(2) do |i| 0.upto(i-2) do |j| ...
stackexchange/codereview
I made this program to rename variables in json files, part of the functions rely on recursivity which i'm not confortable with so I would like some feedback on readability and performance. import configparser def seek_in_array(json_array, conversions): """seeks all data in a json array""" converted = [] ...
stackexchange/codereview
I'm new to Go and I completed the first challenge from Gophercises. Any feedback would be highly appreciated. There are some things that I am unsure of if they are made in an optimal way. Github repo Goroutines and channels in the quizList loop Better error logging for the cli portion The Shuffle function only works...
stackexchange/codereview
Need help with DRYing out my Sass... there is just so much repetition in here: .cta_foo { @include linear-gradient(#f69c28,#b75d00,#b75d00); text-shadow: -1px -1px 0 #b85e00; &:hover { @include linear-gradient(#FFAC41,#E77500,#E77500); } } .cta_bar { @include linear-gradient(#17b629,#0e831c,#0e831c); te...
stackexchange/codereview
The ElectricalEngine class responds to the horsepower message. Because efficiency is calculated in percent a programmer can mistakenly initialize it with an integer instead of a float. class ElectricalEngine attr_reader :volts, :current, :efficiency def initialize(volts, current, efficiency) @volts, @current, ...
stackexchange/codereview
I am not very experienced with T-SQL and feel this can be done better. The script changes ownership of all "user" (non-system) databases to sa. Usage of a dynamic SQL expression seems unavoidable to me. Could I at least iterate the table names in a more elegant way — imperative code looks like a code smell in a SQL scr...
stackexchange/codereview
This was part of an exercise from exercism.io. If you fancy, view the repo here. Given problem statement: Write a program which produces the lyrics to that beloved classic, that field-trip favorite: 99 Bottles of Beer on the Wall. Remove as much duplication as you possibly can. Optimize for readability, even if it m...
stackexchange/codereview
I'm writing a piece of JavaScript to make one or two ajax calls. There will always be one ajax call fired but it might be two based on cookie setting. If user is logged in then we call another service to get the data. I would want this to fire async that's why I didn't put the second ajax call in the callback of the fi...
stackexchange/codereview
This code performs 301 redirects based on the taxonomy terms associated with the node, as 301 redirects can adversely effect page load time. How could this be best optimized? <?php /** * Implementation of hook_init(). *calling this hook causes the code below to execute before the page is loaded */ ...
stackexchange/codereview
I stumbled upon a question on SO asking how to split a comma-separated string into individual values. Since it's been a while since I've had any good reason to write C I'd like to ask for some feedback. #include <stdio.h> #include <string.h> int main (int argc, const char * argv[]) { const char str[] ="coma sepa...
stackexchange/codereview
After receiving some good feedback on the previous question, I've refactored my database and have begun to refactor the associated code. As a result of implementing models for all tables in the database, it has become smoother to use Eloquence Builder instead of a custom class using PDO. Below find some of the changes ...
stackexchange/codereview
Below there is a function eating all strings and convert it to Unicode. It works fine. But is it the best way to do so? Is there maybe already an existing function for it? The reason was a German Windows version which prints German ä ö ü - error-messages which are retrieved from popen/communicate etc. There must have b...
stackexchange/codereview
I've created my first jQuery plugin, so please try to understand :) My plugin code looks like so: (function($) { $.fn.ajaxSelect = function(options) { var $this = this; //options var settings = $.extend({}, defaults, options); //disable select if ($.ui.selectmenu && settings.selectmenu && settings.d...
stackexchange/codereview
One of the tasks I find myself doing repeatedly is to filter the incoming inputs that will be stored in models. Examples of this include trimming, removing repeated or unnecessary pre/suffixes, commas or dashes in numbers, etc. This is similar to validation, but Laravel's built-in Validator does not appear to have this...
stackexchange/codereview
The macro below clears cells that do not match any cell in comparison to a range (a master list). It works on small file but is too slow to work for files with large ranges. Sub REMOVEINV() Application.Calculation = xlCalculationManual Application.ScreenUpdating =False Application.DisplayStatusBar =False Application....
stackexchange/codereview
I always been curious on how to build great application with proper routing to my controllers, but after seeing some sources of applications like Xenforo, Joomla, it seems completely different, and mostly I can't understand them. From my understanding the user sends a request to the web-server, the controller's job is...
stackexchange/codereview
I need to write a program that uses the Fibonacci Sequence to calculate a sum. The calculation requirement 1: Take the first n Fibonacci numbers (excluding F0) S1 = {F1, F2, F3 ..... , Fn} 2: Modulo each Fibonacci number by a positive value Q S2 = {A1, A2, A3 ..... , An} Where Ax = Fx % Q 3: Sort the number in...
stackexchange/codereview
I wrote a connect four game for two players, where each player uses the same keyboard. I programmed this solely in hopes of improving my skills. I'm open to and looking for any sort of feedback. Do the comments contain sufficient detail to understand the code? Are the functions separated into their individual mechanism...
stackexchange/codereview
Original Problem Short Summary: Given a \$M\$ possible characters all of which must be used at least once, find the number of possible combinations of length (exactly) \$N\$. The first input contains the number of cases, followed by pairs of M, N. Output is modulo 1000000007(\$10^9+7\$). Example Input: 4 1 1 ...
stackexchange/codereview
I'm working on a program that corrects all punctuation spacing in a String. Examples: // "Hello ,World" -> "Hello, World" // "9 :00 A .M ." -> "9:00 A.M." // "can 't even." -> "can't even." Here's how it works: My process is to first add a space between all punctuation and then remove any unnecessary spaces. T...
stackexchange/codereview
I want a cryptographically secure version of array_rand(). Is this it? /** * retrieve a random key from an array, using a cryptographically secure rng. * - it does the same as array_rand(), except that this one use a cryptographically secure rng. * - relatively speaking, it should be significantly slower and more me...
stackexchange/codereview
I have the following class for Quicksorting. import java.util.Random; public class QuickSorter { public static void main(String[] args) { Random random = new Random(); int[] randoms = new int[10000]; for(int i = 0; i < randoms.length; i++) randoms[i] = random.nextInt(10000); quickS...
stackexchange/codereview
I was thinking about using very basic bounded (preallocated) stack to keep track of my threads IDs in correct LIFO order. I was wondering if my implementation is thread safe: // we use maximum 8 workers size_t idle_ids_stack[8]; // position current write happening at std::atomic_uint_fast8_t idle_pos(0); // this funct...
stackexchange/codereview
This is a program to read and store the data from a Excel file (.xlsx) which is uploaded by users. Any better approach to reduce the usage of if-else to return the error message? How to design or construct a good coding pattern before I code? What kind of aspects I should pay more attention on ? Excel file uploaded b...
stackexchange/codereview
I have a File System. It is *supposed* to be laid out / used / added to in certain ways. This is a program to report on the *actual* state of the file system versus what it's supposed to be. In particular, pick out unexpected folders and (eventually) validate that Client Folder Names follow a particular convention. E...
stackexchange/codereview
I have a basic outline for the best way I can come up with to move a character through a basic text map. I want to implement this module in my simple text RPG. I know there has to be a better way to implement this code with less functions, and possibly with less print statements. Also I am not sure if this is a module ...
stackexchange/codereview
I wrote this code in C++ to convert an array to a binary tree. For instance, int nums[] = {7,5,9,1,7,3} to a binary tree (root-7, root's left child-5, root's right child-9...). ( here, I made a function named 'create_tree()' which only take one argument ) Is there any shorter way to do this? #include <iostream> #includ...
stackexchange/codereview
I'm learning Haskell, and I tried to do an exercise which it is an implementation of the Caesar Cipher method. The problem asks for cipher a text which it is in lower case and can contain characters from 'a' to 'z' without numbers, uppercase letters, symbols etc.., only lower case letters. If the letter it is in an ev...
stackexchange/codereview
I think there are some confusing and weird indentation problems in this WordPress file (single.php). Any suggestions on improving indentation and readability? <?php /** * The Template for displaying all single posts. * * @package WordPress * @subpackage Starkers * @since Starkers 3.0 */ get_header(); ?> <?php g...
stackexchange/codereview
This is a part of simple sfml C++ game, but I think neither the library nor the language is that much crucial here. I am mainly worried about the design. I have a class template ResourceHolder<Key, Resource> to hold one type of Resource such as texture or sound, inside a map. A key is usually an enum but can be anythin...
stackexchange/codereview
I recently started to learn C++ and came across this problem in a book "Object Oriented Programming in C++" by Robert Lafore. The author has a program in the book which creates a Parser. I found a problem with the original program in the book which breaks at one of the input expressions I am providing. Therefore I trie...
stackexchange/codereview
I am attempting to polyfill the broken character encoding system in javascript. For example, characters such as , have a length of 2 and are treated as 2 separate characters in regular expressions when they should have a length of 1 and be treated as a single character in regular expressions. This may not seem importan...
stackexchange/codereview
I have a Pub/Sub class that will call Notify() when published and that Notify() could take around 10 seconds, so I need to make sure that this does not block the UI. public static class NotificationService { private static Dictionary<string, INotification> Observers { get; } static NotificationService() { ...
stackexchange/codereview
I'm trying to implement a heap using list data structure. I'd also like to keep track of the position of elements in the list in order to enable easy deletion. My implementation involves looping through the entire list to update the positions after an insert/delete combo. I'm afraid this raises the time complexity from...
stackexchange/codereview
I am trying to create a web app (CMS) as part of my research project, and I use the code below to load modules into a page. Please review this code. public function LoadModule($module,$position){ if(file_exists('modules/'.$module.'.tpl')) { //todo: might have to get a better thing for this ! $...
stackexchange/codereview
This is a plugin I wrote a while ago and I'm trying to improve it. Is this the best practice for jQuery plugins? Should I use options for flexibility? The initial aim was to replicate the syntax for .fadeIn() in jQuery. Any pointers would be appreciated. /* AnimateCSS - CSS transitions instead of js */ (function ($, wi...
stackexchange/codereview
This is a file shredder utility that runs on Linux. It writes random bytes over the file contents, repeating this 48 times and calling sys_fsync after each pass to make sure data goes to disk. ; Description : A file shredder, it reads a dword from urandom then replaces ; the file contents with it,...
stackexchange/codereview
Question- My approach I noticed that the minimum of a row is when t=k-one of the numbers of that row. Suppose in the above sample case, t=4 which is 6-2. Since we have to find the minimum maximum testing all k-no will give the solution. Any tips to improve this technique as for cases where each number is unique and n...
stackexchange/codereview
I am a C# game developer currently learning C++ and this is my second big-ish project (the first one being a vector implementation). This time I opted for implementing a mot-a-mot any implementation based on the specifications of the ISO/IEC N4830 standard draft. My objective is to familiarize myself with the modern C+...
stackexchange/codereview
How well does this code limit security problems when uploading images to the server? <?php $filename = $_FILE['inputfile']['name']; $upload_path = 'images/'; //extract extension $ext = strtolower(substr($filename, strrpos($filename, '.') + 1)); // return mime type ala mimetype extension $finfo = finfo_open(FILEINFO_M...
stackexchange/codereview
I wrote a Java program that when its executable .jar is opened manually, it re-opens itself inside the operating system's shell console. The purpose of this is to have a C#-style console application where the user can enter commands, without the user needing to manually open the shell console and run the java -jar ... ...
stackexchange/codereview
In reviewing code in our application, I see a tension between what makes a convenient design for methods accessing database data versus coding to ensure that the JDBC resource objects are closed properly. An example problem: // Application.java: Singleton class for objects which want to execute SQL queries /** * Exec...
stackexchange/codereview
I wrote this method to upload a floor plan image: function upload_image($path, $file) { $errors = []; $ext = pathinfo($file["name"])['extension']; //randomly generate filename to avoid conflicts $filename = uniqid().'.'.$ext; if ($file["size"] > 2000000) { $errors[] = "The image cannot be ...
stackexchange/codereview
I have this code to get the current Timestamp and compute the last timestamp's difference with the current timestamp in minutes. I'm wondering if this can be optimized further for production. public static Timestamp getTimestamp() { java.util.Date date= new java.util.Date(); long time = date.getTime(); ...
stackexchange/codereview
The The Hardest Logic Puzzle Ever recently came to my attention: Three gods A, B, and C are called, in no particular order, True, False, and Random. True always speaks truly, False always speaks falsely, but whether Random speaks truly or falsely is a completely random matter. Your task is to determine the identities...
stackexchange/codereview
I have snippet that really look ugly but I don't know how to refactor it: if owner samples.each do |sample| sample_name = get_name(sample) # logical to get correct name serialized_sample = SampleSerializer::Level10.new(sample, 10).serializable_hash groups[sample_name] = groups[sample_name] == ni...
stackexchange/codereview
Suppose I have some expensive function expensive_computation which takes a long time to compute but it always returns the same value. I want to avoid paying the cost of computing this function because it may never be called. Here is my solution to this, is there a more obvious or clean way to do it? Or maybe even some ...
stackexchange/codereview
I was doing a JavaScript challenge to test myself and I succeeded in finding a solution but the code is very ugly. I was hoping to get some opinions on what a better solution would look like. The problem is this. We need to write, in Javascript, a function with signature f(input) that when called in the following wa...
stackexchange/codereview
You can find my original post here on SO. I was very surprised that I couldn't find a pre-coded function doing a mean square error between a signal (array A, size a) and a pattern (array B, size b<a) in a sliding window fashion. Thus I made one... and obviously it needs a lot of code improvement. I don't really know ho...
stackexchange/codereview
Problem Statement You are given a tree (a simple connected graph with no cycles). You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected component of the forest should contain an even number of vertices. To accomplish this, you will remove some edges from...
stackexchange/codereview
/* Convenient Objects Library Extender for PHP 7+ * ----------------------------------------------------------------------- * C-OLE is a container super extension for PHP 7+ * that is to make everything you thought difficult, * impossible, or completely outside the grasp of * PHPs language restrictions completely ...
stackexchange/codereview
I have an application which currently uses AJAX for CRUD operations on a simple Person object. The following script works fine, but I'm looking for some pointers on how to structure my code. Currently, I have four methods for CRUD operations, and I'll extend my person module as needed, but I was hoping to get an idea...
stackexchange/codereview
I've just downloaded a script and would like to use it as a contact form on my site. The problem is I'm a front-end dev with little knowledge of securing PHP code. So, could you please have a look and let me know if there are any glaring problems with security with this script that uses phpMailer to send? As you can se...
stackexchange/codereview
Here's my code for a consise node.js HTTP server. It does work as intended, but I'd like to ask if there's any glitch or to be improved. var httpServer = function(dir) { var component = require('http') .createServer(function(req, res) { var fs = require('fs'); var path =...
stackexchange/codereview
I'm looking for following kind of feedback: Firstly, is the use of a cursor an overkill here? Is there a simpler way to do what I'm doing in SQL? Could the script go terribly wrong? I have limited SQL experience, how does it look? Any standards that I'm not following? Bear in mind that this is a one-time script to be...
stackexchange/codereview
I have three methods in API running similar code snippets. For this reuse the code inserted a switch-case according to the API method. It's good practice that? I mean, this isn't a high coupling and low cohesion? There is another better way? API @ApiOperation(value = "Gerar permalinks de todos os arquivos com validaçã...
stackexchange/codereview
I am new to programming and I am trying to develop a machine learning approach for image segmentation (https://en.wikipedia.org/wiki/Image_segmentation) and here I want to evaluate the predicted (output) segmentation. In order to do this, I am using multiple (common) metrics (dice score, jacquard index, surface distanc...
stackexchange/codereview
From numbers from 1 to 100, count the numbers where the following equation is satisfied with 1 <= a <= 100, 1 <= b <= 100, and 1 <= c <= 100: $$a³ + b³ + c³$$ I have this: def has_power3(n): for i in range(1, n+1): for j in range(1, n+1): for k in range(1, n+1): if i**3 + j**3 ...
stackexchange/codereview
In this strstr implementation, I am basically skipping the already matched and checked characters with an if else condition. Is this a right way of implementing it? char *strstrImp(char *input, char *find) { if(*find=='\0') return input; if(*input=='\0') return NULL; char *start=input; ...
stackexchange/codereview
I'm currently working on a company management system as a university project, and I have to get my hands in java.sql. I have come to struggle with extracting a query result from a ResultSet object, as I find its usage is a bit complex. I have written this code to automatically extract all the entries of a ResultSet in ...
stackexchange/codereview
im trying to migrate my very large swift view controller to mvvm but it still feels very large, can you guys give me any advice What this controller does is simple it shows a UIView on which i can draw the buttons that I display are here to manage the lines that i have drawn on the canvas. For example to delete the las...
stackexchange/codereview
I need to extract the dimensions (width and height) of a jpeg file for inserting in an html document. According to the JPEG image compression FAQ, cautions against what's commonly out there, Some people have recommended just searching for the byte pair representing SOFn, without paying attention to the marker block ...
stackexchange/codereview
I am developing another bigger project, I want to try a simple DatingApp and currently I try to develop a Login and Registration Form. There is no special register / login button, the code will later decide wether email is registered (-> login) or not (-> register). But even though it's working I am not sure if I make ...
stackexchange/codereview
I have very little experience with cmake, this is really the first time I used it for a project. In the past I used some autotools and recently mostly bazel. I would appreciate some suggestions how to better structure the code. For example during compilation I noticed that the same targets get compiled multiple times, ...
stackexchange/codereview
I've got a method that needs to PUT data to a web API. Sometimes the connection fails, so I needed a way to do retries, but if the retries fail, I still need to capture the exception and re-throw it. I've got something that I "believe" is working, but I've got a stupid throw at the end. Is there a better, more concise ...
stackexchange/codereview
I gathered a lot of information in order to try to make my code as secure as possible, and I would like to know what I can do to improve more its security. (Sorry for my english if it's bad) What did I do: Only logged-in users will be able to upload images. If a user has uploaded more than 10 images in the last hour, ...
stackexchange/codereview
I had already posted a question about the one I am asking right now. To quickly revisit the scenarios: I am trying to generate reports which involve fetching data from a DB, writing data to a CSV file, and sending email. I am pulling data for all the reports in the same format since I wanted to keep the DAO layer and C...
stackexchange/codereview
I have a view which takes a DataPresenterStrategy instance to retrieve the proper text out of some data: public interface DataPresenterStrategy { String getDisplayString(Data data); String getUnit(); } public class DistanceStrategy implements DataPresenterStrategy { @Override public String getDispla...
stackexchange/codereview
I have a program doing a LOT of iteration (thousands to millions to hundreds of millions). It's starting to take quite a lot of time (few minutes, to a few days), and despite all my effort to optimize it, I'm still a bit stuck. Profile: using cProfile via console call ncalls tottime percall cumtime percall filen...
stackexchange/codereview
I've created some controller for handling clicked links statistics. Does this class meet Single Responsibility Principle? class StatisticsController { protected $statisticsQuery; public function __construct(StatisticsQuery $statisticsQuery) { $this->statisticsQuery = $statisticsQuery; } pu...
stackexchange/codereview
I am a beginner in python and I was wondering if the code for this program is nice and clean. The program works I was wondering how could i improve it. So this program asks for your 'username' and checks to see if your 'username' is in the 'banned users' list. If it is then it will 'log out' and won't let you comment. ...
stackexchange/codereview
I'm new to coding and this code pretty much goes to the extent of my current knowledge I'm looking for ways to improve this code. This code compiles and runs fine in Visual Studio 2013. I'm also using Windows 8.1 as my current OS for the computer I'm writing and compiling on. I'd like a review over anything and any err...
stackexchange/codereview
I have written an algorithm that generates a Fibonacci series to the \$Nth\$ number. The code below works fine, but as a beginner I know I must be writing pretty ugly code. For example I think it is probably not good practice to declare and initialize the variables where I have, but I am confused about what would be t...
stackexchange/codereview
After having showed a previous implementation of my "Resistance System", I decided that I was completely wrong about how I had been going about things. The system, as it had been presented, was completely erroneous in both theory and execution. I can admit that. Realizing this, I took a step back and realized that I co...
stackexchange/codereview
Rubberduck's latest (and greatest?) feature is a regex search/replace: This is the defining interface: public interface IRegexSearchReplace { List<RegexSearchResult> Find(string pattern, RegexSearchReplaceScope scope = RegexSearchReplaceScope.CurrentFile); void Replace(string searchPattern, string replaceValue...
stackexchange/codereview
Here is a wrapper to a MySQL connection. First I have a DatabaseController and then a DatabaseConnection. How I use this is shown below. using (var dbConnection = Program.DatabaseController.NewConnection) { } Here is the full code for both classes. internal sealed class DatabaseController { private readonly strin...
stackexchange/codereview
my code is for menu. In the exit case of the menu it must count how many times are used options 1 and 2. No matter how many times I choose 1 and 2, when I choose 3 it gives me 0 for counter1 and counter2 and I can't find out why. The code for passive class: public final class Service { private int x; pub...
stackexchange/codereview
The question is here. 100 people are standing in a circle with gun in their hands. 1 kills 2, 3 kills 4, 5 kills 6 and so on till we are left with only one person. Who will be the last person alive. Write code to implement this efficiently. Here is my Java implementation: public static void main(String[] args) throws...
stackexchange/codereview