instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have revised my other question's code which you can find a link to here. This is just an automated turn based battle simulator which means everything comes out about 1 second at a time, and player and enemies roll dice to determine the amount of damage they have done. I have updated it thanks to the last answer doing...
stackexchange/codereview
I have a lookup table "RequestTypes" that has the following data: ID Type ---- ----- 1 Leave 2 Loan 3 BlahBlah Using EF, and whenever the need arise to check the type of the request, I used to do something like: if (row.RequestType.ID == 1) { // request is leave } else if (row.RequestType.I...
stackexchange/codereview
I have the following code: let id = ''; let text = ''; // Note: `match` = [full match, id (first group), text (second group)] if (match.length > 1) { [, id] = match; } if (match.length > 2) { [, id, text] = match; } return { id, text }; match could be null, or lengths between 1-3. id and text need to be empty str...
stackexchange/codereview
I've been making an app, which gets data from external device (via bluetooth) and displays received data. I'm still pretty new to programming and I'm struggling to finish this app. I wrote some code, that works well, but I wanted to ask you if my solution can be considered as a good one. Firstly, some background. Exter...
stackexchange/codereview
I recently ported a blog of mine from Python to Go (to improve speed and performance) and while all is great so far, I'd like some help optimising the Markdown function to improve the general performance, maintenance and readability of the function. I have this function because I write my blog articles in Markdown (.md...
stackexchange/codereview
I got this background console script running, which pulls all necessary XML files from the server and stores them locally for faster performance. These XML files contain Graphs full of data, which will be shown inside the application. Right now the user can get to the graphs in about 45 seconds if he directly goes tow...
stackexchange/codereview
I don't truly understand how OOP works and It's stopping me from creating good programs! Below I have a program that will check to see if there are 3 tiles from a gridview in a row. Here's a screenshot of the game. Basically you're not supposed to get 3 of the same colours in a row! But at the moment I've been adding...
stackexchange/codereview
Although I should know better, I wrote my own linked list implementation in C. My goal was to make it a true generic collection, with no need to modify the structure being listed. I only implemented push, pop, peek, append, size, and next. This is sufficient for implementing stacks or queues. I welcome feedback...
stackexchange/codereview
I have the following code which returned the solution I was wanting after running for 1 hour. Are there any techniques I could use to improve run-time? If I were using imperative programming I would just more aggressively cache the partial results, but that's less appropriate for this approach. How should I transform t...
stackexchange/codereview
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...
stackexchange/codereview
I needed a lot of data for a tensorflow project so I made a web scraper to get all of the text and links off of websites then to repeat the process at all of those links. I left it on overnight and it did not get much done, so I spent the day optimizing it. I can't find any ways to optimize it more (If anyone knows a w...
stackexchange/codereview
I have an RPG program which processes a file containing records of subscription details of users. Each subscription record has a "valid from date" and "valid to date" - indicating when the subscription started and ended. I need to check if a subscription is currently valid (curdate holds current date) or should have be...
stackexchange/codereview
I took a class covering HTML, CSS, Javascript and for a final project, thinking of a previous community challenge, I created Simon Says. Going through my code my professor deemed it overly complicated (or did he mean complex?), explicitly referring to my showSequence method in particular. I'm just wondering what and ho...
stackexchange/codereview
I came through a question on Stack Overflow, which shows this array structure: array (size=4) 0 => array (size=3) 'id' => int 1 'name' => string 'Anniversary' (length=11) 'parent' => int 0 1 => array (size=3) 'id' => int 12 'name' => string 'New arrives' (length=11) 'pa...
stackexchange/codereview
Imagine a website that publishes the number of daily commuters in only a graphical form each day using a bar chart. I want to determine the number by reading the bar chart after saving the graphic as an image (the image stuff is not important here). The way I want to read the bar chart is by going to a pixel number (...
stackexchange/codereview
I'm learning to code PHP and gave myself a challenge: Filter array data by matching a specific element value for duplication. I went through it logically on paper then wrote code and it worked on the first try :) But I bet it is the most inefficient way, so to learn I would like to compare it against what others would ...
stackexchange/codereview
I have implemented a class which implements a list of my custom DateObj. I have sorted the list in a peculiar manner based on the current month. I achieved my desired results, but I'm required to call Collections.sort() four times to achieve it. I feel this could be improved. Any thoughts? //Custom Date Object public c...
stackexchange/codereview
I am utilizing an API module for interacting with virustotal.com in order to get AntiVirus results based of SHA256 hashes. The code I have is working but I feel like it can be improved greatly. I think that I am brute forcing my way to some of the text fields I am looking for. Any suggestions on optimization would be g...
stackexchange/codereview
I have the following arrays: Array (db_values) ( [0] => Array ( [system_name] => object_car_brand [value] => Alfa Romeo [id] => 136 ) [1] => Array ( [system_name] => object_car_model [value] => Spider [id] => 137 ) ) Array (db_attributes) ( [0] => Array...
stackexchange/codereview
This is a follow-up of my question here: I am currently working on an application for various statistics. One task is to analyse a good amount of sentences for their word counts. The specifications are: sentences are read from SQLiteDatabase (up to 20k with an average of about 15 words) transformation: split by whites...
stackexchange/codereview
In the SplashActivity of my Android Application, the following sequence of events occur: Check if Google Play Services is installed If Google Play Services are available, start the InstanceIDListener service Check if app needs to be updated Load country info using network IP Previously, I'd implemented this logic usi...
stackexchange/codereview
In the mobile application I have a search page. As user types search keywords I display autocomplete entries. On each keystroke I initiate autocomplete lookup, and I am using CancellationToken to cancel lookups if user keeps typing. I am new to using CancellationTokens, so please review my code and recommend changes as...
stackexchange/codereview
I have a general value called Seed which is required to multiple class. But those class aren't dependent of the class which declare it. class Game { class Settings { public static float Seed = 1337; } } And some class need a Seed value to work. I take the class Noise as example here. class Noise { p...
stackexchange/codereview
I have an sql table with multiple fields and 4 of them are enums. I wrote a script that runs thought the table and retrieve the enums and put them in a 2 dimension array. Unfortunately this script is extreamly slow and I can't fix it. <?php require_once('mySQL_Connect.php'); $con = ConnectToDataBase(); if ($con == f...
stackexchange/codereview
My web API has 3 controllers for get, post and users CRUD. I named it as DetailsControllor, FormControllor and AuthControllor. In the details controllor, I used a switch case to find out which type of details needed, but I found that code is repeated in switch case. Can I use generics to minimize code or is there any o...
stackexchange/codereview
I struggled to figure out how to clear a textbox after submitting it's contents via a button control. I would like to know if my solution is an accepted practice for initializing a control after an action has been made by a user. Is embedding event data (i.e. SendRequested) within a model an accepted practice for updat...
stackexchange/codereview
I wrote some code to encrypt and decrypt some user credentials for services that a locally run application needs to work. I get a password from the user, use it to stretch a key via Scrypt, and then use the key to do authenticated symmetric encryption with ChaChaPoly1305. I use the hostname as salt for the key, so that...
stackexchange/codereview
What I'm trying to do is quite simple: my table has pagination. So if I have 12 items to show and my max items per page is 10, I will have 2 pages, one with 10 records and another with just 2. I created a code that works just fine, but it seems rather dirty. What is the best way to have the same outcome as the code bel...
stackexchange/codereview
I am studying mutual exclusion in college, and we just covered the producer/consumer problem. The class does not involve writing code, but I decided to implement a bounded buffer version of this problem. I have never written a multi-threaded program before, nor have I written a program with mutual exclusion before, s...
stackexchange/codereview
$("#colors_added").html(parseFloat($("#colors_added").html()) + 1); This JS line makes my IDE go Duplicated jQuery selector with the following explanation: Checks that jQuery selectors are used in an efficient way. It suggests to split descendant selectors which are prefaced with ID selector and warns about duplicate...
stackexchange/codereview
I wrote a simple program to count the number of words in a string using C. Would you mind reading it and telling me if the method used is acceptable? Or if there are style errors or ways I can improve it? /*Procedure that counts the number of words in a string A word is any set of characters (or a single character...
stackexchange/codereview
Over the years I’ve seen many C# sieves and despite their varying internals all that I have seen invariably are a static method that returns a List<int>, perhaps with the occasional rare exception of an Enumerable<int>. This is fine for small collections. Granted relatively speaking for some people a 1 million item l...
stackexchange/codereview
This is one of the longest programs I have made with methods and I think I must be doing this rather inefficiently. Any comments to improve would be appreciated. package numberwords2; import java.awt.Component; import javax.swing.JOptionPane; public class NumberWords2 { static String rawInput; static String out...
stackexchange/codereview
I made this method that takes any string and transforms it into a multiline text l; each line having the max (character) length specified by the rowLength parameter. How can I make this better, functionality and code wise? There is currently one known issue. It sometimes adds an empty line at the end because I have to ...
stackexchange/codereview
I've written the following code for computing the powerset of a list (we consider the list has all distinct elements, although it doesn't really matter). Can this function be further optimized? def powerset(A): if A == []: return [[]] a = A[0] incomplete_pset = powerset(A[1:]) rest = [] for ...
stackexchange/codereview
I am currently learning C++, using this book: C++ Primer, 5th Edition. I made this program to help me understand the usage of vectors in C++. I have prior programming experience (mainly Python), and this just seems way too messy to be the right way of doing things. If I'm doing this incorrectly, or inefficiently, then ...
stackexchange/codereview
I am tasked with being able to find the \$n\$th prime number. I've tried to implement something like the sieve of Eratosthenes in increments of 200. The code works and returns the \$n\$th prime number. However, when asking for the 1000th prime number I already notice a significant lag on my box. This code needs to be a...
stackexchange/codereview
I'm not a beginner programmer as I have experience in Node and Ruby, but I'm a beginner when it comes to C++. And as C++ is quite different from these two, I figured I could use any tips, tricks, hints and pointers (hah!) to learn how to actually write C++ and to get the most out of the language. I feel a bit like I'm ...
stackexchange/codereview
Might there be a simpler way to write this code? I'd like to learn to write code more efficiently. def leaves_and_internals(self): """(BTNode) -> ([object], [object]) Return a pair of lists: (list of all the items stored in the leaves of the subtree rooted at this node, list of all the items stored in the ...
stackexchange/codereview
Given a string find the number of meaningful words which could be formed from the string for eg. programmerit forms: pro+gram+merit program+merit programmer+it pro+grammer+it Looking for code review optimizations and best practices. Also hoping for suggestions for complexity better than \$O(n^2)\$, where n is the n...
stackexchange/codereview
I'm writing a toy heartbeat server. Each client, upon loading, registers itself and thereafter, sends heartbeats every X seconds. The server checks every Y seconds if a heartbeat has been received. (In the following code, X = 5sec and Y = 60sec.) A brief description of the components. Data Users and their last heartbea...
stackexchange/codereview
I'm not quite sure I understood thread-safe correctly. I built the following registry: @Service public final class EntityDefinitionRegistry { private static final Logger logger = LogManager.getLogger(EntityDefinitionRegistry.class); private final HashMap<String, EntityDefinition> definitions = new HashMap<>()...
stackexchange/codereview
I decided to roll out my own encryption algorithm, which I am calling "SBC" or Simple Byte Cipher. Essentially, I just take the bytes of the string data, do a Caesar cipher like shift to it, increment through an array of password bytes for each byte in the data (this enables the same letters such as "T" to not always h...
stackexchange/codereview
In prepping to teach a workshop on recursion I wrote this code that uses a maze-building algorithm. In doing so I found it really natural to use generators a lot. I feel pretty happy with how the code turned out but its also pretty unusual and I wonder what yall think of it. This is meant to run on latest chrome (parti...
stackexchange/codereview
I made a Poker-Hands tracker. The 52 cards of the game are in this program represented by their value and their type. For example Ace-heart is stored as "Ah" and 7-spades as "7h". In order to check for a simple Straight I have generated this code, where the array cards is a sorted array with the cards on the table and ...
stackexchange/codereview
This code is extremely slow and ideally I would appreciate someone walking me through getting this going on the GPU, but if nobody has time for that which is understandable, any and all optimisations would be most welcome! Private Sub Picture(source As Image, picturebox As PictureBox) Dim r As Double Dim g As D...
stackexchange/codereview
I'm implementing a JNI library that needs to dispose a few native objects after use. The main library class implements Closeable and is almost always used within try-with-resources. Even then, as the library will be used in by a larger audience within the company, I want to make a safe-guard to make it harder to introd...
stackexchange/codereview
Here is a code file (I use it as a stand alone header file to be included in my projects) that contains macros to generate ANSI encoded strings that when printed are colorized. Also, the module contains useful string functions that are found in PHP standard library: strpos, stripos and substring functions: substr, sub...
stackexchange/codereview
I have answered a Question in Stackoverflow link. a) Create a function called resize that can be used to increase the size of integer arrays dynamically. The function takes three parameters. The first parameter is the original array, the second parameter is the size of this array, and the third parameter is the ...
stackexchange/codereview
The project is an API that will itself make HTTP requests to external webservices. Since this is PHP, we actually chose to use guzzlehttp. Now the library itself doesn't matter much, but I'm scared we'll be stuck with it if it ever has a major change (it already happened in the past). So I thought I'd create an inte...
stackexchange/codereview
I need to store the data in three different ways: storing the data to a std::string writing the data to a given file descriptor both of the above And I hope to use a uniform interface for these three different methods. How to make it better? Here is the code snippet: #include <memory> #include <string> #include <i...
stackexchange/codereview
I wasn't quite sure whether I should do it this way or create a validation service and inject it, but this works: Controller: [HttpPost] public async Task<IActionResult> NewUser(NewUsertVm viewModel) { if (UserValidator.NewUserIsValid(viewModel, ModelState) == false) { return View(nameof(NewUser), viewM...
stackexchange/codereview
Just completed a piece of code - a credit card validation program in python - as a little side project. Having no experience with classes in the past, I decided to employ classes in this project. I am wondering if you could review my code, both appraising the actual code, but also evaluate my use of OOP/classes. The re...
stackexchange/codereview
I was de-serializing objects that had an extra newline that needed to be removed before getting the next object. #ifndef THORSANVIL_UTIL_H #define THORSANVIL_UTIL_H // Removed headers for getDist() and getRandomContainerIterator() // We already reviewed those two. #include <iostream> namespace ThorsAnvil { nam...
stackexchange/codereview
I tried to make a Server using Java with a Thread Pool. Any review is welcome: /* User: koray@tugay.biz Date: 21/02/15 Time: 21:12 */ import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.Stack; public class MyConnectionAccepter { private Stack<MySocketThread> mySocke...
stackexchange/codereview
I wrote the following method which would just call an API which would then update a user's subscription to something. void updateSubscription(String userId, boolean subscribed){ try{ // some stuff restTemplate.exchange(.....) // some stuff }catch (HttpClientErrorExcep...
stackexchange/codereview
I'm a PHP Developer. I'm trying to learn Python. So I tried to create a simple game, a Number Guesser. I tried to comment out as much as possible without making super obvious comments. I also made the attempts message color to be red. Here's my code. # 1. Print a message about the game # 2. Tell the user that the ra...
stackexchange/codereview
I have implemented a thread safe vector, based on std::thread and std::vector. I am new to many of the patterns used in threading and was wondering if there's a more efficient way the locking can be implemented? Also I'm not sure what the best name is to give variables that just get stored right away (i.e. in). Here is...
stackexchange/codereview
The code is the view part of my bookmarker - project for managing bookmarks by categories. It uses Python 3.4/Django 1.6. I have also included models.py for reference. The code does the following Providing relevant autocomplete JSON data Providing details of categories/bookmarks (both are DB models of my project) Open...
stackexchange/codereview
The "Rope Intranet" problem from Google Codejam 2010 asks us to count the number of intersections (black circles) in a planar straight-line graph like this: That is, with each line segment having one endpoint with \$x=x_0\$ and the other with \$x=x_1\$. Input The first line of the input gives the number of test cas...
stackexchange/codereview
Normally I code in Java but have recently been trying to teach myself C for a university course I will be taking next semester. (I'm about to enter my third year). I wouldn't consider myself the best programmer, or even a good one. Now, I was just wondering if anyone would be able to take a quick look through my attem...
stackexchange/codereview
This is a fairly straight forward question. I have a C# WPF MVVM application that call a C++ DLL to do some compilation/crunching. To update the UI C# application for progress updates I am using callback delegates. public static class Callbacks { public static ConsoleCallback ConsoleOutputCallback { get; set; } ...
stackexchange/codereview
I am trying to optimise my remove-erase functions by using some attributes of C++ containers. This function should delete all indices defined in std::set form given vector. I am pretty sure that algorithm is functionality-wise working, but every time I see STL implementation or any code using STL I see a lot of checks ...
stackexchange/codereview
I'm new to Rust and I would like to implement a function to compare 2 collections of strings. The function should compare them as if they are unordered. In Python, I would implement something like this: from collections.abc import Iterator def unordered_eq(a: Iterator[str], b: Iterator[str]): a = sorted(a) b =...
stackexchange/codereview
Article: https://arxiv.org/pdf/2009.07047v1.pdf Full Code: https://colab.research.google.com/drive/1KZZuIa7Lk13ImZLJ3b-kxMfcveOPaWvN#scrollTo=XhdMfBFtzaEH Dataset: https://drive.google.com/file/d/1IliW9Z7s6B9VBadQ7BahFLnXLt_mmGzg/view?usp=sharing First Block import os import sys import torch import torch.nn as nn impor...
stackexchange/codereview
I had this idea to exploit anonymous lambdas that are immediately executed that wrap around an allocation function to track those allocations in a statically created Stats object. This is the code I came up with after some time #define TW_INLINE __attribute__((always_inline)) #include <iostream> #include <cstdin...
stackexchange/codereview
Here is the stack abstraction that I've written. I've designed it to be safe and without undefined behavior. I use ugly_cast to discourage casting and to make casts more easily visible. stack.h: #ifndef STACK_H #define STACK_H 1 #include <stddef.h> #define stack_op(var, op) stack_##op(&(var), sizeof(var), stack_globa...
stackexchange/codereview
The class I'm using is called Review and looks like this: public class Review { public virtual Guid Id { get; set; } public virtual int Rating { get; set; } public virtual Guid RestaurantId { get; set; } public virtual Guid UserId { get; set; } } I'm using a LINQ statement to first check a few thing...
stackexchange/codereview
I've tried to create a small OpenGL abstraction layer. I've tried to favor composition over inheritance but somehow it added extra complexity to my code. I probably overused it. shader.h #ifndef SHADER_H #define SHADER_H #include "filereader.h" #include <string> #include <iostream> #include <GL/glew.h> #include <memory...
stackexchange/codereview
While executing a SQL script in production like sensitive database, usually I do the following BEGIN TRANSACTION --Declare of test variables DECLARE @ExpectedAffectedRows INT = 10 -- Manually count this DECLARE @ActualAffectedRows INT = 0 -- Its a demo code, don't take it seriously ;P DELETE * FROM SomeTable AS st ...
stackexchange/codereview
I need to calculate pi to 7 significant figures in Java—without using Math.PI. Here is the code I came up with to do that: public class ComputePI { public static void main(String[] args) { double sum = 0.0; double sumOne = 0.0; double delta; int counter = 0; f...
stackexchange/codereview
So I've read numerous tutorials on handling game states in XNA, and to each tutorial I've been read, it was different from the others. Now I want to ask which way is more efficient? I've created my own ScreenManager and what not, but it wasn't satisfying to me because it was inefficient since I didn't unload any unused...
stackexchange/codereview
I have the following class to help me deal with files: File class: # -*- coding: utf-8 -*- """ file ~~~~~~~~~~~~~~~~ """ from mimetypes import MimeTypes from os import path from lazyproperty import lazyproperty class File(object): """Class to help dealing with files. """ def __init__(self,...
stackexchange/codereview
Inspired by another question, I decided to implement Kahan summation in C++ (though that question implemented a different summation algorithm). Since I was writing C++, I decided to make the code generic. Although it's a little difficult to imagine anybody bothering to use Kahan summation on single-precision floating p...
stackexchange/codereview
I have a slider with 3 images and left/right arrows. If you click on them, the image changes. You also have 3 bullets below the images and the image changes depending on what bullet you click. I don't want to use buttons "arrows"; I want to use the tag "a." Any ideas on making it better? You'll need to add 3 images "be...
stackexchange/codereview
The AsyncTask available in android, gives you the result from doInBackground on the UI thread so that you can update UI according to the result, but exceptions need to be handled inside doInBackground function. So following is my generic solution to the problem, the main objective here is to allow user to handle except...
stackexchange/codereview
I have a function written in Python 2.7 that I call several times in a program. This function is rather slow, and I'd like to rewrite it in NumPy. However, I don't know how to do it. I basically have a canvas of width * height pixels, and I'm making something rather complicated inside. I'd like to know how to replace a...
stackexchange/codereview
C++11 provides a std::tuple template, but it requires the types of all the fields to be listed individually, which is inconvenient if there are many fields and they're all the same type. If I want a tuple of, say, 10 integers, instead of writing std::tuple<int, int, int, int, int, int, int, int, int, int>, I'd like to...
stackexchange/codereview
I've been researching about JavaScript and jQuery function chaining and different callback techniques. I am trying to create a very generic code that allows chaining, and in a way that I may create several parallel chains without them interfering in one another. Expected Usage Setting up /*---Usage---*/ var chain = ne...
stackexchange/codereview
I just started learning Python and I wrote my first useful script for work. I did a bunch of the basic tutorials and really enjoyed learning Python so far. I am looking for any advice on how to make things more pythonic. What areas can I improve going forward? I want to make this script better/move on to my new project...
stackexchange/codereview
I am displaying a loading spinner inside of various elements. There are four potential states an element could be in: Reduced opacity; unresponsive to pointer events. Reduced opacity; responsive to pointer events. Maintain opacity; unresponsive to pointer events. Maintain opacity; responsive to pointer events. I'm tr...
stackexchange/codereview
For an (completely optional) assignment for an introductory course to programming with C++, I am trying to implement a diagonal matrix-vector multiplication (?diamv) kernel, i.e. mathematically $$\mathbf{y} \leftarrow \alpha\mathbf{y} + \beta \mathbf{M}\mathbf{x}$$ for a diagonally clustered matrix \$\mathbf{M}\$, dens...
stackexchange/codereview
On several occasions I had to use a fixed set of keys (constants in the sense of static final String) with some additional logic (grouping in different keySets). After some more or less lefthanded approaches with static final String constants, I learned the advantages of enum. Since everything is known from the start I...
stackexchange/codereview
I found this question in an old exam in computer science. I solved it in a good way, but I'm not convinced that my solution is the best solution. I believe that there's a better way to solve it. Given N Columns that are lined up, The horizontal distance between two adjacent columns (The lower edges) is exactly 1 met...
stackexchange/codereview
Sometimes I like to use word count to describe someone's contributions to Stack Exchange, so I wrote a query to state the word count for a given Stack Exchange user using SEDE. click to run it online DECLARE @total_count int, @post_id int, @post_body nvarchar(max); SET @total_count = 0; DECLARE vendor_cursor CURSOR...
stackexchange/codereview
I have the following algorithm which retrieves information in a List of KeyValuePair (prices) and write them in a DataRow. I was wondering if I could achieve the same result without j. if (prices != null) { for (int i = 8, j=0; j < prices.Count; i+=2, j++) { res[i] = prices[j].Value; res[...
stackexchange/codereview
Recently I completed my first assignment at the university. The assignment is : Write a CPU scheduling simulator that uses the Shortest Job First and Priority scheduling methods. Both of these should also have a "preemptive" and "non-preemptive" option. Each process information will be read through a text file and to...
stackexchange/codereview
How is this? Any ways to improve? public void DownloadPDF(Uri uri) { downloadProgress.setVisibility(View.VISIBLE); downloadComplete.setVisibility(View.INVISIBLE); openFile.setText("Wait..."); // My button openFile.setEnabled(false); if (uri != null) { DownloadManager.Request request = new Do...
stackexchange/codereview
I implemented an algorithm for solving sudoku using reduction from sudoku to SAT. Now, I am trying to refactor the code using code review principles. I find some difficulties apply the principles. Because of that I would like to share the following code snippet in order to get some hints how to approach this proble...
stackexchange/codereview
I am creating a simple 2D canvas game engine in JavaScript. Are there any optimizations that I could make, or obvious issues (performance, semantics or otherwise) that you can see? JS Bin here var GameCanvas = { // GameCanvas Variables animation: { requestAnimationFrame: null, halt: false },...
stackexchange/codereview
Recently, I've solved the "01 Matrix" LeetCode problem and the solution was accepted by the LeetCode OJ: Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. Example: Input: 0 0 0 0 1 0 1 1 1 Output: 0 0 0 0 1 0 1 2 1 Note: The number...
stackexchange/codereview
I was reviewing the following code block and noticed there was validation check at the top. The 3rd line in the function checks if the invoice belongs to the logged in customer. I am wondering what the correct way of doing this might be. Some options that come to me head are: GetInvoice should take an overload and...
stackexchange/codereview
I was tasked with implementing Conway's Game of Life. It seems to work fine but the implementation is lacking as I find that it takes a long time to generate the next generation of the grid. I'm looking for flaws and tips to speed up the process. Currently, I can only refresh the display twice a second. The grid class ...
stackexchange/codereview
I have following input range (slider), values allowed are from 0 to 100. I need to map values from the slider to a input text, with the following rules: range => text 0 => 2000 100 => 200 With the value in between accordingly. Currently I am using the following script, which works, but I would...
stackexchange/codereview
I wrote a function, read_fox_rcu() for getting an element from RCU-protected list in a linux device driver. read_fox_rcu() reads the first element, converts it to string , stores it to tmp and stores the first pointer to ppfox. I wonder that I used locks (rcu_read_lock(), synchronize_rcu(), etc), in an appropriate way....
stackexchange/codereview
This code seems surprisingly fast at checking if a number is prime. def is_prime(number: int) -> bool: """Checks if a number is prime or not""" # number must be integer if type(number) != int: raise TypeError("Non-integers cannot be tested for primality.") # negatives aren't prime, 0 and 1 aren'...
stackexchange/codereview
I couldn't help but notice we didn't have a FizzBuzz in lua yet. I've always wanted to take a shot at Lua, so here goes nothing. Code: function fizzBuzz(maxNum) local fizz = "Lua" local buzz = "Yay" for i = 1, maxNum do if i % 15 == 0 then print(fizz..buzz) elseif i % 3 == 0 then print(fizz) ...
stackexchange/codereview
I have written code to add a node to the head of the list. Criticisms and feedback are welcome. typedef struct sList { void *data; struct sList *nextNode; }sList; sList *addNode2Head(sList *psList,void *data) { if(psList == NULL) psList = newNode(); else { psList = addHeadNode(psLis...
stackexchange/codereview
script.py: #!/usr/bin/python import os srcDir = os.getcwd() dirName = 'target_directory' dstDir = os.path.abspath(dirName) def ignore_list(path, files): filesToIgnore = [] for fileName in files: fullFileName = os.path.join(os.path.normpath(path), fileName) if (not os.path.isdir(fullFile...
stackexchange/codereview
There are two main classes: Game and MCTSPlayer. The first one is just an abstract class with a couple of methods and some hints on how to implement actual games. The second implements the simplest form of MCTS algorithm (it does not use any expert knowledge), storing a graph of all known games as a dict[Game, NodeInfo...
stackexchange/codereview