instruction
stringlengths
71
71.9k
I have got a piece of code that initialize Scanner in two possible ways: no argument constructor creates Scanner that uses stdIO (System.in) as source contructor with String, which creates Scanner, that uses file as source, where String is a path to file It looks like this: public class InputMethod implements IInputM...
I recently tried my hand at writing Go code for a project I'm working on. In order to help myself get a better grasp I decided to write a simple yet somewhat practical program for parsing numeral characters from strings based on the ascii values of the runes within, and appending them to a slice. My primary concerns wi...
I've written an implementation of a Stack data structure using a linked list. Stack.java import java.util.EmptyStackException; public class Stack<T> { private class Node { private T data; private Node prev, next; public Node() { } public Node(T data) { this.d...
I am trying to read properties file using a singleton class. I would like to know if there are any best practices and design patterns to read the properties file. I found dependency injection is one way to read properties file. But, I did not find any examples on the DI design pattern. Any sample code and links would b...
I've created a class that translates an integer into words in an English (not British) format. My first human language is not English, and I don't have a good idea of a truly right way to read numbers, so I followed the exact meaning of the numbers (e.g. 1024 = one thousand twenty-four, not ten twenty-four as read by s...
I've created a simple JavaScript application, which also happens to be my first-ever piece of code in any programming language.It took me two days to get the core correct and another two days for styling and the progress bar. I'll be adding subsequent features to this quiz, as I continue to learn more and more about th...
I'm using nodegit to develop the backend for a nodejs app that uses a mix of mongodb and git for persistence. The app has to version documents and be able to present diffs between versions, thus the use of git in the backend. For one of the API endpoints, I needed to get the diff between two commits, so I've develop th...
After rolling my own virtual machine, I decided to implement an assembler for it. Ironically, it's all Java, since I needed to do a lot of text manipulations. Please, tell me anything that comes to mind. Here is the main component: ToyVMAssembler.java: package net.coderodde.toy.assembler; import java.io.FileNotFoundEx...
Would you please recommend how I could improve this code? My PHP editor only gave a warning about the variable $id. require_once 'includes/config.php'; $id = (isset($_GET['id']) || trim($_GET['id'])) ? intval($_GET['id']) : 0; if (!empty($id) && filter_var($id, FILTER_VALIDATE_INT)) { $sql = $pdo->prepare("SELECT...
I'm currently building a game called "Drones! Attack!", and I needed a drone controller that the player can use. It's currently very simple and only supports a small amount of actions, such as: Basic movement (forward, backward, left, right, up, down) FPS camera control Camera scoping (e.g, changing the FOV from a hig...
When I started learning Repository Pattern with Unity few days ago I was under impression that the main benefit of this pattern is the separation of data layer from the business layer. In other words, if there is a need to change the way, how application stores the data, it's very easy as only one main model takes care...
I've recently applied to a backend position and I was asked to complete a take-home interview question. I thought the question was rather simple and I completed in about an hour although I was told it could take up to 4 hours. I got a response back recently stating that my answer does not demonstrate the necessary skil...
This is my 2nd program I wrote on my own, a pretty simple program consisting of two functions (those functions are not combined in any way yet though). The first function moves the display times of subtitles saved in .srt files by a specified amount of time. The second function "warps" the display times by a specified...
I have a game in which the player has to do something within a defined time. E.g.: the player has 10 seconds to complete a level. My current code animates an imageview (it's only a horizontal line) when the game starts: progressAnimation = new TranslateAnimation(0, -Settings.screenWidth, 0, 0); progressAnimation.setDur...
Do you think the way I'm doing it is fine? Is this the most typical way to do it? Share your thoughts please. # Display the last three lines of a text file with line numbers in reverse order # Can come quite in handy when reading log file entries cat -n [FILE] | tac | head --lines=3 Test: # Let's create a text file to...
I'm new to Powershell scripting and trying to write a script that will go through printer queues on a print server, get the print queue's port address, then compare the print queues port address to the DHCP reservation associated with the print queue port address on the server. If the port address of the print queue co...
This code works but I don't know if I am doing this correctly. I want to have a do-while loop for the menu and app. How could I improve this code? import java.util.Scanner; // import scanner public class CalcPart3 { //class definition public static void main(String[] args) { //main class char result...
I tried to come up with a good challenge to learn some Rx.js programming and I came up with this chain of operations below. As well as a bit of code that works and does these things. Take github username Create folder based on username (/repos-${user}) Get all repos for username (https://api.github.com/users/${user}/...
I am writing a program to generate a height map following the midpoint displacement algorithm (somewhat similar to diamond-square). I'm at the point where I have a recursive program that paints the whole map but still needs some modifications to provide the desired result. Before I do, I would like a code review on wha...
So I've written my first android app in kivy. This app takes a Vehicle License Number as input from the user and submits it to a sites and shows the results from the site. The complete Source Code of the app is at https://github.com/Logmytech/Andhra-pradesh-vehicle-lookup Here is the Kivy language code: <RootWidget>: ...
I'm very new to AngularJS and just started in a new project which uses AngularJS for Web UI. I was looking into our code and found out that we have huge functions in controllers. Like, one 100-LOC function which does a lot. Logically, our Sonar complains about it and for me as a novice it's quite difficult to understan...
I implemented a vector class in C for integers. Any feedback welcome. header: #define DEFAULT_CAPACITY 1000 // Define a vector type typedef struct { int nrOfElements; // Current number of elements. int capacity; // Possible capacity. int *data; // Pointer to array elements. } CVectorInt; typedef e...
I am using the following Depth-first search algorithm to compute value of a property called rotation_absolute based on previous values of rotation of parent elements recursively. The result of the script is correct (open console to see the result) but I would like your code review regarding performance, considering tha...
I have this code which makes it easy to color a string in terminal but it is looking really repetitive. Is there a more idiomatic way of writing this? Also is there a functional way of doing this more effectively? It seems really trivial, something like strings blue,red etc should point to a generic function, and when ...
I solved FizzBuzz using tail recursion. Is it efficient enough? (defun mod-3 (n) (zerop (mod n 3))) (defun mod-5 (n) (zerop (mod n 5))) (defun analyzer (n) (if (mod-3 n) (if (mod-5 n) 'fizzbuzz 'fizz) (if (mod-5 n) 'buzz n))) (defun fizzbuzz (limit) (fizzbuzz-helper limit nil))...
This is follow up to this one. In the previous some minor errors slipped, so I couldn't update the code. Also took some advice. So final version is below. header: #define DEFAULT_CAPACITY 1000 // Define a vector type typedef struct { int nrOfElements; // This just denotes current number of elements. int capacity;...
I've got a job to create a library that would be able to support multithreaded and multi process read and write to a single file. On that single file we would store C# models in an array in JSON format. It would basically work as a mini file system JSON DB. When the application that uses this lib starts, it would load ...
I have created this middleware code for slim. I just want to know that is this right way to store site settings globally. so, I can use where ever I want. What do you think about my class structure apart from invoke (which is slim's own feature) what do you think about foreach and setting the data. I'm trying to learn ...
I have a need to get notified about validation errors that occur in a child collection of my ViewModel. For validation I use the INotifyDataErrorInfo interface. I've created a class that handles this successfully however, I feel that additional refactoring / simplification can be done on it. Here's the class that imple...
I have done this quiz project and I have tried as hard as I could when I was writing to make it user friendly to read. Could you help me on improving and making it more user friendly please. import random import operator import csv OPERATIONS = [ (operator.add, "+"), (operator.mul, "*"), (operator.sub, "-") ] NB_QUES...
I have this Brainfuck interpreter: // Credit goes to where it is due function throwException(cause, index) { // Execute when there is an error in Brainf*** code $('p#output').text("Interpreting Terminated because " + cause + " at char index " + index); } function runBrainfuck(data) { console.time("Runnin...
I have used loops to remove lines that are doing various things, but all are deleting rows where certain criteria is met. Some are deleting less than certain numbers, deleting blanks, removing specific rows that contain specific things in columns, remove all the items that don't contain 4 specific parts. This works but...
I'm trying to improve my C++ template metaprogramming skills. From my understanding, I can't partially specialize a function(either member function or not). So, I need to define another class that can be used as template class, which enables us partially specialize template argument. So, In order to check my understand...
I created a Sliding Number Tile Game, and am looking for input on how to make the code better organized & more efficient. #include <iostream> #include <random> #include <algorithm> #include <chrono> #include <windows.h> #include <conio.h> using namespace std; void initializeBoard(char pB[][3]); void printBoard(char ...
CasperJS doesn't allow continue statement inside a casper.then functions. This was my solution but I'm not happy about it. Is there a better way to achieve this effect? casper.start(); casper.then(function() { var current = 1; var end = 4; var skip; for (;current < end;) { ...
attributes is an array with all attributes selected by the user. attributeList is a Mongo collection declared in [root]/lib and contains all possible attributes. I'm using two loops in order to match attributes. For those that match, new fields "operator" and "value" are added and will be used in the template. Do you s...
VSDiagnostic's latest refactoring and code fix detects when a switch does not contain case statements for each of the enum members and adds any missing members. So, for example, with the following enum and switch, VSDiagnostics will detect that some members are missing and add them as shown in the second switch: enum...
The following is a webpack loader for Phaser asset files. The way this is supposed to work is that it looks at the json string, and finds all of values with "url" keys in the json object, and transforms that value to a function call with that value as the parameter. I need to assume any level of nesting of the json v...
I am refactoring a part of big old system developed in Java. I came across a situation where we are migrating some data types, and there will be use of both types. For compatibility, as all the old part will remain using id as an int, I simply overloaded the constructor, and the old getter now parse a integer value. Th...
I never get to use ECMA6 in production/work, so I am hoping you all can help me write better code by reviewing my finished sample: (function() { 'use strict'; class BudgCalc { constructor(personFullName, yearlyAfterTaxIncome) { this.name = personFullName; this.income = this.d...
I just spent the last few days constructing the currency system for my game, and was wondering if you guys had any suggestions on how—if at all—I could improve it. Before I show the code, let me explain the system as it currently stands. It works a lot like World of Warcraft, in that Copper is automatically converted t...
In The Nineteenth Byte, we have an excessive amount of carets (carrots, if you will) that direct one's attention to another message. For example: Amidst the confusion, I made a userscript that highlights in yellow the pointed-at message when the message in question is clicked. (function(){ var elements = {}, messa...
I'm using Microsoft's SqlDataConnection type provider. However, the only way I've seen to update a row in the database is to use something similar to this where it updates mutable values: let updateProduct product = let currentProduct = query { for c in context.Product do where (c.Product_id = product.Produc...
RULES: Strict tasks must occur at the time the user selected no matter what. Flex tasks are in a priority order. Even if there is a gap big enough to fit several flex tasks with lower priority, no flex task can be scheduled until all the tasks with a higher priority are scheduled. Flex tasks will continue to be resch...
What I'm doing I am writing a server to work as my games backend. The server is being written in C# using UDP as the protocol, while the game is in C++. The biggest thing I've been focusing on was trying to make the packet messages more OOP than what I've typically seen for game servers. As a result of this, I wonder i...
I'm relatively new to Python, I decided to make a simple battleship game. Is there anything I should do to make it shorter, or in practice, "better"? from pprint import pprint as pp import random Rows = 0 Columns = 0 turns = 0 Answer = "NaN" print("Welcome to battleship!") while (Rows > 10) or (Columns > 10) or (Row...
So I am assuming that I did something wrong, and my AES and RSA encryption and decryption classes are insecure. I plan on using them for a larger project, and want to make sure I didn't completely muff them first. My questions are as follows: What, if anything, makes these two classes insecure? What, if anything, coul...
I know there are a lot of different solutions to solve the "Dining Philosophers" problem, but I wanted to get some feedback on a solution that I have so far. My motivation for working on this is to prepare for future job interviews and to get more familiar with threads and C++. #define P 5 #include <iostream> #include...
I have written a program to find all anagram groups in a text file. I used first 26 Prime numbers as a mapper for 26 characters for finding anagram groups (Since character_set of all anagrams of a particular word are same, the products of the anagrams are also same ). After finding product of anagram I put (product, an...
I have a server that uses Java NIO in non-blocking mode. Right now I'm using a single thread for the selector, and four worker threads to process the bytes after the selector reads them in. I'm going to switch to a thread pool soon enough. Anyway, that's not why I'm here. Take a look at the code below. I have a state...
I've developed easy Game of Life project. I'd highly appreciate any feedback and possibilities to improve my code, both in efficiency and style. It works on list and it's terminal program. ICell.java public interface ICell { public int getX(); public int getY(); } Cell.java public class Cell implements ICell { ...
Given the following input values from a form, create a method or methods to validate the input based on their requirements. Throw an exception if any data is invalid. 1.1 name: is required 1.2 must be first name AND last name 2.1 email is required 2.2 is a valid email address 3.1 twitter is optional 3.2 is a...
I'm new to parallel programming concepts. I'm trying to implement fire-and-forgot kind of method in my project. Somebody please evaluate the below code & let me whether this is thread safe or not. //Controller public ActionResult AddMail(Guid userId) { EmailNotification.QueueMailAync(userId); } ...
A user can have many subscriptions, and a subscription belongs to one plan. The plans table tells us a subscription's cost. Is the query below the correct one for figuring out the number of subscriptions purchased by a user with an "ongoing" status and the total revenue brought in each day between Jan 1 and Mar 4, 2...
I am deleting rows based on a date. I am loading the entire sheet into an array and doing the evaluation and building a string containing the rows I want to delete. Option Explicit Sub arrmaker() ThisWorkbook.Activate Dim i_LastRow, i_LastColumn, i_FirstRow, ictr, ictr2, i_row, i_col As Long Dim Da_Array(), Da_Other_A...
As a post processing step of a similarity matrix computation that leads to the non-negative matrix mt4_ in gpu, I am performing an assignment step to determine which element in rows/columns is most similar to which element in columns/rows. So this is more like a first-come-first-serve algorithm in which the largest sim...
I had posted this question in Stack Overflow and they told me it would be better served on Code Review. Is there a more effecient way of changing the mouseout state when a button is clicked? When a button is clicked I want the image in the click event to take precedence over the image in the mouseout event. The followi...
I recently decided to see if I could make a functioning templating system. It works, but I feel like it is not all that great. What I'm looking for here is just general critique or ideas to improve. I'm new to this stackexchange, so if this is not the right place to do this, please let me know. As requested below, I'll...
I have a simple Flask app that realises rest-api with SQLAlchemy. I have written this create_app function: views.py def create_app(config): app.config.from_object(config) url = config.DATABASE_URI engine = create_engine(url) Base.metadata.create_all(engine) Base.metadata.bind = engine DBSession = se...
I have created a function that will take as a parameter a StorageFile and return a WriteableBitmap. I use this data type so that I can later encode the image into a base64 string. My concern is with the intermediary BitmapImage that I create to get the original dimensions. Any other improvements would be welcomed as we...
I am practicing for technical interviews and I am encountering a lot of problems relating to the tree data structure. I have gone through other posts that discuss about the tree data structure and come up with the class definition and method signatures for the some of the operations as below: class Tree { struct No...
I need to transform List("home", "mens", "clothing", "jackets") into List( "/home", "/home/mens", "/home/mens/clothing", "/home/mens/clothing/jackets" ) This is what I have so far: val nodes = Array("home", "mens", "clothing", "jackets") val (rootNode, otherNodes) = nodes.splitAt(1) val tree = otherNodes.fol...
After failing to answer an interview question, I went back home and coded the answer for my own improvement. The questions was: Given two arrays containing a number, but with each element of the array containing a digit of that number, calculate the sum and give it in the same format.There must be no leading zeros in ...
I have a function that essentially searches out a value in a table by looking through the column headers and row headers to locate a data point. The function takes the sheet name, the column header name, and row header name as arguments, and I have an error handler set up if any one of the methods performed with those ...
This is the basic structure I usually end up with whenever I'm writing a simple application. More recently I've learned about singletons and have started to incorporate them into my design, but other that that I haven't changed much about it in recent times. I've been wondering if there is anything in here that I coul...
I've decided to make a text adventure game but I feel that the code I have now is annoying, and as I get farther, it will make it hard to read. Is this a correct assumption? Please tell me what I'm doing wrong so I can improve on my techniques with coding. #VARIABLES=====================================================...
I wrote this code and I am wondering if there is a better way to phrase this. I was considering switch case but I was not sure how to translate this code into that. The purpose of this code is to add a css body class to the webpage depending on if certain block regions show up on the page or not. $varssignifies a path...
How can I improve this program? #include <stdio.h> #define MIN 80 int main(void) { char line[MIN]; int i, c; for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i) { if (i < MIN - 1) line[i] = c; else { if (i == MIN - 1) printf("%s", line)...
I have an implementation of flatmap for std::vector. However, I find the repetition of the inferred return type to be ugly. And, in general, I suspect that the implementation could be cleaner or more general. template<typename T, typename FN> static auto flatmap(const std::vector<T> &vec, FN fn) -> std::vector<typename...
I'm trying to write a simple python script that acts like the nc program (netcat). I've got it working on OSX (the client that is) by testing against a netcat server, but I'm unsure about the way I've implemented it. I'd appreciate it if anyone could give me some advice and/or let me know how you would implement it as ...
I created a Caesar Cipher Program in Tkinter, to help me learn the Model-View-Controller concepts and Tkinter in general. The code works, but it is a mess, and I want some help on cleaning it up, reducing junk, and just making it better. import string import tkinter as tk from tkinter import ttk class TextIO(tk.Frame)...
In order to improve my c# (which is fairly basic at best) I decided to try to serialize a simple mesh to a file using the JSON.net library. Simple mesh in this case means an array of vertices and a number of arrays of triangles constructed from 3 vertices each. No materials or animations or anything fancy. Vertices hav...
On a whim, I came up with this program to act as a helper class for base changing, if I require it in the future. It was made to support fixed-point and negative inputs, but they are basically a hack. I used conventional mathematics for the algorithm, and I welcome any appreciation or criticism that may come my way. No...
In Tavern on the Meta, our spam detector is a bot named SmokeDetector. While you can ignore the bot, you can't ignore specific replies to Smokey without ignoring users, so I wrote a UserScript to hide SmokeDetector messages and replies/calls to it by other users. Click Here to install. It's also available on GitHub and...
I am trying to sort a list on basis of C before . Is there better way to do this? import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class MainClass { public static void main(String args[]) { List<String> activeLoadList = new LinkedList<String>(); List<String> tempList =...
I've created a simple Hangman game (not finished yet). What could I improve? (This isn't intended to be object-oriented but suggestions on that are also welcome.) What are its flaws? Here's the code: public partial class Game : Form { private ReadFromFile readFromFile; private Random random; private str...
I'm creating a console application that takes as input starting column and starting row, also the ending column and the ending row and it's going to output all the possible way's to get to that point and also highlight the best turn/s. It's all working, however, I'm not satisfied with the time it takes to calculate it....
I wrote the following code to read the config/property files. I will be exposing my api as jar to multiple application teams. Functionality: Reads the property files and returns the resource bundle object. I am returning the resource bundle object as, there can be multiple config files in the application. Getting the ...
A zero-indexed array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A. For example, consider array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 The dominator of A is 3 becaus...
I have a Pub/Sub class that will call Notify() when published and that Notify() could take around 10 seconds, so I need to make sure that this does not block the UI. public static class NotificationService { private static Dictionary<string, INotification> Observers { get; } static NotificationService() { ...
I am working on a Spring-MVC application in which there are around 2-3 methods which are quite big and complex, but only one of them worries me, especially for maintenance or changes. As changes in the method can immediately change some critical functionality in the project. The application is basically a Note-taking a...
I am using the ancestry gem to organize my post categories tree. I have 8 parent categories, and they all have many child categories. To retrieve an array of child categories, I use: parent_category.children I defined these relations in my category model: has_ancestry has_many :posts has_many :users, through: :...
I have started learning Java recently and I solved the following problem on Hackerrank. The challenge is to : You are given NN sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick. Suppose we have ...
This is a follow up to my previous question, Base-changing numbers in Java I have followed @Pimgd's advice in the answer to that question, and I'm posting the improved code for any further review. Note: I didn't bother with whitespace in the test method, because I don't use it anyway. It also isn't up for review, it's ...
Note: this is from a COMPLETED course. This is not a ploy to get help with homework, as I have already received a 100% on this assignment (last year). I just want to become a neater programmer. Can you please provide me with some stylistic feedback? Note, the assignment did not allow for the use of objects at the time ...
I wrote a simple algorithm for finding all possible letter combinations of a single word. I want to know if my code can be improved in any way, although I'm mostly interested in efficiency. You can ignore my notes if you wish, they are mostly for myself and the questions in them are not the ones I ask answers for here^...
I have got an array of javax.security.cert.X509Certificate and need to convert it into an array of java.security.cert.X509Certificate. My thoughts when I implemented the following code was that I must keep the order of the certificate thus I used a LinkedList. In the first step I am converting all of them into the new...
I have created a program which takes a value x and uses this value to create a power of ten value like so 10 ** x. This has then been used as the maximum number of a range 1..(10 ** x), which has been expanded using the splat * method to create an array of numbers, and then assigned to the variable num_array. Using th...
I'd like to learn if my rewrite is worse than the original, less clear or less "idiomatic". I've found this code that handles updating two dimensional matrixes in Elm: type alias Matrix a = Array.Array (Array.Array a) type alias Location = (Int, Int) get : Location -> Matrix a -> Maybe a get location m = Array.get (...
import socket,time s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('',0)) port=s.getsockname()[1] s.setblocking(0) lines=[] while True: try: data, addr = s.recvfrom(1024) if addr not in clients: clients.append(addr) if not lines: for client in clients: ...
I have a form code behind and it has what are called "Common Utilities". Basically the original author made a super class that is embedded into the main form code behind. What is the best way to refactor this? And what methods can stay in the main form? I think my issue is in each of these methods there are referen...
Following the tutorial from Filip W's blog, I've ended up creating my own implementation for a custom ActionFilter. This logs the execution name, action, parameters and elapsed time of every ApiController in my solution. The post is a bit old (2013), that's why I'm still thinking it must be a better/simpler way to do ...
I am working with synchronization for the first time. I wrote some code that I have to implement in my current work. I wanted to know if I am doing it right or am I making a mistake. Whenever a new list of data is downloaded, NewDataArrived() is called. This method then calls the ListData() that returns the list of pr...
I'd like someone to double-check my use of Atomic primitives, because multi-threading is hard. What I don't want to do is locking the whole get method, or having too many pre-checks per get() call. private final static AtomicReference<T> REFERENCE = new AtomicReference<>(); private final static AtomicBoolean IS_CREATE...
Disclaimer: My code is translated from Peter Norvig's Python code. This simple code uses only two techniques: Constraint Satisfaction and Depth-First-Search. Backtracking is not implemented. Here's the code: Board.java package core; import java.util.*; import static core.Constants.*; /** * This class represents a ...
I'm somewhat new to TDD and unit testing, but I've written a suite of unit tests to check my functionality. The basic classes automate simple load and unload operations from s3 and redshift, and allow one to use custom SQL if needed. I've also implemented an execute method which will try an operation on a dev databas...
I had an exercise as below for an interview. I've added my implementation at the end. How could I improve it? Exercise description: Develop a simple vector based drawing package. Your application should support the following 5 drawing primitives (we will call them widget) 1) rectangle 2) square 3) ellipse 4) circle ...
The newer version of this question is located here: Cyther: The Cross Platform Cython/Python Compiler (Take 2) I am currently writing a Python library (soon to be published)that automatically compiles a Cython/Python file to pure -O3 C, without the user having to do anything other than: C:\Project_dir\> cyther example....
For my current project I need a circular buffer, which is able to do the following things: Push something to it (to the head). Pop something from it (from the tail). I don't need the popped data. Peak the head and tail (no popping). Iterate through the currently contained elements. Here is my C implementation. circul...
I have this class: public class MapController { private Polyline _currentPolyline; // The line connecting two locations on the map private GoogleMap _map; private Context _context; public MapController(GoogleMap map, Context context) { _map = map; _context = context; } /** ...