instruction
stringlengths
71
71.9k
I've written some Python 3 code that computes the \$n\$-th prime. I implemented first a naive isprime function that looks for divisors of \$m\$ between \$2\$ and \$\lfloor \sqrt m \rfloor+1\$. Then a loop looks for primes and stops when the \$n\$th one is found. from math import sqrt def isprime(n): for i in range(...
Inspired by Sam's question (Brute-force string generator) and rolfl's really short version of the algorithm I started to experiment with a different approach and created one that seems to run a little bit faster (about 40-50ms for a string of length 4). As it doesn't really optimize the orginal algorithm but is a compl...
Problem Statement (from HackerRank) We have two arrays \$a\$ and \$b\$ of length \$N\$, initially all values equals to zero. We have \$Q\$ operations. Let's define three types of operations on this arrays: 1 l r c: Increase \$a_l, a_{l+1}, \ldots, a_r\$ by \$c\$. 2 l r c: Increase \$b_l, b_{l+1}, \ldots, b_r\$ by...
I'm trying to run a build scripts framework, so build scripts can be configured via yaml file tasks.yml: --- release: # This is a 'runner' or group of related tasks. They share common initialization needs config: repo: ci-repo # Configuration parameters can be set at runner level and overriden by nested tasks/s...
I've written a smaller version of 15 puzzle in C, using OpenGL 3.3 and freeglut. I've found a place you can play it online to get familiar. I'm new to OpenGL, so I have no idea if I'm doing this in the right way. Nevertheless, this game compiles and works as intended on my 64-bit HP COMPAQ laptop with Intel HD graphics...
Here's a simple snake game I implemented in Python, which works in a console. It's not complete yet (doesn't generate food yet, and no scoring or difficulty levels), but it works. I would be really grateful if you give me any suggestions on how I can improve my code. Note that I did some of the things I did in a reall...
A long time ago I found this question and asked about an algorithm here. My code is also available on GitHub. Given a self-balancing tree (AVL), code a method that returns the median. (Median: the numerical value separating the higher half of a data sample from the lower half. Example: if the series is \$2, 7, 4, ...
I have been playing around with the Io language, and this is my second toy, after the yes program that is just loop ("yes" printl) and on which not much review is possible, I wrote a FizzBuzz program. I like the shortness of it, but any improvement is welcome as I am very beginner in this programming language. toBuzzWo...
I have created a simple implementation of the bubble sort algorithm. I have tried to make it as efficient as possible by following pseudocode which I have provided below, making some slight modifications to suit my needs. The pseudocode: procedure bubbleSort( A : list of sortable items ) n = length(A) repeat ...
I have JSON data: var data = [ { dat: 'timestamp', val: 10 }, { dat: 'timestamp', val: 20}, (...)] Data contains objects with timestamp and value, can be more than one in month. I need to sum values from objects which have the same month and year. First I use each function to add additional field cat which contains ...
Is this the simplest way to write this? This code evaluates if a textbox value exceeds 20 characters, and then displays the proper message (essentially truncating the string and then adding an ellipses to the end.) I've tried using a tertiary operator but doesn't seem to work with appending data to an element as it ove...
So I'm very much a beginner to Java and Android programming. I've worked a lot more with Python so I might have some quirks from there bleeding into my code here. I'd like a particular focus on pointing out ways I'm approaching the language and any confusing style I might be employing. What the app does is pretty simp...
I program in C, and it's my favourite language. I've recently found Rust. I like their ideas. Sometimes looks like a weird mixture of C++ and Haskell, but overall it looks nice. The for loop in C is very flexible, and I truly miss them in Rust. Just look at my messy beginner Rust code below. Below that there is the equ...
I have the solution for the problem, but it is taking me 7 seconds to run on a large dataset. I am trying figure out a better way of doing this. It has to run in under 3 seconds. Problem Statement: There are N plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any ...
This is a Login Authentication / Sign-up Models for my class project in PHP. I would really appreciate criticisms and any suggestions to improve security, code quality, etc. Hashing.php class Hashing{ public static function getHashedPassword($username, $password, $regTime){ //Prepending Username and Appendi...
I used XML to control the theme of an InputMethod for Android. A theme in XML contains the color and the shape of keys. XML file <theme> <color name="FIRST_LINE_LETTER_COLOR" value="#263238"></color> <color name="SECOND_LINE_LETTER_COLOR" value="#263238"></color> <color name="THIRD_LINE_LETTER_COLOR" valu...
I have written a simple event emitter in Python, which allows subscribing to events and emitting events (along with monitoring events too). I'm rather new to Python, and would like some feedback on the overall style of my code (I tried to follow PEP 0008) as well as how it works. import inspect _DEFAULT = object() c...
This post goes over how I updated my 2048 merge function code from spaghetti code to being somewhat more readable. Spaghetti Old Code I incorporated a few techniques from pretty much all of your suggestions! I realized there were a lot of logical mistakes and redundancy in my code, like why append 0's over and over aga...
I have written code to add a node to the head of the list. Criticisms and feedback are welcome. typedef struct sList { void *data; struct sList *nextNode; }sList; sList *addNode2Head(sList *psList,void *data) { if(psList == NULL) psList = newNode(); else { psList = addHeadNode(psLis...
I have written a piece of code that notifies if something is added or removed from a folder location: from PyQt4 import QtGui from PyQt4 import QtCore import sys import os def xor(lst1, lst2): """ returns a tuple of items of item not in either of lists """ x = lst2 if len(lst2) > len(lst1) else lst1 y...
I'm starting out with learning how to program in Python and created a Hangman game. I think there is a lot of unnecessary code but I am not sure how to improve it. I wanted to avoid using global variables but was not sure how to save the random word (as every time I called it in another function, it would be a differen...
This is a C# WinForms program targeting .Net 4.5. I am using it for a movie organizer application that will contact sites like OMDB, MyApiFilms, etc. for data about the movies. At the main application level a new movie list needs to have its movies matched to their info, which means searching these sites via their API,...
I have that girl whose graph walk I want to intercept, but because I am not good at running algorithms in my head, I had to program my computer to do that for me. I would not consider the problem to be a problem in its own right, but can be thought of as an extension of the shortest path problem. Edit: I am not quite s...
I improved the code from my previous question. At this moment, the 3 entities have not yet a connection with each other. They should only be available for CRUD actions in a SQLite database. I would like to have a review of this basic CRUD application so I can improve and learn from your experience. The full code can be...
I have written a jQuery plugin (my first for a long time) that simply cycles through strings of text in a data attribute and uses setInterval to type it out - it's a common effect you've probably seen hundreds of times. I'm looking for a code review of the JavaScript/jQuery portion of the code mainly because a lot of ...
I've just wrote my first code, which is basically a calculator. Please rate it and suggest improvements (keeping in mind that I'm a beginner). import math #Returns the sum of num1 and num2 def add(num1, num2): return num1 + num2 import math #Returns the difference between num1 and num2 def sub(num1, num2): r...
I want to get the value of an integer from within a struct pointer. Simply: int cool = *(*(&(coolPtr->map)) + x); can this be simplified? The rest of the code is context. X being the index of the array. struct Cool { int map[5]; }; int value (Cool* coolPtr, int x) { return *(*(&(coolPtr->map)) + x); // Here ...
This code will print an arrow of asterisks, like: * ** *** **** *** ** * raisingAsterisks, decreasingAsterisks, arrow :: Int -> [String] raisingAsterisks n = take n $ iterate ('*' :) "*" decreasingAsterisks = reverse . raisingAsterisks arrow n = raisingAsterisks n ++ (tail (decreasingAsterisks n)) main :: IO() main ...
This code generates an animation that gives the idea of an ever changing network of nodes (each with different impact and possibly more than one color) connecting each other to create something. I wanted to give it depth perception, so I ended up using two canvases around the title: one in the foreground, even over the...
I wrote a general purpose library for in-memory cache with custom timeout for each key. import ( "strconv" "sync" "sync/atomic" "time" ) type item struct { value interface{} expired bool owner *Cache timer *time.Ticker } //Cache of items which can be expired or cancelled (pulled)...
This question is a follow-up from Object Oriented Finite State Machine. I vastly improved commenting and followed the suggestions from the answer. Additionally, I improved my tests and did some more refactoring. At this point, I still want to know what I could be doing better in my code. How could I better follow C++ c...
The Cardshifter web client is coming along! The game client is a web app written mostly in Angular.js and is hosted at at play.cardshifter.com. @SimonForsberg (who runs the server) is getting tired of the web people always working tirelessly and updating the code, and asked for a script that can do deployment for him. ...
Some folks told that a two-dimensional array can solve almost all the problems, but let me disagree with that. That's why I made this Deca dimensional array sort function. The array must be symmetrical, meaning that it must contain elements corresponding to all the existing elements in the other dimensions. I didn't pu...
This is the Utopian Tree in F# (from HackerRank) The Utopian tree goes through 2 cycles of growth every year. The first growth cycle of the tree occurs during the monsoon, when it doubles in height. The second growth cycle of the tree occurs during the summer, when its height increases by 1 meter. Now, a new Uto...
I have this algorithm for mining frequent itemsets from a database. In that problem, a person may acquire a list of products bought in a grocery store, and he/she wishes to find out which product subsets tend to occur "often", simply by coming out with a parameter of minimum support \$\mu \in [0, 1]\$, which designates...
I'm newish to C#, being mainly Java oriented. I have a field _config which needs to be a value from 1 to 8, and I have this code which checks to make sure I can only set _config to 1-8. If the value given for set is "invalid", _config becomes -1. public int Config { get { return _config; } set ...
How good is this algorithm? Personally I think it's over-complicated and needs some improvement. Should I be using iterators here (I think it's "harder" this way) or indexing? Should I stick with a vector or try other containers? Is a vector (array) of pointers generally better than one of objects? #include <iostream> ...
We have a round table of n knights, where n is some positive integer. These have failed to satisfy the expectations of the mad king and are sentenced to death. However as an act of mercy he goes around the table killing every other knight (starting with the second) until only one knight remains. The question i...
This accepts text and returns a list of all words which occur with a required frequency (default frequency is 2). It works well, but gets too slow with large texts, more than 1M words. Where can this function be improved to speed searches in larger text? from collections import Counter import re def words_in_text_coun...
How to make code dry in this example? My program is working, but I want to improve it by shorting my code. . parser = argparse.ArgumentParser() parser.add_argument('--words', '-w', action='store_true') parser.add_argument('--lines', '-l', action='store_true') parser.add_argument('filename') args = parser.parse_args() ...
Problem The problem is to build the tallest tower made up of cylinders, respecting all the rules. Will be arranged on the table, an amount of \$N\$ cylinders. Each cylinder has one color: Red, orange, green or blue. Each cylinder has one heigth \$h\$ and a base with radius of size \$r\$. To the build the tower, the c...
This is a practice question: A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include ...
Idea behind the class is same as boost::string_ref or llvm::SrtingRef. StringRef is immutable and not-owning. I did not implemented substring() yet, because I will not need it. Example usage: std::string name = "xxxx"; void store(const StringRef &s); void something(const StringRef &s){ //... do something here, fo...
Here's my assembler for the HACK assembly language, part of the Nand2Tetris course. I'd really appreciate any comments/criticism/help! If you want to know what input and output files should look like, you can check out the test data in the /tests/ folder on GitHub. Assembler.c: /** * file: assembler.c * * usage of...
I have ASP.NET WebApi project. Some of controller has method SetAsMain(int id) that get information about people then use stored procedure update people. How can I improve it? Should I do check people.IsMain == true in stored procedure? public HttpResponseMessage SetAsMain(int id) { People p...
I have two different arrays: var array1 = [ {id: "foo", name: "Foo Smith"}, {id: "caa", name: "CAA"}, {id: "bar", name: "Bar Jones"}, {id: "baz", name: "Baz Apple"}, {id: "boo", name: "Boo Ghost"}, {id: "dah", name: "DAH-123"} ]; var array2 = [ {name: "bar", key1: false, key2: false, key3: ...
I'm reading a book about C programming, at the end of each chapter it has some training exercise and one of them was to make a program that tells if a date is valid or not, the code below is what I did and I would like to know if it can be improved? #include <stdio.h> int main(){ int dd,mm,yy; printf("write a date(da...
I recently came across this problem which is as follows: Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). For example, S = "ADOBECODEBANC" T = "ABC" Minimum window is "BANC". Note: If there is no such window in S that covers all characters i...
Today I encountered something that I have been wondering about in the past a few times before. How can I refactor a method that has this format: private boolean isRectificationUpgradable(Rectification rectification) { final boolean validType = rectification.getType() == RectificationType.VH || rectific...
Project Euler 11 Solution in Java. The problem is at https://projecteuler.net/problem=11 package coderbyte; public class Java { public static void main(String[] args) { int Grid[][] = { { 8, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 8...
I need to write 5 crores records with 72 columns into text file, the file size is growing as 9.7gb . I need to check each and every columm length need to format as according to the length as defined in XML file. Reading records from oracle one by one and checking the format and writing into text file. To write 5 crores...
I'm currently learning C with "The C Programming Language" by K&R. At the moment I'm at the chapter about pointers (since I come from Java, they are new to me). In the book is an example code for a method getint(), which is supposed to read integers from input, but doesn't handle freestanding '+' and '-' correctly. As...
I have created keyboard shortcuts menu,same as like this stackoverflow keyboard shortcuts.In multilevel. Scenario In first level i have assigned functions for only key A. In the second level i have assigned functions for B & C keys I have controlled key events B & c in the first level with a variable. Its working f...
Database.php This creates a connection and executes a query. Although, I think I should make it a static/singleton class. class Database extends PDO { /** * constant DSN contains database driver, host and database name. */ const DSN = 'mysql:host=localhost;dbname=matrimonial'; /** * @var s...
In want to implement length prefixed strings in C (not null terminated), with some idiosyncrasies: malloc is prohibited, memory efficiency is important, each string (except for literal-backed ones) is modifiable and can change its length, but it has a fixed (at declaration) allocated length (maximum 255), C code is gen...
My WinForms application is a bit slow, I'd like to make it faster. It extracts only the power and energy values out of a string in textBox3, and displays the extracted values in textBox2 and textBox4. textBox3.AppendText(datarecv); // display data on text box temp = textBox3.Text; //Regular e...
This is from Bjarne Stroustrup's C++ Programming: Principles and Practice, Chapter 13 Exercise 2: Draw a box with rounded corners. Define a class Box, consisting of four lines and four arcs. I've already defined class Arc and using existing facilities (class Lines) for drawing the lines. Here is the code that draws ...
Given a set of overlapping boxes, and a set of points, I'd like to be able to determine which of the boxes contain each point. The number of points is much larger than the number of boxes, and I'd like to do it faster that brute force, so I'm trying to do it with a map-like structure. My current attempt is below, it se...
Suppose you are running a business of repairing cars. You know all the parts (graph nodes) and the way they affect other parts (directed edges), and you know the probabilities of each part failing. If the graph of interdependencies between parts is acyclic, it is called a "Bayesian network". Now suppose a client arriv...
I've written a Code Review design using Userscripts and CSS. It works by fetching the CSS from my GitHub repo, and using the built in gm_addStyle function to add it to the page. The CSS that's fetched is minimised, also. This is what it looks like: I was looking at some of the other Stack Exchange sites for inspiratio...
In my shop system I'm using the PDO lastInsertId to assign the order_id to the products that belongs to it like this: $connection->beginTransaction(); try { $sql = "INSERT INTO orders (customer_id, order_price, order_date, order_hour) VALUES (?, ?, ?, ?)"; $query = $connection->prepare($sql); $...
Given: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. My Solution: def sum_multiples(num, limit): """ Calculates the sum of multiples of a given number. Args: nu...
I’ve created a much cleaner, better designed version to my parallel sieve. I’ve implemented most of EBrown’s micro-optimizations but also revamped the code on my own (that is not in direct response to someone’s answer). public class Sieve32FastV2 { private static ArgumentException BadUpperLimitException(string pa...
Given: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Solution: class Main { public static int sumMupltiple(int num, int limit) { int numOfMulitples = (limit - 1) / num; ...
This is my first foray into OOP, so I'd appreciate any kind of advice! Here is the problem description: On the first line of the input, you will receive a number specifying how many lines of input to read. After that, the input consists of some number of lines of text that you will read and determine whether or ...
I am building my first Laravel web app and I have created a class to handle API requests for a model called Quote. In what ways can the code be improved or reduced? <?php namespace App\Http\Controllers; use Illuminate\Http; use Illuminate\Http\Request; use App\SuperQuote\Transformers\QuoteTransformer; use App\Supe...
Sometimes, I need to change the color of <hr> elements in an email. The only achieveable way is by using CSS. But not every email client supports CSS. Most clients delete separated stylesheets. And some even delete stylesheets altogether! With a lot of trial, I came up with the following: <font color="red"><hr align=...
I'm working on my first Windows Forms tool for a project; this is my first time using C# extensively. Right now, my only objective is to be able to open an XML file and have the resulting XML in hand. I know this works, but I want to know if there's a better, or proper, way to do it. There is also the issue that when I...
Recently, I wanted to see how I might could track state changes to objects, and manage relationships (1 to 1, 1 to N, N to N) between types in C#. This was a really interesting project, and I'm wondering how it might be improved. Full code The full code can be found here, which includes a test project. Basics: Tracka...
I am creating a program that will analyse encrypted text using Kasiski examination in order to find possible key length: #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <string.h> #include <time.h> char *file_get_contents(char *filename, char *fmode) { FILE *f = fopen(filename, fmode); fseek...
I've made a concurrent implementation of the Big Step Giant Step discrete log solver in Go. I'm pretty new to this branch of math, but it seems slow. Any way to speed it up or is this the limit of this particular algorithm? package main import ( "fmt" "math/big" "runtime" ) const increment = 1000 var proc...
I'm trying to find patterns of different length in a given string. How can I improve it? Are there problems? function find(pattern,str) { var arr = []; for (i= 0;i<str.length;i++) { if(pattern== str.slice(i,pattern.length+i)) { arr.push([i,pattern.length-1+i]); }; }; if(!arr.length) { retu...
It has been a very long time since I've used Python. What I'm looking for: I would like to create a 6-by-6 random matrix where each component is either 1 or 2, so that there are 18 ones and 18 twos. Attempt: import numpy import random array = numpy.zeros((6, 6)) while (array == 1).sum() != 18 or (array == 2).sum() != ...
Given: Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ...
I'm using this code for checking if two List<T> are equal or not: public static bool EqualsAll<T>(this IList<T> a, IList<T> b) { if (a == null || b == null) return (a == null && b == null); if (a.Count != b.Count) return false; EqualityComparer<T> comparer = EqualityComparer<T>.Default; ...
From https://www.chrisstucchio.com/blog/2013/actors_vs_futures.html: A very nice feature of Futures is that they are highly composable. Consider the following problem. I want to return an HTTP result to a user based on the following criteria: If a cookie is set, I'll return them a result from the cookie. If I ha...
This is a function definition from an external dll, that I'm calling from my code: LZHAM_DLL_EXPORT lzham_compress_status_t LZHAM_CDECL lzham_compress( lzham_compress_state_ptr pState, const lzham_uint8 *pIn_buf, size_t *pIn_buf_size, lzham_uint8 *pOut_buf, size_t *pOut_buf_size, lzham_bool no_more_input_bytes_...
I was wondering if there was a better way to do this. Would that mean there would need to be no client-side refreshing to show the cookies when they are created? <?php class cookieMonster { public static $lastDestroyed; public function __construct() { } /** * Register a cookie with the browser. ...
Missionaries and cannibals problem is a well known Toy Problem to learn basic AI techniques. I implemented it using iterative deepening depth-first search algorithm. My state is represented by a 3-element vector <A,B,C> where A represents the side of the boat (0/1), B and C represents the number of cannibals and miss...
The problem The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043...
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers: 1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1...
I'm trying to study network diffusion. I took the code form this. However, I would like to see if there's any potential to optimize the code to be faster and clearer. This is what I'm trying to do. In a node, get all the successors and loop through to get the property in an edge to see if the probability is more than ...
I have this array within array which contains a lot of values: 183 => array (size=3) 0 => string 'DE' (length=2) 1 => string '2015-06-09' (length=10) 2 => string 'GK' (length=2) 184 => array (size=3) 0 => string 'DE' (length=2) 1 => string '2015-06-08' (length=10) 2...
I have prepared a small makefile for a small project, but I am trying to find what would be the best practices; up to now I have gathered these: relatively idiomatic (typical structures, flows, var names for Least Astonishment) define the products in terms of the inputs (if I have .c files and want an exec, why shoul...
I've been learning Java for a very short period of time but with a couple of pointers, I've been able to put this simple VAT calculator together. If anyone could offer any ideas for improvement that'd be great! import java.text.DecimalFormat; import java.util.Scanner; public class TaxCalc { public static void ma...
First I have method called in LoginActivity to call my login API. This is my Listener that reads user input and then passes it to a method to call the API: OnClickListener onSigninClick = new OnClickListener() { @Override public void onClick(View arg0) { String Pass = password.getText().to...
I am a beginner level programmer and recently I started learning OOP, so I made a simple war game import random cardsstart = 4 * range(2, 15) cardsstart.extend([15, 15]);random.shuffle(cardsstart) cardslen = len(cardsstart)/2 class cards: def __init__(self): """intializes a set of cards(deck) to the object ...
I have a regex pattern that will match some elements from a string and give them a particular name. For example, #^(?<foo>.*)$# will match the whole string and name it foo. My problem is that the matches also contain the "classic", numbered matches. For example: <?php $pattern = '#^(?<foo>.*)$#'; $str = '123'; $matche...
When hashing a password, I understand it is best not to use functions such as SHA1 or MD5. This function is working fine and I want to know if it can be improved to increase site security. class safePassword { public static function makeSafe($password) { $salt = "mySalt"; $hash = hash("sha256", ...
I am parsing the following line of code via a specific format. Line is: S|111111|87654321|Bar UK|BCreace UK|GBP|24/08/2010| The Format is: Index Field Length S0 - 1 S1 - 6 S2 - 34 .... ... S6 - 10 I am validating using many if statements. Could anyone suggest a better approac...
I was involved in some code-review discussions about UnitOfWork and Repository pattern implementation with EF, which put me in some sort of confusion. Yes, I know that EF already implements UnitOfWork and Repository pattern, but the question is not about that. I am just asking for your opinion regarding existing code b...
I have the following data structure that's obtained from a third party: var data = [ ["Parent1", "Parent1.1", "Parent1.1.1"], ["Parent2", "Parent2.1", "Parent2.1.1"], ["Parent3", "Parent3.1", "Parent3.1.1"], ["Parent1", "Parent1.2", "Parent1.2.1"], ["Parent1", "Parent1.2", "Parent1.2.2"] ]; Where c...
I've just finished working on a multi-threaded network queue and was wondering where I could improve. I'm a little rusty when it comes to waits and such. The idea is to queue up network actions whilst waiting for a form of network internet connectivity. I also added the ability to prioritize which network actions shoul...
This provides (my own) implementation of ToBase64String and FromBase64String (since the .NET implementations suck), and a ToBase32String (since .NET hasn't one). /// <summary> /// Provides extensions to convert certain objects to certain other objects. /// </summary> public static class StringHelpers { /// <summary...
Recently, I wrote a simple program to solve the change-making problem. Rather than the tabular dynamic programming solution (described in the link), I tried to write a solution that uses memoization. usd = [25, 10, 5, 1] def make_change(W, denoms=usd): """ Solves the change-making problem where W is a giv...
I would like to read a file into a list when I create the class below. Once the list is ready, I would like to access it outside the class in order to process more code based on the list which now contains my file. Can the code be improved upon? class ReadFile(object): def __init__(self, filename): self._da...
I have included almost all features that real poker game contains, but even tho I tried to make it as clean as possible, I think it can be done much better. I used inheritance to somewhat distinct player seating, getting ready for hand to actually playing the game, but then again some things as moving the button depend...
I am developing a project that converts SQL server file to MySQL file based on some assumptions. I have written a function that takes the string source as input and it extracts the database name. Is there any way to improve the code? public String getDatabaseNameFromMySqlServerFile(String source) { String sourceFi...
I am presently working on refactoring ReactJS code away from directly manipulating this.state and towards using this.setState() only (which I should have been doing from the beginning). The contents of this.state in my application include containers with varying numbers of objects. They are entirely JSON-serializable, ...
I'm designing a generic interface for a MessageEntry class for a .h file. I'm looking for guidance on form and terminology (would I call this an interface/template/generic class?): #ifndef cppmq_message_types_h #define cppmq_message_types_h template <class T> struct MessageEntry { public: MessageEntry<T>() {} Me...