instruction
stringlengths
71
71.9k
Here is the implementation of interface Dictionary using chained hash table class HashTableChained. Despite item 22* saying Favour static member classes over non static in Effective Java, I used non static member class DListNode in class DblyLinkList, because any instance of the DListNode class MUST be associated wit...
We are using images from Wikimedia commons for some of Cardshifter's game artwork. I selected some art for each card to make a .jpg file to use in the game clients, and added a URL to the original file as a comment for reference. This is what one card looks like: (with our DSL made from Groovy) // https://en.wikipedia....
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...
How can I improve this code and avoid crutch? Can I use a case operator? public bool Crutch; public void Resize(SizeChangedEventArgs input) { if (input.NewSize.Width < 450 && Crutch) { if (!ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled) { ...
I'm working with Codeigniter most of the time (about one and a half year now) and I came across many form validation code flows. Here are my best two selected shots which I created for a client recently. I only care about model and controller, views do not need to be reviewed. Features of both code: Validation for for...
I started to teach myself Haskell recently. Here is some code I wrote to convert a roman numeral into an arabic numeral: import Control.Arrow ((>>>)) import Data.Maybe (fromJust) fromRoman :: String -> Int fromRoman = translateFromRoman >>> applyNegationRule >>> sum translateFromRoman :: String -> [Int] translateFrom...
I'm new to JS and am trying to write a perfectly clean source code. I'm using gulp to concatenate and minify my files, as well as removing comments. So the end result will always be the same in production environment: a single line without spaces. But for a dev environment, I'm trying to achieve clean code. I'm buildin...
This script shows the number of contracts for persons. Table Contract has more than 82008 records and Candidate has about 7978. Could you please suggest improvements for this script? select ISNULL(CON.ContractCount, 0) , CAN.PersoonName , ... /* some fields from table Candidate (more than 25) */ from Candid...
This code is part of an application page, which lets user select existing or add new members, For email and Username it needs to call web services to see if they already exists then validate respectively according to business logic. I believe this code has a lot of potential to be improved. Please note this is part of ...
I wrote a Haskell program to solve the N-queens problem by bruteforce. It works and I find it reasonably readable But it is pretty slow: 5 seconds for one solution of 8 queens. 1 minute for one solution for 9 queens. Crash for 10 queens. I fear that allFalseOneTrue gives memory problems as it uses permutations. I wo...
Currently, I have a big for..loop with many if..else inside the loop. I just wonder is there any design pattern or other approach to reduce the long code inside the for..loop. Thank in advance. foreach ($workingTimes as $hour => $minutes) { foreach ($minutes as $shift) { $isBookable = $this->isBookabe($hour...
This code inserts data into the database successfully. I was concerned about whether it is a considered good practise to go about inserting data into the database in this way. Is there something I am not considering? function insertTest(){ global $db; $field_names = array("id", "first_name", "last_name", "...
I have this code that I am using to delete all records from an entity. The question is can it be done better or is already the best? func deleteIncidents() { let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let context: NSManagedObjectContext = appDel.managedObjectContex...
I have created a directive for common form fields shared across all the forms in a large AngularJS app I am re-factoring. The app has lots of forms for various data models (user, owners, victims, suppliers, etc). A lot of the forms for these data models contain an address section which is the same format throughout th...
I have finished my first project using ASP.NET MVC. I did not have to wait long to realise I have essentially violated all possible codes of good programming. Well, experience comes with practice. One of the styles I completely missed was Dependency Injection Principle. It was far too late I could re-write the project ...
This is working, but I want to know if is this a place where IEnumerable can be used? public static int LongerThanStingCompair(string s, int n) { int counter = 0; // splits based on nextLine break var sCount = s.Split('\n'); // Cast to list sCount.ToList(); foreach (...
I was reviewing some WPF code I've written in C# last year. The scenario is the following: I've got a usercontrol that show usermessages and it's docked in the bottom of the application's workspace I've got a ConcurrentQueue that receives message via a IMessageMediator (from Catel, but's irrilevant how data are pushed...
So here's my attempt at the September community challenge, making an elevator handling system. I'm not really very familiar with OOP, so I'm particularly looking to get feedback on that part of the script even if you're unfamiliar with Python. I'm fairly certain there's times I've mishandled abstraction and what class ...
I developed a Kuku Kube game for iOS. Each time I choose a correct different color tile, it will increase a number of tile quantity 2x2 3x3...10x10. How to optimise the code each time the tile increase that auto fit on ip4 to ip6 Plus? I think it can not use auto layout to set for the size. - (void)setSizeforTile { ...
A recent Mandelbrot question (Hi @EBrown) in C# inspired me to build my own using the Java 8 parallel streams to implement the parallelism that's useful for computing each pixel value. The intention is to incorporate this in to a graphical interface that allows you to navigate and zoom in on the Mandelbrot set. To do t...
The application listens for OP_RETURN messages on the Bitcoin blockchain and prints them to standard output. OP_RETURN is a custom transaction locking script that can store data, but nothing beyond that. It's used for experimental use cases such as proofofexistence.com and coinprism.com. I would like some critical f...
I've been given the following task: Given N rectangles with edges parallel to axis, calculate the area of the union of all rectangles. The input and output are files specified in program arguments. Input is represented by N lines with 4 numbers separated by spaces, defining 2 opposite vertices of the rectangle. Output...
This code defines functions to cipher text with both mono-alphetic (Caesar) ciphers and poly-alphabetic ciphers. I also define a shortcut for rot13. I like this code and I think it is easy to read, but code is never perfect so I ask you for improvements. import Data.Char (toLower) alphabet :: String alphabet = ['a'..'...
This works fine so far, but I am looking for some advice as to how to better write this. My goal is to learn and incorporate current/latest C++ practices, and become a better programmer overall. #include "HTTPRequest.h" /* This function initalized Winsock */ bool HTTPRequest::InitWinsock() { WSADATA WsaDat; ...
I am trying to design a DSL for writing C. Here is my code as a GitHub gist (Github does not allow me to have slashes in the filenames so I have used underscores instead). It depends on packages free and process. My goal is to make the DSL low level enough that one can reasonably predict the output code, and convenient...
This is a follow-up to this question. I've refactored my previous debugging decorator, and added a couple new features, and changed a few things. Here's a complete list of things that have changed: There is only one decorator, Debug, and it now supports functions, and class methods. Each debug message is prefixed wit...
I want to arrange async server-client communication with websockets and vanilla flux architecture. There is an excellent article about "Async Server-Side Communication with the Flux Architecture". I gonna implement it analogue with SockJS and ES6 promises: ActionCreator.js - it's the same but moved to ES6 import * as c...
I am trying to build a tree similar to this one : 1 / \ 2 3 /|\ 4 5 6 / 7 With that tree, I must be able to get all ancestors for each leaf. In this example, this would be : 7 -> [4, 2, 1] 6 -> [2, 1] 5 -> [2, 1] 3 -> [1] To build that tree, I can only use an unknown number of pairs of parent-c...
This animation makes my fans spin up after several seconds, and it seems to have a sub-par framerate. I am trying to understand why, and optimize its performance. Codepen The animation function (this is the main part of the code): function animate() { t++ ctx.clearRect(0, 0, c.width, c.height); for (var i ...
I'm looking for a way to optimize this piece of code in Python. all_users holds all the Twitter users and friends_ids is an array of IDs. g = Graph(directed=True) all_users = users.find({}, { 'id_str' : 1, 'friends_ids' : 1}) # This is from MongoDb names = [] edges = [] print 'Processing first 1000 batch' for idx, us...
How can I maybe do some loop that will compress the amount of JavaScript/jQuery I need to use. I have a function s3episodesChange() linked to a <select> tag. This <select> tag has a few different selectable values that change style properties of various different <button> tags. All it is doing is showing the appropriat...
I wrote this working code to create a linked list of a given length and print each node's values. #include <stdlib.h> //NULL #include <stdio.h> //printf typedef struct Node { int val; struct Node* next; } node; node* make_ll(int len){ node* head = malloc(sizeof(node)); node* cur = head; for (int ...
This is (the significant) part of an implementation of a logging mechanism for recording events in a real-time control system. The basic requirements are: No dynamic memory on either side (producers or consumer), Lock-free variable length event entries strictly sequential timestamps multi-processor safe tolerant of o...
I have made a program in Python to do a filter of log files from a server. What I would like is some guidance on how this code could be optimized, streamlined or 'short-handed' so my 'pythonic' programming becomes better. I don't program for work, I do it on a requirement basis so I'm not good by any means. Requiremen...
This converts from character representation of integers to their decimal value: def chrtodec(str): dec = 0 base = ord('0') for chr in str: dec = dec * 10 + ord(chr) - base return dec For example: "123" -> 123
Similar to my recently asked question: Style-changing handler for an HTML drop-down box How can I compress down JS and almost automate it? I tried changing up the old questions answer a bit but never could get it working as i'm very new to JS I mainly do PHP. So I just need the following JS compressed and automated as ...
@chux pointed out that my attempted solution contained several problems. Since I screwed that up so badly, I figure that I should put my revised solution up for review. #include <stdio.h> #include <time.h> /** * The current year (number of years since 1900) */ static int this_year(void) { time_t now = time(NULL...
I wrote a numbers-to-words converter for English, then tried to adapt the code to work for French. I'm wondering mainly whether any simplifications are possible. In English English is relatively straightforward: english :: Int -> String english n | n == 0 = "zero" | n < 0 = "negative " ++ (english (-n)) | ...
I need to dynamically call a stored procedures from my repository, and here is a my implementation: public void ExecProcedure(string name, Dictionary<string, string> param = null) { List<object> sqlParametesList = new List<object>(); try { if (param !...
Sonar complains that I have too many return statements. How can I reduce the return statement count nicely? public int compare(Sku o1, Sku o2) { if (o1 == null) { return (o2 == null) ? 0 : 1; } else if (o2 == null) { return -1; } if (o1.getSkuNumber() == null) { return o2.getSku...
I want to arrange async server-client communication with websockets and vanilla flux architecture. There is an excellent article about "Async Server-Side Communication with the Flux Architecture". I gonna implement it analogue with SockJS and ES6 promises: TodoActionCreator.js import { dispatchAsync } from '../AppDispa...
I am building a wrapper around the sharp image library. The usage revolves around chaining tasks. But I wish to execute it by just passing in a config. An example of what I am currently doing: var execute = function ( obj, task ) { var methodName = task[0]; var passedValue = task[1]; return obj[ methodNam...
An array is bitonic if it is composed of an increasing sequence of integers followed immediately by a decreasing sequence of integers. Write a program that, given a bitonic array of N distinct integer values, determines whether a given integer is in the array. I have divided the problem in two sub-problems: Find the...
Is there any way I can make this FizzBuzz better? toFizz :: Int -> String toFizz x = case (mod x 3, mod x 5) of (0, 0) -> "FizzBuzz" (0, _) -> "Fizz" (_, 0) -> "Buzz" (_) -> show x main :: IO() main = mapM_ (print . toFizz) [1..100]
This question is related to my question on Stack Overflow earlier today. After getting suggestions on using the PreparedStatement from Java I changed my code a little. EDIT: In my original question on Stack Overflow I attempted to process the query in a very messy way, see this short excerpt: String sqlQuerry = "IN...
Here is my attempt at solving Project Euler problem 3. It works for test numbers up to 9 digits long, but overflows when I input the real 12-digit behemoth. I've looked at other methods of solution, but I wanted to challenge myself to code one that doesn't search with unnecessary numbers - only primes - and never any o...
I have an application in which a user makes a change, and when they click Save they will be prompted to confirm, and the appropriate REST call will be made if they agree. The intial call to Save() returns a promise that is fulfilled if the call returned successfully, or rejected if there was an error or the user cancel...
I have made some adjustments to some code that you can see on this thread: Read daily files and concatenate them I would like to make some further refinements and make sure I am on the right track organize some of my files better. I added some functions and made some other changes to prevent errors and make my code eas...
I have a large text file (~2GB) full of data. The data (sample below) gives an x, y, z coordinate, and a corresponding result on each line (there is other stuff but I don't care about it). The single large text file is too large to be useful, so I want to split it into several smaller files. However, I want each file...
Lately I've been working on adding Scenarios to my city building game. I wanted to create custom terrains for some of the different scenarios (such as a chain of islands, or a volcano). I decided that the simplest solution was to try to use topographic images to create an array of integers that could then be converte...
I'm coding a basic video upload system for a client. The uploaded videos will live on the page using the HTML5 video element. Essentially what I've done is call the following PHP script asynchronously from the upload page when the video is uploaded (the upload page, meanwhile, displays a message that their video is con...
I wrote this for an SO question on formatting numbers to specific quantities of significant figures (after all, reinventing-the-wheel), anyway, all critiques welcome. It's pretty easy to use, FormatSignificantFigures(0.123, 2) should return 0.12; FormatSignificantFigures(0.123, 5) should return 0.12300; FormatSignifica...
I created a bunch of small and mostly internal WPF applications for my company - usually for some file manipulation etc. For these programs, I would like to start collecting user info - who uses them, how often, most importantly - which version is used. It's partly for my personal skill development, but I also want to ...
I am trying to learn how to design and implement a layered Java web application with a presentation layer, service layer and the DAO layer. I have used the Struts 1.3 framework with Java JDK 1.6 for the below explained sample project. Questions: How GOOD or BAD is the below implementation of the layered web applicatio...
I created a form that formats phone numbers, allows only allowable keys to be pressed, and converts a lettered entry into its corresponding phone keypad number. Is there some cleanup or better coding that can be done? There is no business need for international phone numbers as it is a local business. function pageLoad...
Here is a little game modeled after adventure that I have been working on. The code initializes a set of lists. It sets a current location randomly generated. The user is tasked with either incrementing the index or de-incrementing the index (moving up and down the avenue). At each location there is a store which they ...
I'm pretty new, but I'm always looking for different/better ways to solve these problems as it helps me understand it better and hopefully will make me better programmer. Feel free to point out any mistakes or industry "dont's" as well. #include <cstdio> using namespace std; //Function Prototypes void deleteDupes(char...
You have n items, each one of those has a certain value, represented here as an integer. How do you give to two persons the most similar value? No comment from me here as my code already contains much documentation. from itertools import combinations, chain import doctest def all_subsets(lst): """ Returns ...
I've become interested prime factorization since solving Project Euler problem 3 (finding the largest prime factor of 600851475143). Learning here that initializing lists with many elements to later prune them is the computational equivalent of swimming with bricks, I challenged myself to code a function that returns a...
This project is pretty much like a 2D gravity simulator. You click and it creates a circle that attracts other circles. The result of a collision is a bigger circle that is a sum of the masses. If you don't know what I'm talking about, here's a gif: The game was made using CreateJS, but you don't need to know CreateJS...
This algorithm runs in \$O(n!)\$ time and I wish I could make this a bit faster for larger elements. Is there a better approach to solving the parentheses problem in shorter time? import java.util.ArrayList; import java.util.Scanner; public class Main { private static ArrayList<String> pathPermutations = new Arra...
Now I have this fluent API for creating random integer arrays. I can say that I want an array of particular length, having a particular minimum/maximum values and using a particular (or default) java.util.Random. See what I have: FluentArrays.java: package net.coderodde.util; import java.util.Arrays; import java.util...
I have a list of keywords and I want to count the number of records in a db which contain any one of these keywords. From each record, I want to consider only title and description to be checked. Is this correctly written? self.keyword_list = ['Buzz', 'Heard on the street', 'familiar with the development', 'familiar wi...
This is my code to print letter 'F' with nested loop 2d array. Are there changes that could be made in it to make it look better or more efficient? for (int i=0;i<=4;i++){ for(int j=0;j<=4;j++){ array[i][j]='*'; if ( array[1][1]=='*' || array[1][2]=='*' || array[1][3]=='*' || array[1...
One challenge I regularly face is how to name my service objects in Rails. I like the advice in this blog post on Gourmet Service Objects, a service object performs one action. It holds the business logic to perform that action. For example: # app/services/accept_invite.rb class AcceptInvite def self.call(invite, us...
I use the following structure in a web service where performance is critical. It is used for making joins between domain data objects, the key is made of two integers. The idea is to fit the two 32 bits integer in a long (64 bits). Before using that structure, I used Tuple<int, int> which was really slower. Is there an...
I'm trying to reproduce in Lua the mIRC scripting manipulating tokens function: local function tokenize(C, text) local char = string.format("%c", C) local t = {} for w in string.gmatch(tostring(text), "[^"..char.."]+") do w = tonumber(w) or tostring(w) table.insert(t,w) end return t end lo...
I tried writing a prime sieve that grows as needed. I've only just started learning C++ so any feedback on idioms is extra welcome! The header: #ifndef prime_sieve_h__ #define prime_sieve_h__ #include <vector> class prime_sieve { private: std::vector<bool> prime; int upto; void size_up(int n); publi...
This is my ugly code which needs to sort my data. I'm not really familiar with C# since actually I'm a Java programmer. How could this code be rewritten without loosing performance? I know I could use reflection, but it is bad for performance. sortings is a list of the fields that have to be sorted and if it has to be ...
Write a function that returns an array of integers with 1000 elements containing the values 1 to 1000 in random order. No number can be repeated or omitted.Your answer should show good programming style, technique and attention to accuracy and performance. Hint: use Random rnd=new Random() to create a new instan...
Most Python "duplicate file finder" scripts I found do a brute-force of calculating the hashes of all files under a directory. So, I wrote my own -- hopefully faster -- script to kind of do things more intelligently. Basically, it first searches for files of exact same size, then it compares only N bytes at the head an...
I have an array that might be either one-dimensional, two-dimension, or three-dimensional. I'm wanting to check to see if all values in a given direction are constant. Here are 3 functions: # Check to see if all values in the first dimension are equal ...
I've always wanted to be able to steer stream indentation, so that I could write code like this: /// This probably has to be called once for every program: // http://stackoverflow.com/questions/26387054/how-can-i-use-stdimbue-to-set-the-locale-for-stdwcout std::ios_base::sync_with_stdio(false); std::cout << "I want to ...
I've been working on this elevator program for quite some time now and finally finished it and made it work and I'm pretty proud of myself, but I'd like to see ways how to refactor my code so I can learn for the future. By refactoring I mean, making the code look better, maybe by using less lines of codes. public class...
I was originally going to write this intro as just being the bare-bones "here's my problem, here are some ideas, what do you recommend" format (which I am still going to follow, mind you), but I've decided to also add some backstory to it. In high school I would write inefficient programs that generated mathematically ...
Currently, the code will generate a range of natural numbers from 1 to N and store it in a list. Then the program will iterate through that list, marking each multiple of a prime as 0 and storing each prime in a secondary list. This is a translation of a TI-Basic program, shown here, so the same description still app...
I'm writing an AD Termination script for work. I'm new to PowerShell and was wondering if multiple commands within PowerShell switch statement is okay to do: # Switch statement to start here $switchTitle = "Terminate User" $confirmMessage = "Are you sure that " + $fullName + " is the user that you want to terminate?" ...
I've been trying to learn Haskell on and off for a couple years. I had a project for building a parallel web scraper, and I figured I'd try to use Haskell for it. Here's the part used to schedule tasks: basically, it opens a Chan that can be used to send jobs, which is simply an IO action with the time when it should b...
I'm trying to write a HTTP Request library for practice with Sockets and C++ in general. I created a seperate function to setup the struct needed to Connect() however it is now breaking and I cant seem to figure out why even with a debugger. Also looking for any code optimization I can be doing better. #include <winsoc...
I had a challenge a while back from a friend to try and produce the fastest possible program to compute A(3,16), where A is the Ackermann function. He wrote it in Java, and it took ~4.4 seconds. The below (very ugly) Haskell program that I wrote took ~1.7 seconds: {-# LANGUAGE BangPatterns #-} import Data.Ma...
I am kind of new to Java and I have tried making a simple calculator. This lets you do different calculations in a row until you type done then you get the answer. It works as I expected but I was just wondering if I could get some feedback on it and how I can improve on it or what better approaches I could have taken....
I'm creating a new data type, with the intention of overloading the arithmetic operators. It's for Galois Field arithmetic. The obvious thing to do is create a class, the instances of which will be the variables. There's precious little doc, the maths is a bit agricultural, incomplete and fragile at the moment, it migh...
Breeding like rabbits Write a function answer(str_S) which, given the base-10 string representation of an integer \$S\$, returns the largest n such that \$R(n) = S\$. Return the answer as a string in base-10 representation. If there is no such n, return "None". S will be a positive integer no greater than \$10^{...
I came across this interview question to find water accumulated between towers: You are given an input array whose each element represents the height of the tower. The width of every tower is 1. You pour water from the top. How much water is collected between the towers? Any suggestions? def test(x): if len(x) <=...
Three weeks ago I wrote the first version of my chess game in Python and shared on Code Review. Thanks to your suggestions, I improved my code. I would like to know if I am going in good direction with all this stuff. __author__ = 'Goldsmitd' class Condition: def range(x,y): return x > 8 and y > 8 def...
The following program is an updated version of this question, an implementation of the Vigenere cipher in C. It has been updated to take input from stdin and pipes, amongst other suggestions made by users answering the previous question, as well as having been significantly cleaned up. The program has been through seve...
This code is slightly platform dependent but should be pretty easy to port. The goal with this code was to create a circular buffer where the consumer could be limited to read-only access of the buffer (the test uses threads but it could be ported to processes fairly easily.) I think I probably made at least one mistak...
I know about apply, but I'm not sure how to write it so that it works for embedded for loops with if statements and so forth. It gets messy. I am a novice so if you can show me how to properly rewrite the following efficiently it should help a lot. This is an example of what the dataframe inFile() should look like. In ...
I'm writing a program that takes an input image, and generates a set of unique colors, and repaints the image using only those colors. It takes a long time, and I'm hoping to improve the running time. It's on GitHub, if you want more context. This is an example of the output, running from left to right: This is the ma...
I work in a Windows environment where Scheduled Tasks have never been documented or kept up with, leaving us with about 150 servers that have a random smattering of tasks. I am attempting to construct something that will query specific information about these tasks and output them in a pretty format that I can sort thr...
In a C++ program, I have the following function to find the length of the longest common prefix between to char arrays a and b. String b is guaranteed to be shorter than string a. Is there a faster char array comparison code (for example, with some library function)? I wish to optimize this code for speed. long len_co...
I picked up python again, and I am proud with what I have without using if/elif statements throughout the whole thing. I have modified this couple of times, since I kept asking how could I make it better or more organized. My biggest complaint is using the if/elif at the bottom, for some reason when I use. func = optio...
I would like some insight on this function for sanitising user submitted data into a contact form. No HTML content or anything, just plain text. Are there any vulnerabilities here that I'm missing? Am I ok to use the flag FILTER_FLAG_NO_ENCODE_QUOTES on the subject line? I'm not sure if quotes are safe to submit. I'm l...
I made this C++ doubly circular linked list implementation and it seems to work right, handle everything well, and not have any errors. However, I've been working with it for a while and would like some fresh eyes to take a look and see if I am missing anything large or if my code contains any 'gotchas'. Side note: I ...
I made this C++ doubly linked list implementation and it seems to work right, handle everything well, and not have any errors. However, I've been working with it for a while and would like some fresh eyes to take a look and see if I am missing anything large or if my code contains any 'gotchas'. Side note: I ran valgri...
I wrote a little library for myself: implementing a generic finite state machine. I will be using this library in class assignments. I clearly have little understanding of C++ templates because most changes I make break it and take around 30 minutes to debug each. So I would like some review especially regarding my use...
I am trying to read a sequence of random characters, integers and symbols from the standard inputstream, split it into 3 separate arrays (uppercase, lowercase and numeric) and print them in that order using standard Java API and JDK7. Is there any other(better) way of dong the same? BufferedReader bufferedReader = new ...
I'm looking for comments on the use of decorators for the following problem (validating initial guesses for bracketing rootfinding methods), as well as any other comments you might have on the design below. def bracketing(rootfinder): def wrapper(func, x0, x1, *args, **kwargs): func_x0, func_x1 = func(x0), ...
I wrote this in order to get a list of network interfaces on Linux. In the past, I have used publicly available methods from, say, ActiveState, which uses ioctl and was annoying to get working under Python 3. This version simply uses regular expressions on the output of ifconfig. The documentation style used here follo...
So, I did the CodeEval 'Longest Lines' problem and it works fine for any input data I can devise. When I upload it to CodeEval, it says it's wrong. Because it's a "moderate" problem, input data is not provided. After some System.out.println nonsense I got the test data, and my solution seems to work. Am I missing so...