instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have a stream of sensor data which I want to visualize in a plot with many subplots. Plotting the data is a real bottleneck in my code. Right now I get with small resolution only 16 FPS which is far too slow. Here is what it looks like: import time from matplotlib import pyplot as plt import numpy as np def live_pl...
stackexchange/codereview
I wrote a code that retrieves categories from DB and act as dynamic category search. I kindly ask you to review my code and tell me if the code can be optimized/improved. Thank you for your help. This is the html code. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> ...
stackexchange/codereview
I'm trying to update my website's code to HTML5's semantic and structural elements, but I'm not very sure with the sections and article element. Here's the structure of my page: <body> <header id="heaven" style="background-image: url(" ./images/header/2.png ");"></header> <nav id="outer-nav" style="position: ab...
stackexchange/codereview
I was in the mood for some C++ and decided to write a command line calculator, which understands addition, subtraction, multiplication and parentheses. See what I have: main.cpp #include <algorithm> #include <cctype> #include <iostream> #include <iterator> #include <sstream> #include <stack> #include <stdexcept> #inclu...
stackexchange/codereview
I have implemented below code for binary search tree implementation using shared pointer. At present, I have considered only integers. It supports insertion and deletion of values. Also, a print method is implemented for inorder traversal. Please review and provide your suggestions. class Bst { struct node { ...
stackexchange/codereview
I am writing a program that will deal with formatting the text in a text area. The user will use Ctrl + A, Ctrl + C to copy the entirety of a web page, then paste that text into a text area. The program will take the text area, remove the junk, and output the important information to then be copied and pasted into a d...
stackexchange/codereview
I've started to fill my GitHub profile with small applications to educate and showcase my skills. However, I feel like I'm missing something essential, while creating these projects. Could you take a look at this component, and advice me on how to refactor it? Its purpose is to get Coin Data from an API, and display t...
stackexchange/codereview
I'm trying to make a code review for an external developer on my project. His code could be improved and I need your advices in order to know if my overwritten parts are better or not. Part 1 # INITIAL if 'error_message' in result_import: result_import['error_message'] = "The file could not be uploaded. \n" + resu...
stackexchange/codereview
I have write a normal programm "Transpose the matrix" in go. Suppose input are always correct. I also read the article An Efficient Matrix Transpose in CUDA C/C++. So I keen to know how I can use Go-routines or another efficient way to problem in go way package main import ( "fmt" ) func main() { a := [][...
stackexchange/codereview
I was recently tasked with architecting a user/profile object in Objective-C and wanted the ability to access a static instance from the class level, similar in style to the way Parse manages their current user (a static variable on a class, not a singleton). With Parse, I can call a class method to return the current...
stackexchange/codereview
I made a function to get a list with numbers around another number. Example: I want to get in a range of 2 numbers around 4. This will return: [2, 6]. You can set a min number and a max_number. That means when I set a min_num, the lower number should not be lower than the min number. import sys def get_numbers_around...
stackexchange/codereview
public class FirstActivity extends Activity { private String userName; private Uri userPhoto; private void onOkButtonPressed() { Intent intent = new Intent(this, SecondActivity.class); intent.putExtra(SecondActivity.Key.USER_NAME, userName); intent.putExtra(SecondActivity.Key.USER_...
stackexchange/codereview
I'm a beginner in Android and I've been experiencing "Skipped xx frames" everytime I load up my activity which is a list of languages. I tried optimizing the listview following tutorials (applied recycling and viewHolder pattern) but still can't get rid of the issue. ListLanguagesActivity.java package com.experiment.wo...
stackexchange/codereview
This code will copy data from a workbook and copy it to an existing (and open) workbook. At the beginning of the month this copy/paste works very quickly, but as the month goes on and the data also grows, this process slows down to a couple of minutes. Once we start hitting 200 rows of data, we see the performance slow...
stackexchange/codereview
I recently completed the Pascal's Triangle challenge on leetcode. I would like to have my code reviewed. You don't need a leetcode account to see the description of the challenge linked above, but for completeness I'm pasting the description here. Given an integer numRows, return the first numRows of Pascal's triangle...
stackexchange/codereview
In my real life example I am at a layout stage and before I actually move any further I would like to review my current approach. I am still learning about UI, XAML on WPF technology and I guess I haven't gotten my head around all the possible approaches yet. I have built this very simple SSCCE to better demonstrate wh...
stackexchange/codereview
Here's what I ended up with for Learning Python the Hard Way Ex 51 with image upload (save and display). The form: <div style="margin:300px;border:1px solid #000"> <form method="POST" enctype="multipart/form-data" action="upload"> A Greeting: <input type="text" name="greet"> <br/> Your Name: <input type="text" name="na...
stackexchange/codereview
There isn't a very reliable way (in my opinion) to get the mime type of a specific extension, regardless of the file actually being of that type or not. This type of thing usually is used when sending a different Content-type when you intend to send, for example, an image. class MIMETypes { /** * @var string ...
stackexchange/codereview
I have function that takes all of the attributes passed to a custom tag, and returns a select subset. I am try to convert the current function, which does not use closures string function passThrough(required struct attr) output="false" { local.result = ""; for(local.myKey in arguments.attr) { if (var...
stackexchange/codereview
What follows is a piece of code that essentially toggles an array of filters (if the filter doesnt exist it adds it, if it does, it removes it). What would you suggest is the best way to write the following imperative approach declaratively? var selectedFilters = [ {name:"SomeName"} , ... ] var inputFilter = {name:"Oth...
stackexchange/codereview
I completed a short coding challenge and just want to know if I should use shorter methods of which I am unaware, or make it more readable. /* * * Complete the vowelsAndConsonants function. * Print your output using 'console.log()'. */ function vowelsAndConsonants(s) { var strConsonants = ""; var strVowels = ""; v...
stackexchange/codereview
As I am new to bash scripting, and want to use apt-get in my university. I know that many people have issues when trying to do so. My focus is simplicity and ease of use, but still need to be somewhat robust. #!/bin/bash string="install" errormsg="\n\tInvalid input\n You should run this script with the following st...
stackexchange/codereview
I'm currently working on an uncrafting tool for minecraft and got a neat output working that shows all the materials needed in a tree. I wonder if the code used to print that tree could be improved somehow. I only have the recursion depth as a measurement and the ArrayList gets filled in the same order as seen in the i...
stackexchange/codereview
I'm building a text search system for a web application in PHP. I wrote this function that gets the sentences of the text which contains the keywords used by the user and also highlight them (well, surround them with any tags anyway). I'm measuring an average of 23ms if only the first matches is retrieved, and about 27...
stackexchange/codereview
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course. HW1 - Validating Credit Card Numbers - Full description A shortened problem statement: Validate a credit card number by th...
stackexchange/codereview
Some of my functions use a "fail_silently" flag. It is used in the following way: def test(a, b, c=1, fail_silently = False) try: return int(a) + c except: if fail_silently: return None raise Therefore, if there is an error, we catch it and fail gracefully. The key here is tha...
stackexchange/codereview
I'm looking to highlight some words on a webpage, I've grouped them now, but changed the css and html slightly and this seems to have broken it. For context, looking to add a list of words in JS which would then apply formatting to those words. I changed the p to a span because I wanted them to be an inline-block, whic...
stackexchange/codereview
I am requesting a review for my solution to this problem from exercism.io. I'm posting it here since there is not always input on solution submitted through exercism. The problem is as stated: Calculate the Hamming difference between two DNA strands. A mutation is simply a mistake that occurs during the creation or ...
stackexchange/codereview
I recently came across this SO question asking for methods to determine if a std::string represents an integer. There is also this SO question for floats. I decided to code up a few methods consolidating these questions. #include <string> #include <algorithm> #include <iterator> #include <cctype> namespace detail { ...
stackexchange/codereview
I created a quick program to test the precision of randomness generated by the .rand method. The primary question is whether I can use the .times method in place of the while code blocks to increase efficiency and: Whether such a practice would reduce the amount of processing required/if this would be at all signific...
stackexchange/codereview
I wrote a generic implementation of A* with the focus of not having to clone nodes or actions. Thanks to some very good advice I received on Stack Overflow, I have arrived at the following final result: lib.rs extern crate typed_arena; use std::cmp::Ordering; use std::collections::{BinaryHeap, HashMap}; use std::hash:...
stackexchange/codereview
Floating point inaccuracies are really annoying. I understood that in its true sense while developing the next version of Point (this time I'm actually foolproofing my code). Before I upload it for review, I want a class that I wrote, called Numbers to be reviewed. Numbers.java package library.util; /** * This class ...
stackexchange/codereview
I am a freshman Computer Engineering student. Variable names are pretty straightforward; I believe it would be easy to understand. Program explanation: First you have to create an account and deposit money into it. Create method that runs and writes your id and password in separate text files and calls deposit_first w...
stackexchange/codereview
I've recently taken an interest in Android applications and I have been working on an app regarding the travelling salesman problem. My app is a kind of a trip optimizer which is meant for travelers, so that they can optionally choose a starting point and a destination/multiple destinations. Right now the app works fin...
stackexchange/codereview
I decided to implement some data structures- this time an AVL tree. I think the logic is correct. Is there a way to make it clearer and do you have any ideas about more tests to add? # An AVL tree, python import random class TreeNode: def __init__(self, key, val, left=None, right=None, parent=None, bal=0): ...
stackexchange/codereview
This program is supposed to calculate the mathemathical maximum of helpful flags you can have on the nth day, starting with 0 helpful flags, using the StackExchange system of gaining more possible flags, meaning every 10 helpful flags you gain one possible one, immediately. #include <stdio.h> // <summary> // Small C p...
stackexchange/codereview
I need to cut the time it takes to print a large string by ~50%. I went from using s1 + s2 to using StringBuilder, and instead of making several calls to System.out.print for each line, I create one large string by appending newlines to the StringBuilder, and then print that large string just once with System.out. Bu...
stackexchange/codereview
Somebody please verify this code. Is this efficient? please tell me modular way to accomplish this task. Updated I want to add show class to data-targetand remove show class from data-group Just like happening in an accordion. I wanted to know that this code is perfect for that scenario. I'm new here please let know...
stackexchange/codereview
I made this function to act sort of like jQuery's $.ajax. I intend to use it in small projects where I do not use jQuery (I don't want to load a whole framework just to facilitate http requests). Edit: New script incorporating Bob Lauer's suggestions "use strict"; function OM(obj){ return new ObjectManipulator(obj...
stackexchange/codereview
I am trying to encrypt/decrypt file using source code directly. The issue is how to properly do it after reading the file. int crypto_aead_encrypt( unsigned char *c, unsigned long long *clen, const unsigned char *m, unsigned long long mlen, const unsigned char *ad, unsigned long long adlen, const unsig...
stackexchange/codereview
This time I made a quiz game, in which the player is asked questions and receives points for each question answered correctly. Some people told me I should learn about classes, so this is what I came up with. import random from Quiz_Questions import game_questions questions = [*game_questions] def game(): print('-...
stackexchange/codereview
Algorithm: Determine if an array of arrays of characters can be concatenated in order, into a substring of haystack. Example: [['a','A','@'], ['b','B','8'], ['c','(','[']] This list can be combined by selecting from each of the subarrays in order, such as: abc, ab(, ab[, Abc, Ab( etc. Are any of these combination...
stackexchange/codereview
I had always had the necessity to display long text outputs on the console screen. The size of the text displayed usually exceeds the amount of text that can be accessed by scrolling up through he console output. Also, there had been times when I wanted to look at the output history, to spot out abnormalities or bugs. ...
stackexchange/codereview
This is my first Python project in file management. It's a finished and passed exercise from JetBrains (Duplicate File Handler). The main job is reading a full path to folder from argument, list files of the folder, grouping them based on same size and md5 hash (md5 required for passing the test) and then asking for de...
stackexchange/codereview
Credits for the original implementation I based my code on: Quora - What is the most efficient way to sort a million 32-bit integers? Implementation // RadixSort - works for values up to unsigned_int_max (32-bit) template<typename Iter> void radix_sort(Iter __first, Iter __last){ typedef typename iterator_traits<I...
stackexchange/codereview
vstrsepf is string parsing utility function born from the idea of using strsep and strtol with a sscanf-like interface. This is an attempt to build a safer scanf for embedded system application. Some key design choices: Will destroy its input string (by adding '\0'). No dynamic memory allocation. Reentry safe (RTOS a...
stackexchange/codereview
I'm using Cache::remember to cache 3 results in my action, 2 in the same call to Cache::remember. It works, but I have 2 questions about how I can join this Cache::remember call: Could I use two Cache::remembers in the same method? Could I join these two Cache::remembers (I need change the first param)? Is it possible...
stackexchange/codereview
The n-queens puzzle is the problem of placing n queens on an n✕n chessboard such that no two queens attack each other. Given an integer n, this code returns the number of distinct solutions to the n-queens puzzle. How can I further optimize (in time and space) the solution below to leetcode's N-Queens 2 problem? This s...
stackexchange/codereview
I just wrote a basic DTMC algorithm focused on generating names, though it could be used to generate lots of other things. It's designed to be run from the command line, so input is taken from a file, with a couple of options specified on the command line. I'm specifically looking for these things, though any other ad...
stackexchange/codereview
Can someone have a look at my script and maybe find something which can be optimized, as there shall be later 100 of it running. First of all this script shall be triggered once per day to receive data from a website into a sheet called "getdata". Some fields of "getdata" are transferred to "blindcopy" in a certain ord...
stackexchange/codereview
I have a working macro that finds a specific word and deletes the whole text. It finds the word "JOBSPECIALTYCODE" in the sheet, selects and deletes it, then moves to the next sheet. I just want to ask if there is any alternative way to make my macro work fast. I only use a record macro. Sub aHaveProgess() ' ' ' ' 'D...
stackexchange/codereview
I am learning about object oriented programming in Python using classes. I have attached an image of what I had in mind when structuring my classes. This is supposed script model cars. I want to know if the way that I set up my code it the ideal way of modeling cars. A few things: There are no syntax errors. I can cre...
stackexchange/codereview
Most of the VBA I write is to produce tabulated reports from spreadsheet data. So, here is my attempt at creating a CLS_Data_Report class. Properties: a 2-dimensional Data Array 3 dictionaries to, respectively: Map headers to column indexes Map external (user-set) descriptions to data headers Store number formattin...
stackexchange/codereview
I have the following code to calculates and retrieves pair combinations: public static void calculateCombinations(int x){ int number = combination(x); int counter=0,y=0; while(counter<number){ y++; for(int i=1; i<=x; i++){ if(y!=i && !(i<y)){ ...
stackexchange/codereview
I was inspired to write a BBCode to HTML converter as I'm currently learning functional programming. I wanted achieve functional cohesion. jsFiddle I'd like feedback on: structuring of the code. Should the functions getHtmlTag and getHtml be contained within bbTagToHtmlTag since they are coupled through the rules vari...
stackexchange/codereview
I am writing code to filter data on basis of attribute values. It is possible that the user can select multiple values. How can this be better? Models.Products filter(ViewModel.Filter search,IEnumerable<Models.Products> product) { if (search.filter!= null && search.filter.Count>0) { var f = sea...
stackexchange/codereview
I have one PHP file named database.php: try { $connection= new PDO(DB_DNS, DB_USER, DB_PASS); $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(Exception $e) { echo "Error: ".$e->getMessage(); die(); } and I have a user.php with class Users: require_once(__DIR__."/../in...
stackexchange/codereview
I have been working on where I want to improve my knowledge to do a safe JSON scraping. By that is that I could pretty much do a ugly workaround and wrap it into a try-except but that is not the case. I would like to know where it goes wrong and how I can improve the code I have been working with: import json from json...
stackexchange/codereview
Imagine that I need a color palette for my Winforms application to have a consistent look. What I did was create a static helper class and helper methods that I can call from anywhere in my code, and invoke what I need from the App.settings file. Here for example, I am getting the school name from the App.config file, ...
stackexchange/codereview
I wrote an helper class which allow me to request the body content from a site that is created by AJAX, for doing so I'm using Puppeteer Sharp. This is the class: using System; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; using PuppeteerSharp; namespace App.Helpers { public c...
stackexchange/codereview
You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year oc...
stackexchange/codereview
I wrote an adaptive color thresholding function in Python (because OpenCV's cv2.adaptiveThreshold didn't fit my needs) and it is way too slow. I've made it as efficient as I can, but it still takes almost 500 ms on a 1280x720 image. I would greatly appreciate any suggestions that will make this function more efficient!...
stackexchange/codereview
Was fiddling with java-8; trying to write a program for getting all Armstrong Numbers between 1 and 10_000_000. Following is my working solution: public class ArmstrongNumbers { public static void main(String[] args) { IntStream.range(1, 10_000_000) .filter((n) -> { int ...
stackexchange/codereview
I started with a pure python implementation, and have been trying to get the performance as close to native C as possible using numpy, numexpr, and cython. Here is the the numpy version that I compile with cython: import numpy as np cimport cython cimport numpy as np from cython.parallel cimport prange, parallel from ...
stackexchange/codereview
Yet another exercise in converting values between the decimal and roman number systems. I have tried the functional way. Any comments are welcome - but I'm especially interested in answers focusing on the F# specific functional approach and less in if I obey each and every rule for roman numbers. A type definition: mod...
stackexchange/codereview
my Java needed a little refresher so I implemented the Game of Life as a little excercise. The game is working as expected, but I'm sure there is some room for improvement. Here is the code (skipping the interfaces, packages and imports) /** * Controller Implementation responsible for starting the game and keeping it ...
stackexchange/codereview
Just came home from a vacation, and I have a bunch of GoPro videos that I want to compile into a fun music video. In order to support this process, I wanted to write a script that would take all my videos and create a 'summary' thumbnail collage for each video. The idea is that it'll allow me to skim through my videos ...
stackexchange/codereview
Since I didn't find a way to properly transform JavaScript object to JSON with PHP, I wrote a snippet. Lets assume the following excerpt from Google Fonts JavaScript API: WebFontConfig = { google: { families: [ 'Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic,700italic:latin,latin-ext' ] } }; This, ...
stackexchange/codereview
This represents a UI-slider widget - there are a number of different widgets on the page. This function is repeated per widget - 90% of the code is the same - the only difference being that each has a unique getDesc() function which is called by the slider events. My gut feeling is that these widgets can be refactored ...
stackexchange/codereview
I am new to encryption and recently wanted to learn more about it. I researched how to do AES Encryption in java and assembled my own Java AES encryption class. I don't know if there are any major security holes, though. Can someone experienced in Java encryption look at my code and tell me if there are any serious sec...
stackexchange/codereview
When you click open - a div slides out. If you click on the new div, an additional div slides out from under it. This is working great, but I need two things that I cant figure out! How can I condense the jQuery so I don't have to add a class to it every time I want a new slider? Is it possible to do a .sibling kind o...
stackexchange/codereview
I have been reading Clean Code and decided to start working problems on Codechef.com attempting to apply some of what I have learned. Do I seem to be on the right track or am I way off? The challenge is to find the number of trailing zeroes in the decimal form of N!, where 1 ≤ N ≤ 109. I am more concerned with the codi...
stackexchange/codereview
I have a search on a very simple spring-powered website and I want to display 10 recent inputs: import java.util.Collection; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Exec...
stackexchange/codereview
I'm (re)building a data table to track our clients that receive regular income payments. Specifically, I need to pull this data into other workbooks for other reports, and since I was here anyway I decided to upgrade it and anticipate its' future growth. A sample of the data table (minus sensitive data): My code finds...
stackexchange/codereview
Say I'm creating a simple CLI. I want to use native node readline module to take in some input from user at prompt. I thought of this: var prompt = chalk.bold.magenta; var info = {}; rl.question(prompt('Thing One : '), function(args) { info.one = args; rl.question(prompt('Thing Two : '), function(args) { ...
stackexchange/codereview
I am using the Python module urllib3. It occurs to me that there is a better way to design a good class when I rebuild my last site crawler. class Global: host = 'http://xxx.org/' proxy=True proxyHost='http://127.0.0.1:8087/' opts=AttrDict( method='GET', headers={'Host':'xxxx.org', ...
stackexchange/codereview
I think I made a good FileIO object because I can simply copy-paste whenever I need, however I wonder How I can improve my code. This code takes file path of the target file and turns every line to Strings. And combine all of the Strings into String array so that we can use the data of the file. import java.io.Buffered...
stackexchange/codereview
I have the following MySQL query which selects product details and whether the viewing user likes them. I feel like it could be more efficient and that there is a more practical approach than using a sub-query here. Any suggestions? SELECT p.*, pm.filename AS thumbnail, (SELECT COUNT(id) FROM likes W...
stackexchange/codereview
I'm trying to create a generic notification service that works with Mail (smtp ) Sms (Third part vendor) Push events (For future) Purpose : Create a notification service and it should be pluggable A Common interface for all notification service public interface INotificationService { bool Notify(); } Mail Ser...
stackexchange/codereview
This is a work in progress Rubik's Cube scramble generator with timer and list of solves. The list of solves is stored using localstorage so that it stays on page reload. A solve can also be deleted from the list. I used some basic boostrap for alignment and buttons. I also used jQuery to make the list of solves. I am ...
stackexchange/codereview
I have a method visible on a QuerySet class which should return all articles an user can see. If the user is not logged in, all articles with min_age should'nt be visible, otherwise, if the user is logged in, all articles which min_age is lower than the user's age should be visible. I wrote this code but I think it can...
stackexchange/codereview
I have written a (recursive) deep clone method for ES/JS-objects. It seems to work fine, but maybe I'm missing things. Please, feel free to comment! Note: the method will not clone cyclic structures. If it should be somehow necessary to be able to clone such structures, maybe Crockfords cycle.js can be used - but it wi...
stackexchange/codereview
This opens a file and writes 5120 times a string to it, and if the file doesn't exist it creates a new file. The name of the file and the string are chosen randomly. I would like to know if there is a way to speed up this code. It takes about 10 seconds at the moment. I was wondering if I did a recursion in the escreve...
stackexchange/codereview
I recently applied for a job where the company gave me the following prompt for a code challenge. They have since told me "yeah, no thanks" but provided me with no feedback about why they came to that decision. Would you be so kind as to review my code? You can even be harsh. I'd just like to know what this program is ...
stackexchange/codereview
Been studying data structures in C to get more grasp on the fundamentals as a freshman at uni. This is a coding-challenge that I've given to myself to understand Linked Lists better. Basically, my aim was to create 2 nodes, along with the node.header that i've written, which has the functions to add nodes to the head, ...
stackexchange/codereview
When starting an ipython repl for my project at work, I pretty much always want it started in the project root, not adjacent to the file for the buffer I'm viewing (this is python and module loading depends on cwd). While I can always start the repl and then %cd /my/project/root that is a pain the 50th time I had to do...
stackexchange/codereview
I am working on something that involves the observer pattern. A simple version of that looks like this: private var listeners = Set.empty[A => Unit] def addListener(listener: A => Unit):() => Unit = { listeners += listener () => listeners -= listener } In my code I have something that deals a bit more abstract wi...
stackexchange/codereview
(I've improved the code from my last question) My program.... Downloads a file (web tracker) Update if version is lower Connects to a server using the tracker information If one of these operations were to fail, the program stalls for a minute and goes back to step one. A few wrong things I can notice for myself: re...
stackexchange/codereview
I have a 9-dimensional signal (as a csv from this Gist) that looks like this: A signal peaks every 30 steps. I want to get the maximum values of the peaks in that 30 second window. Here's what I've hacked together so far, where sig is the signal loaded from the csv file and max_res is the desired result: trial_num = 8...
stackexchange/codereview
This is part of this topic. Problem: I need to read a file with BigIntegers and make some analysis "on-the-fly" with each read number (get prime numbers count, get armstrong numbers count). Right now I have this code, but it works very slow: package ee.raintree.test.numbers; import java.io.File; import java.io.FileInp...
stackexchange/codereview
I have a requirement that is summarized below. void update() { | | | | | | | | | | | | \| \| \| \| ============= meat <--- Only one thread must execute here, the rest should skip it. ============= | | | | <--- Other threads wait here until the "first" thread is d...
stackexchange/codereview
I have the following poller class that can be used to "poll the required action": public class Poller { private readonly string name; private readonly Action action; private readonly int pollingInterval; private readonly Thread pollingThread; private readonly AutoResetEvent stopEvent; private r...
stackexchange/codereview
The usual way is to implement socket server to handle concurrent requests by creating new thread for each request. Instead of this approach i tried to create a server using consumer-producer design, as follows. Main thread //holds socket instances ConcurrentLinkedQueue<Socket> queue = new ConcurrentLinkedQueue<>(); //...
stackexchange/codereview
I'm trying to model a tournament with Python (Django) and I've got a function that assigns teams of the previous stage to the groups of the new one. The teams in the first stage are assigned manually. Every Stage have OneToOneRel to the previous Stage. Team model is related to the Group through Score model, that has F...
stackexchange/codereview
I have many object of class Test. I want to be sure that among them, there are no two objects o1 and o2 where o1==o2. In order to achieve that, I want to add them all to a HashSet and check if hashSet.size() == numberOfInitialObjects . In order to ensure that the potential future changes in equals method of the Test ...
stackexchange/codereview
Recently I was looking for some really simple modal/popup solution in vanilla JS, but nothing popped. So I wrote mine component. It works great so far, have all the options I need, but I don't know if I can improve the code itself. JS: /* A very simple modal component You can close the modal either with `esc` key, hitt...
stackexchange/codereview
This code write to determine a way to place the N horses into the K stables, so that the total coefficient of unhappiness is minimized. I use python to write a code and I want to reduce the running time and memory used. Or maybe shorten the code. What should I do? My memory used is about 67,000- 80,000 KB. My running t...
stackexchange/codereview
This wrapper incorporates the logging feature and provides a few convenience methods, including a scalar values fetcher, a generator for paged row sets, a wrapper retrieving a row set via a JSON container, and a set of transaction management methods. For now this is mostly an exercise for me for learning the Python sql...
stackexchange/codereview
I use the following code in Javascript to get the difference between two Date objects. I want the result to return the difference in: seconds if the result is less than 60 secs minutes if the result is less than 60 mins hours if the result is less than 24 hours days otherwise The code is very long and I see lots of c...
stackexchange/codereview
I'm wondering if my approach to creating a filtered array (filteredLaunches) from an array of data (launches) is an anti-pattern, or not? Is there a better way to go about it? Here is the code: const initialState = { launches: [], filteredLaunches: [] }; export default function(state = initialState, action) { ...
stackexchange/codereview