instruction
stringlengths
71
71.9k
I have a generic Get function that returns a list of objects based on the name of the desired type of object. This has let to an enormous case/switch statement that delegates out to the specific Get functions for the given type. I'd like use reflection or something similar to avoid this huge case/switch. I can't direct...
I've written a function which takes input such as this: lines: [ { id: 1, name: "1" }, { id: 2, name: "2" }, { id: 9, superIds: [1, 2], name: "Shared…" }, { id: 3, superIds: [2], name: "2.1" }, { id: 4, superIds: [2], name: "2.2" }, { id: 5, superIds: [3], name: "2.1.1" }, { id: 6, superIds:...
I wrote an implementation of a directed graph using the adjacency list representation. My goal was to meet the big O requirements which I'd found here. Please let me know about any drawbacks of the implementation. package sample; import java.util.ArrayDeque; import java.util.HashMap; import java.util.HashSet; import j...
I am studying the techniques of data mining and data processing. I'm doing this through data I've collected and stored in a csv file. The problem is that this filed was very large, to the point of having as astonishing 40 thousand lines of text. Some of the algorithms in the rendering part are fast and agile, but the p...
Context I'm trying to write a function that drops a list of tables from a database (e.g., tables A, B and C). This function has the following type, it returns a list of booleans indicating whether each table was successfully dropped: dropTables :: (IConnection conn) => conn -> [String] -> IO [Bool] Now, imagine table ...
I'm new to both PHP and OOP and would like some constructive feedback on a class I made. I have a "main account" login system already setup and working; when the user logs in they're presented with a list of games. This code logs said user into a specific game. I have a separate database for each game, plus one for the...
The program below correctly calculates factorials, until the limit for an unsigned long long integer is exceeded. My question has to do with loops and exiting loops. The program uses one infinite while loop and the break statement to exit 2 while loops. Do working, professional programmers handle loops this way? If not...
I am learning about Tasks and also writing PowerShell cmdlets in C#. I found that connecting to remote machines was very slow, so I wrote this bit of code to speed it up using Tasks. I am hoping to get some feedback regarding the parallel processing and any other pointers in general. The code is committed to a Github r...
protected static String[] applyInterleave(String interleave, int lengthOfSequence, int numOfPermutations){ String[] interleavedPatterns = new String[numOfPermutations]; char[] pattern = interleave.toCharArray(); StringBuilder interleavedPattern = new StringBuilder(""); for(int i = 0; i < numOfPermutati...
So I'm working on a patch for the python interpreter where you go through the list and look at the types of the elements and try to use optimized special-case comparison functions that are much cheaper than the default comparison function. This is the code that goes through and checks the list elements and then assigns...
While implementing the Retry & Breaker patterns I decided that the Breaker does more then it should so I extracted two responsibilities into their own classes. Here they are. I stripped out the Threshold to be only data: public class Threshold { public Threshold(int count, TimeSpan interval, TimeSpan timeout) {...
I just finished the book title class exercise for The Odin Project and I would appreciate some honest feedback for my code. The code is intended to be "test-driven learning", and therefore emulates test driven development Here is the test spec: require 'book' describe Book do before do @book = Book.new end ...
I try to solve this hackerrank using Haskell but not sure if I use Data.Map corretly. Problem in brief: given 2 strings, magazine and note check if you can make note from words in magazine Here is my code, which passes all the tests. import Control.Applicative import qualified Data.Map as M readInts = map read . wo...
I've been working in C++ for the better part of this year and am looking to improve my style and efficiency as much as possible. One thing I've been told is to work on commenting code to make it clearer, so if you have any suggestions about where I could use a comment to clarify what is going on I would be very glad to...
This function returns a list of all the beginning indices of a substring in a string. After finding the index of a substring, the search for the next one begins just after this index. def find_substring(substring, string): """ Returns list of indices where substring begins in string >>> find_substring('me...
I am implementing a game in python, which will give the user a sample encryption, and explain each step from plaintext to cipher. The task for the player is to decrypt a word by undoing each step shown above on the new word. For this, I have created an abstract algorithm which requires an encrypt function, and a curren...
I've implemented a simple scoped lock like this: public class ScopedLock : IDisposable { private ManualResetEventSlim mres; /// <summary> /// Constructor. Expects a ManualResetEventSlim with /// state to signaled (i.e. true), so that the first /// thread to enter a critical section can execute ...
The last question about sequence generators Growing potatoes in delayed sequences was only about potatoes. I thougt why not make it work with apples and oranges too so I made it generic. The base class got a new name and a generic argument and now looks like this: public abstract class GeneratedSequence<T> : IEnumerab...
I am building a small program for input handling so I can conveniently parse lines and tokenize strings. The token handling works right now but I have to malloc a lot in the main() to make it work. Sadly I can not malloc everything at once because then the strings inside will have NULL pointers. Maybe someone more expe...
Please help me improve my coding style. /* Author: Muhammad Awais Blog: http://uetianblogger.blogspot.com/ Description: Divide and Conquer Rule. Binary Search like algorithm to find local peak.It may or may not find global peak of the array. Parameters: A[]= Array of elements i=starting point j=ending point Algorith...
I am very new to Perl and decided to work on a simple script that could solve a problem I encounter in my day to day work. The purpose of the code that follows is to search over a body of text and extract English case law publication references. There are quite a few flavours of reference style, so I have several expre...
I'd appreciate your advice. data file: https://drive.google.com/open?id=0B_UEM0TEmA_yeHJBZ0dzbV9Ca2c /* CNG213 Data Structures / Programming Assignment 1 - Sinan ULUSOY "A-Eye: Analysing Eye tracking Data" l1 is used for main list record l2 is used for sub list record */ #include<stdio.h> #include<stdlib.h> #inc...
From an unsorted vector of integers, I would like to keep only elements that are present an odd number of times and have them sorted. Below is an example of a working code. #include<vector> #include <iostream> using namespace std; int main() { vector<int> input = { 11, 3, 7, 3, 9, 3, 8, 11, 9, 3, 2, 9 }; ...
This is still my first week of learning C++, I solved the lower bound STL challenge in HackerRank Lower Bound STL but I'm having time exceeded issue for long input. I'm open to constructive criticism, ways to improve in terms of syntax, style and performance. You are given \$N\$ integers in the sorted order. Then you ...
This C++ Boggle board solver is intended to take in many boards one after another and score them. I would like comments on code style, whether there are C++ standard library features that I could use to streamline the code, appropriate division between public and private, etc. Download code Download dictionary file Bo...
To help myself learn macros, I made a custom version of the threading macro that lets you choose which argument the "thread" gets put into. My main concern is simplifying it, and making it more idiomatic, but anything notable is welcome. If anyone knows of a better implementation for insert-at, I'd love to know that as...
I just attempted the Maximum Element Challenge on Hackerrank. This question has been posted before in swift Swift Hackerrank Maximum Element in a Stack but it has attracted low views/no answers. Moving forward, based on the requirements of finding the maximum element, I used a vector<int> as my underlying data structur...
Project Euler 14 asks: Which starting number, under one million, produces the longest Collatz sequence? I've been trying to optimize this solution to execute in less then 1s. Agenda for first 50 eulers. Currently it executes in 1,2s for me, so I guess that I want it to be 20% faster. Any tips or other methods? from tim...
I am trying to write a constructor method that takes dd, hh, mm and ss as parameters and change it as a normal type of Time struct (e.g you enter 25 hours as the hh parameter, it changes it to 1 day and 1 hour). struct Time { public Time(int dd, int hh, int mm, int ss) { seconds= ss % 60; ...
Given a dimension \$D\$. We generate a \$D\times D\$ matrix with elements that start from \$0\$. For example, if we're given a dimension \$4\$ this is what our matrix looks like: $$ \begin{bmatrix} 0 & 1 & 2 & 3 \\ 4 & 5 & 6 & 7 \\ 8 & 9 & 10& 11\\ 12& 13& 14& 15\\ \end{bmatrix} $$ Now compu...
on my initial attempt of creating a duplicate files finder(see Duplicate files finder in C++ @ this code review site) I have finally came across the successful and optimized implementation of this code. The idea is same like the but I have made changes according to the advice of some professional here and also have fix...
As I will be deploying this script on multiple machines with the very same system Linux Mint 18 with rather same configuration, I would like to be semi-sure I won't screw things up much. This little script will run every day from crontab and will be logged into syslog. Conditions were: Code Readability Output Readabil...
This is the "classic" algorithm for calculating the sum of digits uses the modulo-operator together with the division-operator. I had the idea of using the slice-method with a negative index for accomplishing the task. /** * Calculates sum of digits from a given number. * @param { number } num * @return { number }...
I have implemented a renderer for shapes described with a L-System grammar. Implementation of that is not important. Basically you feed it an angle and some rules, and it spits out a string of characters that represents instructions. For example, "+" means turn right n radians and vice versa. The instructions will only...
Proper input handling is a pain in the butt in C, so as part of a project of mine, this header is used to handle reoccurring command line input tasks such as input loops, reading lines and tokenizing strings in a safe and robust way. Would be great if some C veterans could share their opinion about potential flaws. You...
I'm trying to learn Clojure recently and I thought writing a simple web app would be a good way to dive in. This function gets the list of alive threads from the API and reduces, filters and maps until I'm left with a list of image names (which I can append to "http://i.4cdn.org/wg/" to get the URL's.). This is the fir...
This is a continuation from this question: Reading analog moisture signal from Arduino over USB to RPi3 and publishing via paho MQTT I made the advised changes, and added a bunch of new stuff, I'd like it if I could get some further constructive criticism on it. Especially the error handling I have added in. I was havi...
I'm looking for ways to optimize a function that I wrote as an answer to this problem in Python: You and your rescued prisoners need to get out of this collapsing death trap - and fast! Unfortunately, some of the prisoners have been weakened by their long imprisonment and can't run very fast. Their friends are t...
I'm learning C# and have written a function which generates an easily-pronounceable fictional name by alternating between taking one vowel and one consonant. The one parameter, halfLength, will be the amount of vowels added and the amount of consonants added, meaning that the length of the returned string is double the...
This script is a userscript designed for giving a notification when the bot SmokeDetector posts a message in the Charcoal HQ or any other room were he is active. The script has 3 modes of operating, which can be selected at the bottom of the screen chat only (default) It only gives a notification when a spam related m...
Here is the premise: Three women robbed a gentleman of a vase, containing 24 ounces of balsam. Whilst running away they met a glass-seller, of whom they purchased three vessels. On reaching a place of safety they wished to divide the booty, but found that their vessels contained 5, 11, and 13 ounces respective...
I would like to know if my function that checks if a string syntax is correct. It's currently very messy, but seems to do the job. //Example Valid String [12345678] { something whatever } Function: private static bool CheckIfSyntaxIsValid(string input) { int mode = 1; char last = ' '; ...
I have been trying to generate a basic library that I can use at work, to call different REST calls towards a software vendor that we are using. I would love someone's opinion on it, and what I could do better, hopefully with some examples or links, and some descriptions. I am by no means any good at Python, but I trie...
I made a program which is supposed to be an implementation of the game 1010! with support for custom AI agents, minus some pieces available in the original game. It works great for the 1 agent that I made, but it is not really fast IMO. I know that bruteforce is in itself slow, but I still have a feeling that my game i...
I would like to add basic Cloud system to my website project. I have my php login system already included. Every person must be logged in to view this site. There are several session variables like $_SESSION["id"]. I've got my files.php file - main file with list of uploaded files on server, form to upload new and dele...
I am learning C on my own. This is not an assignment. I am trying to implement a function that takes a variable numbers of strings and concatenate them in a new string. It works, but I feel it is not elegant and would like to improve it. For instance, I don't like how I am using n nor having to decrement argc twice, an...
In a chess board, I need to find the diagonals a bishop can move on, and more specifically, the coordinates of those squares. So, given a grid of any size and a position in that grid (expressed in coordinates within the grid), I have to compute the coordinates of the diagonals of that initial position. I'm using zero-b...
Edit: Ok, this was a disaster of a question. I'll make sure to use timeit in the future I solved a Codewars problem that had the user check if a number was a palindrome, was incrementing, and etc. After I solved it, I noted how the top solutions were much more simple, intuitive, and elegant than mine, although they wer...
I am currently making an application where the user will launch the app and the first this we see is the app logo fade in at the center of the screen. After about a second, the logo will translate up and the rest of the content will appear. I currently have a lot of code and wanted to know if this is the most efficient...
I am trying to implement Elapsed Timer in Python (version 3). The clock and time methods in Python seems to have different implementations of calculating time in different platforms. So, I thought of getting the difference between the system time seconds to detect the change in second. Though the program works as expec...
I'm currently facing the problem of unmarshalling a huge number (47) of attributes to a Java object. Changing the format of the XML file to be more structured is sadly not an option. The following should serve as an example. Imagine each request element has 47 attributes instead of two. <Data time="20161031111103"> ...
As I will be deploying this script on multiple machines with the very same system Linux Mint 18 with rather same configuration, I would like to be semi-sure I won't screw things up much. This little script will run every day from the root's crontab and will be logged into syslog or my own log AFTER this manual script p...
Here is my JS code which uses the D3.js library (mostly snipped from other examples). I want to graph the acceleration of a point in 3D-space which changes with respect to time. The X-axis of the graph is timestamp and the Y-axis is the x,y and z location of the point. Is there a way to write this more efficiently? Thi...
I'm attempting to learn more about Java and have created a method that takes a text file with stdout (space separated file) and converts it to a CSV file. I was attempting to use standard Java SE version 8. Is there a better, more efficient, way of doing this? The logic is: Open file Read file by line into string so i...
I'm looking into having a simple dependency injection container in Python. I've Googled on it but so far the solutions that I've found are quite huge and use constructs such as decorators and so on which I'm not so fond of. So, inspired (or copying) the Twittee IoC written by Fabien Potencier in PHP I wrote this scrip...
Currently, I have a function that loops to gather input for program execution, but I feel that it is a bit lacking, overthought and unoptimized. I would love any input on the process, coding style, or usability of the function. I feel like the use of while (true) is not really optimized here. My code uses curses and un...
I'm making baby steps in Java programming and I just ended coding basic game: Snake. Could you share with me what is needed to improve in this code? What about OOP here? GameBoard.java import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.LinkedList...
Does anyone have suggestions for how to make this code for playing a game of Quarto cleaner and more robust (beyond input error checking, which hasn't been fully fleshed out yet)? # Enums for quarto. DRAW = "D" WIN = "W" UNDECIDED = "U" LOSE = "L" TIE = "T" class Piece(): """ This is the piece class. """ ...
I've got the following code where: $urlParams is the school year from 7 to 11 $Comms['Overall'] is the total amount of "commendations" a student has This code iterates through the numbers based on the school year to determine which "award" a student has got. Is there a better way to write this code? if($urlParams['y'...
After receiving some feetback about my previous attempt to create reusable, easily extendable sequence generators I try once again to create such a framework. This time there is no inheritance. Just extension methods. The new core is the Sequence class: public class Sequence { public Sequence(int count) { Count = ...
I use the following code which works OK, the code is filtering requests and in case there are too many requests it sends some logs/errors since I'm very new to Java my question if there is a better way to write it especially the while statement ... public final class filterBu implements Filter { private stati...
Given a number n, the task is to complete the function which returns an integer denoting the smallest number evenly divisible by each number from 1 to n. I have solved it using the following function: long long getSmallestDivNum(long long n) { //number should be multiplier of n bool found = true; int i = 2; ...
I implemented an extension for the NSManagedObjectContext that takes any CoreData class as a parameter and performs a fetch request on it. I am new to CoreData and would very much appreciate any sort of feedback for this function extension NSManagedObjectContext{ func fetchObjects <T: NSManagedObject>(_ entityClass:T....
The following code is to classify the test data into several classes: function pdfmx = pdfparzen(train, test, winwidth) % computes probability density for all classes % using Parzen window approximation % train - train set; the first column contains label % used to compute mean and variation for all classes % test - t...
Here is our code of Tant Fant Game. Does anyone have suggestions for how to improve our code? class board: loc = [] def __init__(self) : self.loc = ['B', 'B', 'B', '', '', '', 'W', 'W', 'W'] def cur_state(self) : return self.loc def find_empty_spot(self) : return [i + 1 for i, ...
I have written this code to check all the edge cases in the implemention of an atoi() function.Please review. //Program to print an atoi(). public class Atoi{ public static int atoiFunc(String str,char[] c,int l){ //If the length is 0,the function returns 0; if(l==0){ return 0; } //va...
I'm trying to implement what I think griddedInterpolant(X,V,method) is doing inside Interp1. I get the same results. Please review the extrapolation part as I'm not quite sure about it and comment about the algorithm correctness. double Model::Interp1(const std::vector<double>& alpha, const std::vector<double>& varSur...
When my program begins, I want to allow the user to hit a key to enter debug mode for one of the modules. Many of the solutions (involving alarm(), in particular) seemed complicated and involved multiple functions. Instead, I adapted this answer: // Check to see if we should enter GSM de-bug mode fd_set s; str...
Story time: A week ago I found a question about optimizing Assembly code, then I remembered how awesome Brainfuck was, and the match was made very quickly. I decided to write a Brainfuck Interpreter in Assembly! For this I have used the NASM assembler with x86 Assembly and is intended to run on an Intel CPU and on the ...
I've been studying the CQRS pattern created by Gregory Young and have been trying to come up with some sort of library or set of classes I can reuse in other projects. This is the mediator (bus) part which can be used in web apps, on controller classes, to push either Commands and Queries to respective handlers. This i...
This is a basic implementation of the game of Quarto, inspired by this question to write my own: From Wikipedia: Quarto is a board game for two players invented by Swiss mathematician Blaise Müller in 1991. It is played on a 4×4 board. There are 16 unique pieces, each of which is either: tall or short; red or blu...
I've been studying the event sourcing pattern and trying to come up with a set of classes or minimal library I can share across projects. Below you can find the implementation of this main parts of this pattern including the EventStore and Repository. I'd be thankful on getting a review on whether this is what the patt...
In my rumblings developing flask applications I found the caching decorator. The decorator is a short and well-written piece of code, but I feel like it misses the few points bellow: It only caches on the server side and doesn’t leverage the client-side cache - meaning that clients still have to go and hit the server ...
I'm making a helper function to make setTimeout synchronous. Currently, it is asynchronous so other code runs before the timeout is done. function syncSetTimeout(func, ms, callback) { (function sync(done) { if (!done) { setTimeout(function() { eval("(" + func + ")();"); ...
I created a project to better understand CI3, while developing it I tried to introduce localization elements. When I tried to localize the view everything messed up. I made a helper to identify if the user choose a language different than default language then load the right language. function lang_load($lang_file)...
I have a bunch of checkboxes that need to be toggled based on certain conditions. My function is called by multiple buttons on an onclick event. The certain condition is expressed as a string (check_all, uncheck_all, check_all_virtual). The problem that I see is that if the function would be called as toggleCheckboxes(...
I am working on a data collection JavaScript library, and would like other members of my organization to be able to write loosely coupled plugins to extend its core functionality. I've been working on a trigger\listener (or publish\subscription) module for it and would love some feedback. Particularly any potential une...
I am currently taking part in research utilizing Naked Mole Rats. I am utilizing data analysis techniques to answer the overall question, "Can we detect certain types of naked mole rat behavior utilizing statistical techniques such as hamming distance and similarity graphs?". Certain statistical techniques, such as h...
I have the following domain model: class Holding ------------ Account account; DataSourceProduct dataSourceProduct; class Account ------------- String name; class DataSourceProduct ------------- DataSource dataSource; Product product; // other product data specific to the data source class Product -------------- St...
What improvements could be made to this script and can you explain why you would make those changes? import hashlib import os import time time = time.strftime("%Y%m%d-%H%M%S") Masterhash = open("Filehash" + time, "a") #get a list of files from your directory for filename in os.listdir('.'): #ignore directory names ...
For my Biology class, I made a Python script which takes a DNA sequence as input, translates it into an mRNA sequence, and then again into a tRNA sequence. It then matches each mRNA codon with an amino acid, and gives the user all of the data it produces. Since this program may have to work with large amounts of DNA co...
I am wanting to implement an AlertDialog with a list into my app and I created a sample to see if I can get the result that I am looking for. It seems I do have the result I wanted but before I implement it into my actual app, is there a way to make my code better?: activity_main.xml: <?xml version="1.0" encoding="utf-...
I have not programmed a lot in JavaScript and I am hoping to improve myself. Thus, I am looking for a style review as well as to look for a better way to approach this problem (the current code works perfectly and as expected). What I am doing is requesting the Microsoft Emotion API to take an image and spit back the a...
I just started learning JavaScript and I have created a basic TODO list following MVC concepts to apply what I have learnt so far. This is probably overkill for a simple todo app, but the objective is to improve my JavaScript skills. I'd highly appreciate it if you can spot flaws, especially bad practices and suggest i...
I've had great experience in the past getting feedback from uDev and python, but I'm dreading this attempt at C++. I have a little background in C - but absolutely none in C++ - so this code is constructed directly from reading many books, SO posts and the code from a lot of GitHub projects. I know there's probably an ...
I'm trying to write a small macro library in Racket that extends a few of the racket/match functions I use, by printing which clause was expanded. While this seems to be decent practice for learning macros in Racket, I still find them incredibly daunting. At some point, I wind up just trying everything with no real se...
While reading Object calisthenics and Getters/Setters. Evil. Period. I got confused. Let me explain it by example. I have this organization class, representing the information about organization, the classic entity: class Organization { private $name; private $city; private $street; private $phone; ...
I can't use std::to_string and std::to_wstring function, so I have written a converter: ///@struct ParseInt ///Contains function that parses integer. template<typename Char_T> struct ParseInt{ static std::basic_string<Char_T> toString(int x); }; ///Converts integer to std::string ///@param x the integer to convert...
I have partial view which update data on server. Partial view contains list of configurations (can be check box or text box depends on type). This code is working, and I would like to know how to implement this better. Main question is related to "@Html.HiddenFor". Is this correct way to implement update? Without "@Htm...
once user login, we are displaying all the information of user in profile/account page. please check code quality , security & Performance. <?php include 'home.php'; // session_start(); require_once 'class.user.php'; $user_home = new USER(); if (!$user_home->is_logged_in()) { header("Location: index.php"); die(); ...
I'm in the process of writing a simple text based MUD. First up is making sure that it's possible to create new players / logon with existing players. Since everything is text based, there are several state transitions involved where the user is prompted and then their response is processed. With this in mind, I've ...
I am looking for feedback on what I can improve to a tool I have been using for several months now, my AnimationFrameController. I find requestAnimationFrame an incredibly hassle and hard to control, so this controller does it for you. Are there better/more efficient ways to do this? The below is an example of how to u...
The idea is that local security/SIEM solutions want to populate their database with information gathered from different security feeds. This is done through importing and monitoring .txt files (for some reason). The idea behind this, is that I want each feed to have their own function, to easier be able to filter out, ...
I have made a small script which grabs data into a map from 80 CSV files and calculates some statistics like average, standard deviation etc. It's also adding some additional data to map from filename. Can you please check if it is a correct way to do so? The idea is to get a list of files in the folder using file-seq,...
I have two JS functions that return a total number for me based on some properties. It works fine but feels a bit 'clunky'. Would there be a cleaner way of doing this? getTotalTrucks: function (data) { var noOfTrucks = 0; if (data.truck1 == "1") { noOfTrucks += 1; } if (data.truck2 == "1") { ...
I have the following function defined in my .emacs to test if a given executable exists within my $PATH. I implemented it with cl-reduce and the code looks really unidiomatic (to me). (defun executable-in-path-p (executable) "Test if EXECUTABLE exists in path." (eq t (cl-reduce (lambda (path exists) ...
I needed a structure that works really similar to the predefined Stack<T> but with a few extra functionalities. Examples include getting the index of value in the collection and being able to index the structure itself. Any flaws or improvement notes are welcome! public class StackList<T> : IEnumerable<T> { private...
My function is supposed to essentially give the cartesian product of all the letters in a string with the caveat that you have to give the permutations of every equivalent of each character in a string (capital and lowercase for example). This is what I came up with but I believe it has a time complexity of \$O(n*k^n)\...
I wrote this small script to help porting msysGit sockets to WSL ("Bash for Windows"). I'm not a big Python programmer so any feedback would be well appreciated. By the way, I made it a public Gist so I want to make sure it is good quality before some other people are using it too. #!/usr/bin/python """ msysGit to Uni...
This code is meant to do a binary search of a sorted list containing integers. I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview. def bin_search(a, item): first = 0 last = len(a) - 1 found = False while first <= la...