instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
This is about to show the results of a runners' competition. It shows us the runner's number, the sex ( 1 = man, 0 = woman ), age and time. After showing the results of these runners, it shows the winner of each sex. package *; public class ArraysSix { public static void main(String[] args) { //int pm = pos...
stackexchange/codereview
I wrote this script for a code challenge on TreeHouse. I already submitted my code, but I am looking for an after the fact feedback. The challenge was to open a file of text, remove specific words (provided in another file) and do the following: Output to the screen in a readable fashion 1. total word count after fi...
stackexchange/codereview
Background I am since a long time ago developing a JavaFX application for creating and analysing 'Mech loadouts for Mechwarrior Online. I previously had a very crude search function based on a FilteredList and a big and complicated predicate. This proved to have many drawbacks, prefix hits were a pain to do and this m...
stackexchange/codereview
I have this code inside a post route: The first one is to alert me when a user registers on my site: sendgrid.send({ to: "my@email.com", from: "myother@email.com", subject: "[ALERT] " + req.body.eventDate, html: "SOME HTML", }, function(err, json) { ...
stackexchange/codereview
Is there a nicer way to write the maybeWhen portion of displayConnectionAction ? I want to conditionally display an Action depending on whether or not the player is connected. This bit of code is lifted from a wider system where there are multiple calls like displayConnectionAction (conditional actions built up by a R...
stackexchange/codereview
There are two ciphers, Caesar and Vigenère, both with an encoder and a decoder. Both work with spaces and can be passed any case (the output will be always lowercased, though). I'm a complete Haskell beginner and so my implementations are quite ugly and wordy. I'd welcome any help which would help me refactor the code,...
stackexchange/codereview
Below code just for assemble data into network packet. but the code logic has many repeat parts to convert integer for byte array. what's the best method for such purpose to simplify below logic? typedef struct _INFO { int pid; int score; } INFO; void send_packet(int connfd,INFO* info,int len) { int buflen...
stackexchange/codereview
I'm new to Python and experimenting with some simple scripts. I would appreciate if you could give me some suggestions on how the following code can be improved or made simpler or anything in general. #Coverts MAC Addresses into cisco format def mac_conv(mac, sep='-'): #split mac address into 3 groups splitted_mac...
stackexchange/codereview
OK, maybe crazy overkill and a little silly, but why not? Here's a Python FizzBuzz Acceptance Test: import unittest from fizzbuzzmodule import fizzbuzz class FizzBuzzAcceptanceTestCase(unittest.TestCase): ''' Test that fizzbuzz(int) returns int unless multiple of 3 (then returns 'fizz') multipl...
stackexchange/codereview
I decided to try to make my own tree style class. I may use it in a project, but it's primarily to practice. I would appreciate any feedback for improvements, best practices, etc. import sys class Node(object): def __init__(self, name=None, data=None, parent=None): self.name = name self.data = data...
stackexchange/codereview
I initially thought that this was just an architecture issue so I placed it on programmers as Thoughts on refactoring a generic DAO. Then I asked on codereview meta here and decided to put up the code here. Here's a github link if someone wants to see there. There are four DAOs - DAODelete, DAOUpdate, DAORead, DAOIns...
stackexchange/codereview
The problem is that I had an interview for a gaming company and I had to write a prototype of a Match Three style game. The time line was 3 days. I made the code in about 2 days and sent it to them. Then I had a rejection and a comment that my code has "many problems with performance, basic programmers mistakes and pos...
stackexchange/codereview
I would like a review of: Correctness, especially around edge/corner cases Efficiency Readability and/or style Appropriate use of Java idioms and data structures In particular: Have I missed typical idioms/patterns useful to solving the problem? Could I have reused existing/popular framework/library code? Less inte...
stackexchange/codereview
I was trying to make a sorting algorithm for an array of integers. Here's are the steps/theory: It turns an array into a HashSet, iterates over every integer value from the minimum value in the array to the maximum. It carries an array that starts with 1 element, the minimum. While iterating to higher values through in...
stackexchange/codereview
This is my try on the 99 bottles of beer on the wall lyrics, made in Python 3. I am a beginner willing to learn so be gentle :) def lyrics(): if count > 1: print(f"{count} bottles of beer on the wall,") print("") print(f"{count} bottles of beer.") print("") print("Take one do...
stackexchange/codereview
Just starting to get the idea of MVC with tkinter. I wrote this simple program and I'm looking for feedback. There are no errors, but I don't know if I set it up right or not. import tkinter as tk class Model(): def __init__(self): self.list = ["email", "sms", 'voice'] class View(tk.Frame): def __ini...
stackexchange/codereview
I have a list of Script that i want to execute them in parallel, i already find this way in Creating dynamic number of threads concurrently, so i use this piece of code here : private int i;//<---------------------------------(1) private String[] listScript = {"Script1", "Script2", "Script3", "Script4"}; private void ...
stackexchange/codereview
Using the following query I'm doing transactions with two tables BEGIN TRANSACTION UPDATE SalaryTrans SET carried_forward_amount = @carriedForwardAmount, net_wage=@netWage, processed_date = @processedDate WHERE employee_id=@employeeID AND reference = @reference DELETE FROM CarriedForward WHERE employee_id = @employeeI...
stackexchange/codereview
In briefly: I'm working on a little chat program just for fun. I am using threads to control two main parts of the application. I am making a socket controller class based on the following design: //this is a "main.cpp example" for the design std::mutex mtx; class AThreadedClass { public: AThreadedClass() { ...
stackexchange/codereview
I want to use libusb library in my C++ application. I have created classes which wraps libusb functions. You can see that libusb API is split into 8 sections: http://libusb.sourceforge.net/api-1.0/modules.html For me the most necessary sections are: Device handling and enumeration Synchronous device I/O Library initia...
stackexchange/codereview
First, my Book object: public class Book { public static final String TABLE_NAME = "BOOK"; public static final String COLUMN_ID = "ID"; public static final String COLUMN_TITLE = "TITLE"; private long id; private String title; public Book(String title) { this.id = -1; this.titl...
stackexchange/codereview
I'm working on a material/shader graph system. I came up with a simple solution, but nodes that weren't connected were used in some situations. So, I thought of using Kahn's algorithm to execute nodes' tasks. I'm not quite sure if it's a proper implementation. I've only played with it, so it's a single file to avoid ju...
stackexchange/codereview
In the UI I have a single search text box into which users can type a query. The query will split the string and compare each word to each configured column in the database and return the matches. The following code works, but I don't know if there is a better way that I'm missing. /// <summary> /// Returns a list of u...
stackexchange/codereview
I have the object with values. I trying to filter based on values. var data = { "map": { "0": ["abcd"], "1": ["efgh"], "2": ["xyz"], } } In above object I am trying to filter xyz which are have in array values. Expecting output: { '0': [ 'xyz' ] } I done the code but I am not sure it's efficient way....
stackexchange/codereview
The following code is to enlarge pictures using bilinear interpolation. What can be modified in the function of slow_rescale to make it more efficient? I expect to modify it from the view of Principles of Computer Organization. unsigned char *slow_rescale(unsigned char *src, int src_x, int src_y, int dest_x, int dest...
stackexchange/codereview
Newbie here. I have this gqlgen api with sqlc update code, which updates the user by given id with provided fields: // graph/schema.resolvers.go ... func (r *mutationResolver) UserUpdate(ctx context.Context, id string, input model.EditUser) (bool, error) { // Validate v := validator.New() if err := v.Stru...
stackexchange/codereview
I have a test which looks like this: Create a base class Human Human class needs to have a method Talk The Human class needs to have to descendant class Man and Woman Both Man and Woman should have their own Talk method (basically rewrite the method) The Man class should have a private property _foo It should have a ...
stackexchange/codereview
I am learning to code in the Assembly language for the x86 architecture. I currently know of a few registers and certain arithmetic operations like add, sub, inc, dec, mov and to check for conditionality using certain jump statements. I am using some "ready-baked" code for input and output. The input - call_hex reads h...
stackexchange/codereview
Take a look at following code: /*abstract*/ class Capturable { object _lock = new object(); public bool IsCaptured { get; private set; } public bool TryCapture() { if (!IsCaptured) lock (_lock) if (!IsCaptured) return IsCaptured = true; re...
stackexchange/codereview
Could I get some feedback on this code? I included a test case as well. This code computes the longest common sub sequence given paired data, it was not part of any challenge I just did it to learn about dp. To my understanding it runs in \$\mathcal{O}(m*v)\$ where \$m\$ is length str1 and \$v\$ len str2. def lcs(word1...
stackexchange/codereview
Find all pairs in an array that sum to a given number without using HashMap. Duplicate pairs are not allowed. Input array cannot be modified. input: {-2, -1, -1, 5, 7, 7, 7, 7, 8}, target = 7 output: (-1, 8) As it is mentioned, using HashMap is not allowed, so I decided to use binary search. GitHub public class T...
stackexchange/codereview
I have a big Python dictionary with more then 150,000 keys every key has list value. This dictionary contains infinitive words as key and all grammatical forms of these words as values: {"конфузити": ["конфузить", "конфужу", "конфузиш", "конфузить", "конфузим", "конфузимо", "конфузите", "конфузять", "конфузитиму", "ко...
stackexchange/codereview
I am trying to convert objects inside an object(arbitrary objects) to Json and later retrieve it. I have developed some codes and would like to share if there is any problem in the code. import json Here is the first class class Foo(): def __init__(self,x,y,bar): self.x =x self.y = y self.b...
stackexchange/codereview
I am using below code and for result i am using interface for call back purposes. @Override public void onResult(String result) { if (this.mClient != null) { this.mClient.cancel(); mProcessing = false; } try { JSONObject j = new JSONObject(result); JSONObject j1 = j.getJSON...
stackexchange/codereview
I am using a public validating sub to help validate the other subs. Is this the most efficient way to do this? Public Sub Validator(sender As Object, e As EventArgs) Handles GrossRevenueButton.Click, CPTCodesButton.Click, EstablishedVisitsButton.Click Dim validater As Integer = 0 'this is the variable that gets sen...
stackexchange/codereview
I'm looking for a way to quickly determine that maximum value of t such that tanh(pi/2 sinh(t)) is strictly less than 1, for a given precision. I have reproduced the code I am currently using to do this below: #include <cmath> #include <iostream> #include <random> #include <boost/math/special_functions/next.hpp> #inclu...
stackexchange/codereview
I have an Entity Framework table of Addresses. I'm building a Repository that would allow me to search for an Address by either parts of the Address or the whole address. Here's what I've got so far: public class AddressRepository : Repository<Address> { public List<Address> GetByAddress(string street, string city,...
stackexchange/codereview
First of all, I am a beginner in Python trying to learn optimizations and proper coding standards. Here is a snippet of code that checks if a number follows the rule: first AND last N digits contain all unique numbers from 1 to N, but in any order. This also means that in either first N or last N digits, each number ap...
stackexchange/codereview
This is a Python script for counting the lines of a compressed file: #!/usr/bin/env python3 import gzip, bz2, zipfile, os, sys def openZip(zfile): f = zipfile.ZipFile(zfile) firstFile = f.filelist[0].filename if firstFile.endswith("/"): raise Exception("This zip file contains a directory.") re...
stackexchange/codereview
I have a very simple app which removes buttons and re-adds buttons to certain layouts when a button is clicked. The problem is this process is taking a very long time. How do I speed this process up? red.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { ...
stackexchange/codereview
The main advantage of this pattern is when I often create and destroy objects, which in this case are often used. I made this because I needed to track several short timers at the same time, but it can also be used for stuff like missiles or else. #include <vector> #include <queue> #define itv(TYPE) std::vector<TYPE>...
stackexchange/codereview
This is my naive approach: $sample1 = [3, -20, 1, -19, -4, 6, 77, -1, 0, 6]; $sample3 = [4, 5, -7, 0, 2, 44, -3, -5, 66, -7]; $sample4 = [4, 25, 1, 6, 9, 5, 999, 4, 43, 2]; $sample2 = []; for ($i = 0; $i < mt_rand(10, 30); $i++) { $sample2[] = mt_rand(-1000, 1000); } extractNumbersThatSquaresAreGreaterThan($sample1...
stackexchange/codereview
This is a C++17 is_integral trait implementation. Most implementations exhaust all integral types: bool char, char16_t, char32_t, wchar_t [unsigned] short [unsigned] [long [long]] int However, it is possible that the implementation defines some extended signed integer types and extended unsigned integer types. One w...
stackexchange/codereview
I would like to write a pseudo version of List.map with the help of the Event and Thread modules: open Thread open Event let rec tmap f ls = let c = new_channel () in match ls with | [] -> [] | h::t -> let _ = create (fun c -> sync (send c (f h :: tmap f t))) c in sync (receive c) Call...
stackexchange/codereview
I have implemented a class Vector to learn about data structures and algorithms and how to implement them using C++. I have yet to implement some std::vector functionalities e.g. custom allocator template parameter, iterator/const_iterator classes. I'm learning C++ through a C++11 book and trying to learn C++14 and C++...
stackexchange/codereview
When a Wizard casts the Monster Summoning spell, all of the summoned monsters shall follow his command. Should the Wizard interact with his summoned monsters directly (what are the potential pitfalls in this case?) or indirectly through a mediator? In my code below, I'm using a mediator, but since such a specialized m...
stackexchange/codereview
I've written a simple lock-free multi-consumer/-producer FIFO queue. It's supposed to work like this: At any time many consumers may read from it At any time multiple producers can write to it, added elements will be made available later After write modification is finished, we call makePushedElementsAvailable(), so t...
stackexchange/codereview
I was inspired by a previous post here that also wrote a pizza ordering application. This is the attempt I have made using OOP in mind as I thought that would be just the way to go. Here is Pizza.java import java.util.ArrayList; public class Pizza { private String size; private ArrayList<String> toppings; ...
stackexchange/codereview
I am currently working on a small website for my scuba diving club, and it needs a "simple" login system to allow members-only features etc. I've been using the php-login-minimal as the base for the PHP login: https://github.com/panique/php-login-minimal It works by creating a session cookie if a user is logged in. Thi...
stackexchange/codereview
This is more of a 'model' of TicTacToe, as you'll see it's not "gameified" in the sense that it will allow for inputs and outputs nor will it record any "active" state of the game but those things are trivial to implement. I'm cheating a little bit on the functional paradigm in my function to rotate the grid, but this ...
stackexchange/codereview
I'm creating a command-line tool which is supposed to work on both Windows and Linux OS. It will be used to manage our application - start, stop, deploy etc. We have it in bash scripts now (and it works very well for about 6 month), but I want rewrite it in Python with classes. It's big enough, so here are only a few m...
stackexchange/codereview
I have multiple places where I need to make ajax requests to fetch the items corresponding to some ids. However, I only want to make a single request by accumulating these ids and debouncing the actual method that makes the ajax request...So far I've come up with this code, but it just feels ugly/non-reusable. Is there...
stackexchange/codereview
I'm doing a infix to postfix conversion. The code works, but here are some points I want to improve 1) In the line of while ((!operators.empty())&&(order(operators.top()) >= order(token[0]))) If the condition order changes ( check the stack empty later), there'll be a segmentation fault (because I'm calling operators...
stackexchange/codereview
I have a cookie on my site with the following value: eyJGIjp0cnVlLCJBIjp0cnVlLCJUIjpmYWxzZSwiUyI6ZmFsc2UsIkciOmZhbHNlLCJYIjpmYWxzZX0%3D I use this function to retrieve the value from the site so I can use it in the applications my site uses to greenlight certain elements or to block them. function getCookieLawSetting...
stackexchange/codereview
I'm building a Slack bot to facilitate the standups for teams of developers. I want the bot to run async and not have to wait for one person's response before it starts interviewing others. Here's what I think is the solution for it, however I'm not really sure. I would appreciate a second eye on this. const users = aw...
stackexchange/codereview
As I'm getting to grips with front end development I'm looking to consolidate/improve my below HTML, CSS and JS code in terms of adhering to best practices so any advice is appreciated. Quick overview: I'm working on a page which has required me to create a page with a nav bar, a horizontal bar below the nav bar, a ver...
stackexchange/codereview
The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property. Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following: d2d3d4=406 is divisible by 2...
stackexchange/codereview
I would like any feedback on making the unit test for a BlockingQueue class more robust or better? improvements to the coding style, use of the gtest framework, better test cases etc. C++ style suggestions (up to c++ 14). Feel free to add suggestion to improve the BlockingQueue class if you feel inclined to. BlockingQu...
stackexchange/codereview
I wrote a code that requests user input and then converts binary to bcd then back to binary using bitwise operations. While I think my code is good I want to know if there is a better way to write the code. Is there also a way to keep the code mostly the same but getting rid of the arrays for printing out the bit posit...
stackexchange/codereview
I was asked to make a String encryption utility without using encryption API. I basically had to come up with my own encryption methodology! the program was to be able to encrypt a string and decrypt a string and to of course make it nearly impossible for anyone to figure out what the encrypted string says! I would rea...
stackexchange/codereview
I'm working on a project where I'm instrumenting how long it takes to get from one point in my code to another. I've written an LLVM pass that instruments the IR with calls to a simple timing library I've written. Each point is identified by a 64-bit randomly-generated unique identifier. Unfortunately, I'm spending a l...
stackexchange/codereview
I'm a beginner developer and I'm building a calendar for smartphones. I'm using HTML, CSS and JS. I'm not entirely done with the project yet, however, I have the feeling that I'm making a messy code. I'll be posting the link to the git + the code in here, so you can better read it/clone, and help me with design pattern...
stackexchange/codereview
I want to create a function that takes a numpy array, an axis and an index of that axis and returns the array with the index on the specified axis fixed. What I thought is to create a string that change dynamically and then is evaluated as an index slicing in the array (as showed in this answer). I came up with the fo...
stackexchange/codereview
I wanted to see how this code looks, what can be improved and how those improvements can be implemented. I'm still new to C++ so I hope it isn't too sloppy. #include <iostream> #include <string> #include <time.h> #include <stdio.h> #include <stdlib.h> int main() { int warrior, mage, rogue, priest; int...
stackexchange/codereview
I am working on state space search (8 Puzzle) in Python and when I run my program with python3 -m profile, I find out that most of time program performs a few functions. I would like to optimize functions bellow (if it's possible). I am using dictionary node, whose structure is: { 'id': string, # Unique ID of node...
stackexchange/codereview
What is an efficient way to implement the Mergesort algorithm in Java such that it meets the following criteria: Must be multi-threaded. Must retain the Mergesort time complexities. Must be in-place implementation, no copying arrays. Must use Java Collection classes, not an array. Must work on any Java Comparable. My...
stackexchange/codereview
So I've decided to dabble a bit into C, and while it's trippy as heck I've finished an implementation of a linked list for practice. I've pretty sure there's some type of obscure bug or memory leak in here some where since I really don't have a solid understanding of this language yet, so yeah, please review my code an...
stackexchange/codereview
I have a small Coldfusion section of our site that all uses similar JavaScript and CSS files and page design. The code is currently repeated for each file, and I'd like to factor it out and set something up using a master page and templates. Master.cfm page: <!--- Master template, includes all necessary js and css file...
stackexchange/codereview
I'm beginning with Django and I have a Civil Status project. I created my first models.py in order to get a Form, but I had some advices in order to normalize my database. I made this process and I would like to know what do you think about this new restructuration. My old models.py : from django.db import models from...
stackexchange/codereview
I have been developing a simple login registration page with PHP using the repository pattern. Following are the business rules : During registration Email must be unique. Email must be a valid email address. User table columns: id, name, username, password, created_at, updated_at register.php page if($_POST) { t...
stackexchange/codereview
I am studying computer science and recently I developed an application in Java (it is a minecraft mod) that connects a MySQL database and queries to fetch, update or insert data. My DatabaseHandler class is the one that initialize the connection to the database and performs all the necessary queries my application need...
stackexchange/codereview
This function checks if the EndDate of my grid is valid or not. If it is not valid, it turns the bgcolor of the cell to red color with cell-error class. I need some help in optimizing this block of code. It looks dirty right now. function onAccrualEndDateChange(current) { var endDate = $(current).val(); if (endDate != ...
stackexchange/codereview
I'm looking for some feedback on my code here. I want to eliminate duplicating the code through the different button_clicks. I'm thinking with a method but nothing I try works better than what I have. using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.W...
stackexchange/codereview
I have created an Arduino sketch that I am using to send and receive data via serial. It works pretty well and doesn't seem go wrong as long as the correct formats are received. Is there anything I could do to improve this/shrink it to clear up some code smells? String dataString; void setup() { Serial.begin(9600); ...
stackexchange/codereview
A made a shipping calculator, which consists of one field that is validated. jsFiddle HTML: <div class="container main-container" id="mainContainer"> <h1>Калькулятор доставки</h1> <div class="content-container" id="contentContainer"></div> </div> <script type="text/template" id="calculatorSubmitBut...
stackexchange/codereview
I have this PHP code. I wrote it for a webpage it uses parameters. Only one set of parameters can be set at any one time. If both are set its invalid, if None are set its invalid How would be the best way to write it, looks too long to me and i Feel like I have complicated it if($_REQUEST['b_id'] && $_REQUEST['s_id']) ...
stackexchange/codereview
This code calculates the probability of a runner finishing 3rd and it works like expected. I'm pretty sure though that is woefully inefficient. How could this code be transformed in a much more cleaner and performance efficient way? My focus is the nested fors and and the if handlings. def Trd(mylist=[]): third=[]...
stackexchange/codereview
I'm a newbie getting into web scrapers. I've made something that works, it takes 3.2 hours to complete job and randomly have 10 lines blank each time I run this job. Help is much appreciated! import sys import pandas as pd from selenium import webdriver import time from datetime import datetime from bs4 import Beautif...
stackexchange/codereview
I'm still relatively new to C++ and I've written a program that could do with being a bit shorter and faster. I use this same set of for loops many times to cycle through the whole tree of values. I'll use the JSON format to show you a much shortened version of the tree (in reality the tree has another layer of depth w...
stackexchange/codereview
I've borrowed and written the following code to output the disconnect time. All works well but I'm curious as to how I could tighten/ shorten the code. If anyone feels like having some fun then I'd love to see what can be done. Be a learning lesson for me. Excerpt of input: ftp> !:--- FTP commands below here --- ftp> l...
stackexchange/codereview
I am attempting to make a python script that imports a given file. Then on the import of the file, I am pulling a value from in the filename to determine what function to run. I will then eventually extend this to pull all files from a folder rather than explicitly pass it a specific file. The format of the file names ...
stackexchange/codereview
In the following code, there are some repeated commands. How can I reduce it and make the code more concise and automate it more? In the following code, I am trying to read different folder files. The folders have a fixed kind of structure for all different set of data. I want to access those folders in easier way su...
stackexchange/codereview
I've been using a thread pool that I wrote using Windows threads for a while and I've decided to update it to use std::threads. I'm looking for some feedback on how this could be improved in terms of (in order of importance) reliability, usability, and performance. Header #pragma once #include <queue> #include <threa...
stackexchange/codereview
I made a simple web-based file browser with Flask. It also shows some metadata of a file. I have a few questions regarding security though. Is it possible for an attacker to escape out of the preset root directory? Are there any ways to make my code more readable and/or more efficient? Would love to hear some feedback ...
stackexchange/codereview
I wrote this program which takes all the bits in a number and shifts them to the left end (for example: 01010110 --> 11110000). It's and exercise from a book. It works, but it seems to be very wasteful to use integers (I only need 8 bits). Can you tell me if the code is proper or not? Is the algorithm good? #include <...
stackexchange/codereview
This is a revision of the code posted here. It's a Makefile that I want to use for compiling Sass files to CSS in web projects. For this, I typically have two folders css and scss in a theme's top level directory. The full Makefile has other duties (such as optimizing images), and needs to be run from that directory. I...
stackexchange/codereview
I have this string containing this block of code: [General] StartWithLastProfile=0 Profilist.notifications=true Profilist.dev=true Profilist.dev-builds=80k Profilist.launch_on_create=true [Profile0] Name=Dev Profilist IsRelative=1 Path=Profiles/j0a1zjle.Unnamed Profile 1 Profilist.tie=0 [Profile55] Name=Main IsRelati...
stackexchange/codereview
My task in C#: Random missile generator generating 2 types of missiles each second: ThermoNuclearBomb and FacetBomb Missiles have properties Serial Number, Type Air Defense System, that is identifying the 2 types of missiles and neutralizes each of them with a different gun (AntiThermoGun and AntiFacetGun) Air Defe...
stackexchange/codereview
I have a MVC framework, and I am struggling with the following dynamic menu code. A menu is pretty much HTML, so technically it should reside in the View, but the dynamic part is driven by PHP and a config class that holds all the menu items. Where would I place this class? (model layer, view, library, or helper folde...
stackexchange/codereview
I am new to C++ and game programming. I am using SFML for graphics. I wrote a clone of Sokoban in my free time and to be honest, I am not happy about the result. I feel like I reused some code too many times. Please don't hesitate to criticize every bit of it. Also I am open to advices about the improvements and update...
stackexchange/codereview
I have a standard table-test unit-test in Go. How can I make it simpler, easy to read and succinct? I'm looking suggestions for: Structural refactoring. Less and simple code to achieve the same thing. test.go func Test_Parses_Books(t *testing.T) { books := xmlDoc.Book type tester struct { texts ...
stackexchange/codereview
I am making a class method in ruby to convert from roman number to Arabic and vice versa. However the loop is run to match each character and again to match with roman mapper. Can I optimize the same? class String private def roman_mapping { 1000 => "M", 900 => "CM", ...
stackexchange/codereview
I've got a database table in my application called "periods". The structure of the table is: Year (Number) Month (Number) Period (Text) The Year column stores years (Say, 2016), Month stores months (1-12), and period stores the period of the month/year - eg; November 2016 = 11/16, so period = 1116. In the table, it s...
stackexchange/codereview
I want to provide, in the the spirit of C++11/boost make_shared and C++14 make_unique, a production-ready make_auto for C++03 compilers. So, inspired boost's make_shared implementation for C++03 compilers, I provide N overloads (0 to 10, currently) of the same make_auto function. template <typename T> inline std::auto_...
stackexchange/codereview
I'm writing unit tests for a web application that has quite a lot of UI interactions. I would like some feedback regarding on how to handle click events with asynchronous code. My goal here is to simluate users interacting with the page. That's why I'm triggering events rather than making function calls. Here is my id...
stackexchange/codereview
A friend of mines needed some help. He wanted to build up two linked list and then compared them to see if they had the same data values. Finally a 3rd link list would contain the nodes with duplicated data. The linked list holds int data btw. I redid his code and I was aiming to be as simple and clean as possible but ...
stackexchange/codereview
I sometimes have to schedule some tasks and wanted to have my own reusable scheduler. Since I like the Rx, I build it on top of it. Follow-up There is a newer version of the Scheduler. The Scheduler class is really simple. It's backed by a newer implementation of my old CronExpression. There are currently only these ...
stackexchange/codereview
Please review my implementation of Fermat's Factorization. fermat :: Int -> Maybe (Int, Int) fermat n = odd' n >> (go $ ceiling $ sqrt (fromIntegral n)) where go a = case (try n a) of j @ (Just _) -> j Nothing -> go (a + 1) odd' :: Int -> Maybe Int odd' x = if (odd x) then J...
stackexchange/codereview
I'm quite new to Rust, and am working on a virtual machine image decompiler. I have some working code that uses match to check opcode numbers, but it doesn't feel very idiomatic, and am wondering what alternatives I should consider. First up is the cleanest case: // Stop, or next instruction? let next = match o...
stackexchange/codereview
Is this an efficient way to implement the Roman Numeral Converter ? So first, I put all the digits of the parameter number into an array. Then I loop through this array, and multiply a 10 power based number to the current digit. I use the resulted number in multiple statements, to compare it with special cases or numbe...
stackexchange/codereview