instruction
stringlengths
71
71.9k
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; } /** ...
I would like to improve everything that can be improved. I don't understand regex a lot and what could be wrong. The main improve that I am looking for is related with errors. I want make the code robust to deal well with all kinds of errors. I could try to run in production and wait to see the errors, but I can't. At ...
This is a working program I made to roll dice a specified number of times, show how many times each number (2-12) occurred, and the percentage of the total rolls that each number got. I'm trying to make improvements to the efficiency of my code. I've already found one, as noted beside int[] results on line 15. Are ther...
I've recently begun to teach myself to code. One simple project that I wanted to do was create a Caesar cipher that works well. Now that I feel I've accomplished that task, I'd like to know how I'm doing with overall code quality. Here's the code. import java.util.Scanner; public class Encryptor { private char[] ...
I've been studying computer science for around two school terms now. Currently, I'm making a Caesar Cipher program as a base for my examination, this is so that I can use the 15 hours to either add, or improve my code. Please, give me some feedback on how to improve my code or, at least, make it clearer. class Function...
It would be great if I could get this code reviewed. I would love tips on how I could improve my code. Problem You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all available items. From this list you would like to buy two items that add up...
I'm currently creating a game engine for my personal project. And I'm currently implementing Entity and Component System. Classes and Interfaces Definitions Here the classes and interfaces that involved to this problem: Entity: abstract class for any entity in the game, it does not implement any interface or class. ...
I've completed the small challenge in the eloquent JS book to create a chess board pattern: Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chess bo...
I have a code which checks if any of the 4 textfields on our server contains text. If even one of the four textboxes is not empty, the generated table won´t skip that row and will draw it, otherwise the row will be completely skipped and not shown in the table. For that I declared the variables for the words and the B...
I am working on an app in which I need to get destination list from server and set it in autocomplete text view. I am using text watcher and on its onTextChanged event I am fetching destinations data using async task. My problem is I am not sure that am I doing it in a right way. Please review my code below FragmentHot...
I'm learning PHP, HTML and SQL - and wondered if anyone could take a look at this code and give me some feedback? <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> <title>Store product information</title> </head> <body> <?php $host = "localhost"; $database = "shopDB"; $us...
Yesterday I had posted a question regarding optimizing editMethod here on code-review. Thanks to an awesome answer by Pimgd, I was able to merge conditional checks, checking conditions and few other things. I am posting this as a follow-up question for the other question for further optimization of the method. All sug...
This is the code for an AngularJS controller that I've written: app.controller('employeeController', function (employeeService) { var Controller = this; Controller.employees = {}; Controller.fetchedEmployee = {}; Controller.populateTable = function (data) { Controller.employees = data; }...
I'm a .net programmer with littler experience in AngularJs and Javascript. I have implemented an AlertService, AlertsController and Alerts view for alerts/notifications in my system. PaymentService is a service that uses the alert service to notify user of things. Could you please give me any comments about my code? A...
I made this Tic Tac Toe game and I would like to know your opinion and what can be improved. I also want advice about making it check if someone wins. I'm 10th grader, so I still need to learn a lot. #include<iostream> #include<windows.h> using namespace std; int main() { char x1,x2,x3,x4,x5,x6,x7,x8,x9; int x, i, a; ...
I tried to write a lock-free list in C++. Unfortunately, the performance compared to an std::list secured with a simple mutex is bad. What do you think? Are there major performance or code-style issues? #include <atomic> template <typename T> // lock-free list-container class lf_list { // ~~~~~~~~~~~~~~~~~~~~~...
I am looking for the elements that are zeroes in a square matrix (of size n), as a list of pair. I don't really like the following code, some condition seems rendundant but my knowledge of OCaml is limited and I can't find an elegant way to refactor it: let find_zeroes input_matrix n = let rec aux i j n = i...
Intro to Computer Science project here. Calculates the hat, waist, and jacket size of the user when given age, height, and weight. Seems to output correctly. Here are the guidelines for the assignment. Write a program that asks for the user’s height, weight, and age, and then computes clothing sizes according to t...
I am going deep on this array in order to make an id comparison. I want to know if there is a way to use like a kind of flatten function to avoid using _.each the way I am using it because I think it is not a good practice. .json file: [ { "enterprise" : [ { "id" : "743512", "name" : "Hellen...
I need to find the percentile where a list of values is higher than a threshold. I am doing this in the context of optimization, so it important that the answer is precise. I am also trying to minimize compute time. I have a O(n) solution which is not very precise, then I use scipy's minimize optimizer to find the exac...
I have the following code made to output the following: Is there an efficient way to simplify it and not have to repeat the same if(!empty($st[$i]['feedback'])) { code block 2 times just to seperate 2 feedback lines with a echo '</div><br><div class="row center">';? <?php //Get 4 Feedback from Database; $st = fetch("...
name = company_location for i, j in enumerate (list): if j == 'Last 10 Accidents': last = i try: date1 = list[last+28] employee1 = list[last+31] days_lost1 = list[last+49] days_paid1 = list[last+43] with open("report.csv","a+") as report: ...
I need to calculate the minimum number of jumps to reach the end of an Array with dice throw. Array values may be negative/positive: When positive - move forward When negative - go back The array may also contain an R value, which means that the player have to throw the dice again. The start position is marked on ou...
(See the next iteration.) I have this tiny library for building HTML pages in Java code: HtmlViewComponent.java package net.coderodde.html.view; /** * This abstract class defines the API for logical HTML view components, that * may consist of other view components; * * @author Rodion "rodde" Efremov * @version ...
I want to generate statistical reports and I have many different where clauses so the function became long. I did much refactoring, but it is not enough. Can someone help me with some techniques that these techniques make the function short and easily readable? public static function allRejUserByProv($prov = '', $gende...
I posted a similar question “Curious Numbers” (HackerRank PE 34) recently (but in a different language/platform altogether). I'm starting to learn JavaScript and decided to take the challenge again and adapt it to this language's features and quirks. While I could have written many of the functions below using for-loo...
Inspired by a PPCG answer, I wrote this code, which shuffles the autoboxing caches of Number subclasses. This leads to, among other things, outputting 2 + 2 = -72 after invocation of EvilStuff.doEvilStuff(Class<? extends Number>,String,int). (The result differs for different invocations, due to reshuffling). I use a s...
(See the previous (and first) iteration.) Now, I have incorporated all the modifications proposed by janos, and, thus, I have the following: HtmlViewComponent.java package net.coderodde.html.view; /** * This abstract class defines the API for logical HTML view components, that * may consist of other view components...
I am currently making Pong in C++/SDL2 and after a while of tinkering, I have come up with a solution! This function gets the hit position and returns the necessary direction change: MoveDirection Ball::getHitPos(const Player& player) const { MoveDirection dir; //Direction of movement //If ball is moving left ...
I would like to get my code for implementation of simple sorting algorithms in idiomatic python code reviewed. I am looking for feedback on python idioms used, better ways of doing the same thing. I am familiar with FP, and I am willing to put in effort to get myself familiar with pythonic idioms such as list comprehen...
I'm currently attempting to learn Haskell after a fair history of imperative programming. When I saw the Pizza Hut Pi Day math problems, I thought the first one would be a good candidate for my Haskell experimenting. The question is: I’m thinking of a ten-digit integer whose digits are all distinct. It happens that t...
This program uses UDP broadcast to find app servers on the local network. When a server receives a client broadcast, it sends a port (integer) to the client which will later be used to create a TCP connection. The Server portion of my code is written in C#. The UdpPoller method returns an IObservable<IPEndPoint> which...
I have inherited a PHP base class for an API call to a music provider. It is functional, however it makes me feel that there are some "magic" nature behind it that makes me un-easy (or maybe I'm not knowledgeable enough to understand it completely). After initializing the apiObject I can make calls such as: $results = ...
The function wants to achieve to find all distinct subsets that sum up to an given number. results = [] def rec_subset_sum(current_elements, available_elements): for i, inspected_element in enumerate(current_elements): # Get list of all smaller available elements smaller_elements = [q for q in avai...
I want this to be similar to the STL algorithms but I don't find it elegant nor concise at all: #include <iostream> #include <iterator> #include <vector> #include <algorithm> using E = double; template <typename IT> E std_dev(IT begin, IT end){ auto N = std::distance(begin, end); E average = std::accumulate(be...
I decided to finally write up a Tic-Tac-Toe implementation. Since I'm currently learning web development, I decided to write it in JavaScript. My main problem, and what I want reviewed here is my checks to see if there are any winning plays on the board. I figured the easiest way to start out with would be to "brute-fo...