instruction
stringlengths
71
95.1k
While learning Go I decided to implement a simple REST API to get to know the language and since I am inexperienced in Go I would appreciate any feedback on the code. Please post any thoughts you have. They don't have to be constructive, but if you have some constructive feedback that will be great. Q: In particular, I...
I am in the process of learning basic C++ and one of the practice questions I came across was to write a function to open a file in C++. I did understand how to use the streams but I think I went overboard a little bit by making sure that it works. I would appreciate any feedback on my code. The objective was also to k...
I created this wrapper to use together with HttpClient streams and ZipArchive. ZipArchive reads .zip index once from the end of the archive, so this wrapper caches last 4MiB of the stream. Also the wrapper avoids pointless seeks until the first read. I am interested if there any issues with this approach, and whether t...
This program Detects application uniqueness, if the application is a unique/primary instance, it launches a server, otherwise a client over a Unix domain socket. Client will send a message that will trigger the server to invoke a time-heavy task. When the task is running, the server will ignore all the incoming messag...
I am working on an information retrieval project, where I have to process a ~1.5 GB text data and create a Dictionary (words, document frequency) and posting list (document id, term frequency). According to the professor, it should take around 10-15 minutes. But my code is running for more than 8 hours now! I tried a s...
I am trying to solve the HackerRank: Array Manipulation problem using Java. The problem that I am facing is that the program is running for half of the test cases, while for the other half it is showing "Execution couldn't be completed because of Timeout". It seems like there is a more efficient way to do the problem s...
C# lacks a common off-the-shelf encryption and decryption interface for dependency injection. Nearly every codebase I've ever opened has a couple of extension methods for hashing strings and so on. This is always frustrating because it makes it difficult to change the cryptography in one hit. It seems blindingly obviou...
I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace...
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...
Sometimes I save a file somewhere but can't find it after or I install something and want to see what files were added. For this reason, I created a winforms app which only displayes files created/changed/accessed in a certain timespan. Since the windows timestamps aren't reliable when it comes to folders (see here), I...
I'm writing a bash script for my tablet laptop to flip the screen depending on a file in Manjaro Linux. My current script is the following: while true do state=$(cat /sys/devices/platform/thinkpad_acpi/hotkey_tablet_mode) #This file indicates if it's in tablet mode or not if [[ $state == 0 && $oldState == 1 ]] ...
First question here on CodeReview. I was directed here from a question I asked on SO: Swift protocol with lazy property - Cannot use mutating getter on immutable value: '$0' is immutable. Goal: Create a protocol that allows lazy computation of a property for structs that conform to the protocol. The computation is inte...
I am currently "gracefully" handling HTTP server net/http shutdown which works perfectly fine (I am not asking you to review server shutdown). As seen in the code below the context is created first time directly in server package when I run the application. What I've done afterwards is (this is the one I would like you...
I have implemented the A-Star path finding algorithm for a 2D grid. The function returns a list of positions of an acceptable path. main.cpp : #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <set> #include <unordered_set> #include <boost/circular_buffer.hpp> #inclu...
Summary: This function generates a truth table for a boolean function of variable number of arguments. The name of the function passed and its arguments are deduced outside of the computable function scope. The returned value is a logical matrix with columns corresponding to function arguments and result. library(R.uti...
I just started learning python a couple of weeks back from and like many others here, I too seek feedback on my simplified Blackjack game. I would like to know if the code could have been more elegant/ shorter and how. PS - In my code, aces count only as 1 for the time being. class Bank(): def __init__(self,bet,b...
This script sends and receives text messages and logs responses in a google sheet. Demo Gif here: https://github.com/RyGuy96/HealthTracker. I'm a self-taught beginner coder just starting my formal education in college. I've never had an experienced programmer look over my work; it was suggested to me that I needed to s...
I'd like to receive a CR for the following command-line program options' initializing using boost::program_options. I'd like to know if there is a better way of doing this using boost::program_options or using another available library/code: #include <iostream> #include <boost/program_options.hpp> using namespace std;...
I'm applying what I learned in statistics class to a program to calculate everything automatically, but encountered an unexpected 'mistake' in my code. I say unexpected, because it's not the first time I use malloc() to make a variable sized array and used reference from my previous work, but it goes off limits with th...
I recently interviewed for a software engineering job that requires at least one year of C# and experience with the Microsoft stack. Even though I made it clear at the outset that I had zero experience with C#, they still wanted me to take their engineering test, which led me to believe that they were willing to give m...
I'm currently creating a 2d game in python. I have to calculate the closest enemy so the player knows which one to target. I have the following function to accomplish this task: import math def find_closest(character: tuple, enemies: list) -> (int, int): """ Finds the closest enemy in enemies :param chara...
As a spare-time personal project, I'm implementing a set of symmetric-key cryptographic primitives. One thing I've left vacant for a long time, is the key/state eraser, which I decide to add right now. I intend it to be a macro, so that it doesn't require any additional object file; the macro should be statement-like...
I'm writing some OO Python and I would like to know which of these methods is more pythonic, or which is generally better, or faster. This is an accessor for an attribute which is a dictionary. Method 1: if/else def GetSlot(self, slot_name): if slot_name in self.Slots: return self.Slots[slot_name] else:...
I'm toying with the idea of writing a "bigint" library in 6502 assembler that would handle variable-length integers up to 255 bytes long. Since this would be unit tested using pytest, and to help wrap my mind around the representation issues, I've come up with a function in Python that takes a decmial integer and depos...
I have implemented a BFS. Does this look like a proper implementation of BFS in Python 3? And if you think something needs to be improved, say it. class Node(object): def __init__(self, name): self.name = name self.adjacencyList = [] self.visited = False self.predecessor = None cla...
I have a solution for making the .kml file transparent in the Leaflet Map. The working code looks like this: L.KML = L.FeatureGroup.extend({ initialize: function (kml) { this._kml = kml; this._layers = {}; if (kml) { this.addKML(kml); } }, addKML: function (xml) { var layers = L.KML.parse...
We faced an issue where URLs had a wrong "subfolder" in its URL, so e.g. example.com/match1/randomgenerated should have been example.com/rewritewiththis/randomgenerated We currently use this code for redirecting URLs that (maybe it could be that it only starts at urls that are "bad"): $oldurl = JUri::getInstance(); ...
My Linux kernel version is Linux version 5.0.0-29-generic I'm currently learning how to write kernel modules for Linux and implemented this simple module which creates a new procfs entry and allows some data to be read from it. The module consists of the following files: init.c: #include <linux/module.h> #include <li...
I am currently implementing an app that uses an architecture based on features & usecases and message sending. Features are created with message handler passed in. To test the feature, a handler intercepting the resulting message, must be passed in. I came up with 2 solutions, both currently being present in the proj...
Problem 1 Given a string, the task is to reverse the string and return a reversed string. Problem 2 Given a string, return true if the string is a palindrome or false if it is not. Code Just for practicing, I've implemented reverse string and palindrome problems using JavaScript and Python. If you'd like to review the ...
I am trying to implement a monitor for a certain temporal logic. What this means is the following: There is some external source, from which a trace of items are coming. An item looks like a timestamp along with some propositions which holds at that point. There is a property of traces we care about. This is specified...
Here is my code, it works fine, just wondering if there any anything to make it even better. public static boolean isSorted(int[] arr) { int n = arr.length; int i = 0; while (arr[i] == arr[i + 1]) // same elements at the beginning i++; if (arr[i] < arr[i + 1]) // candidat...
https://leetcode.com/problems/diameter-of-binary-tree/ Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree ...
I'm using a NamedTuple to represent the state of my game while it's running. The user can alter these settings using key presses, so in my PyGame key handler, I'm writing things like: if key_code == 273: # Up arrow return game_settings._replace(fps=game_settings.fps + 5) Each key press transforms the settings sta...
After getting a CR from @pacmaninbw and @ALX23z here, I want to share my new code, and to ask for better ways (which always exist) to improve the code, even with new libraries. The only thing that important to me, is the way of receiving the parameters have to be the command line [I am using Linux OS, so it's highly co...
I recently made this game for rock, paper, scissors in Python 3. Everything works as intended, but I am sure this is not an optimal way of accomplishing this task. Wondering if there is any beginner friendly advice on how to improve upon this. Thank you! def main(): import random game_active = True options ...
I've created a simple C++ logging class. It outputs various loglevels, and adjusts output color accordingly. I'm interested in any tips to improve my coding style. I am especially concerned with my use of #define's in the bottom of Logger.hpp. I was unable to find another way to pass __FILE__ and __LINE__ to the functi...
I wanted to create a script that will perform the k_nearest_neighbors algorithm on the well-known iris dataset. This was mainly for me to better understand the algorithm and process. I think it works, but it could definitely use some tuning up. One thing that has me worried was incorporating multiple features into the ...
I currently got into coding and I am completely self taught. Since I know that my code is far from being perfect, I am asking for advice and tips on how to improve. Feel free to drop in any comments related to the topic - any helpful advice and food for thought is highly appreciated. It doesn't matter if the advice is...
I've seen variations of this assignment where you reverse a string to match it to the original to find out if it is a palindrome, but this version I made only iterates through half of the string comparing it in reverse and would terminate the loop as soon as it notices a difference between the mirrored char and the cur...
Problem explanation I've written a function to validate sudoku. Given a two-dimensional 9×9 array of numbers: Each row should have each of the numbers 1–9 exactly once. Each column should have each of the numbers 1–9 exactly once. Each square should have each of the numbers 1–9 exactly once. · · · | · · · | · · · ...
My task is to write a simple shop. The requirements are : It can have multiple items Each item its own price and quantity Each customer basic identifier such as full name Each customer receives clear receipt Shop keeps the shopping history It's meant to be flexible, easy to expand, high performance considered. I'd ...
I'm trying to write unit tests code for a java class. The class tests an array for sorted (either way) or not. Here is the Unit Tests code: public class SortedOrNotTest { @Test public void test() { int[] A = { 32, 32, 32, 32, 32, 32, 32, 32, 34 }; assertEquals(true, SortedOrNot.isSorted(A)); ...
I read a book about OS development and faced with a simple exercise: write a function that prints a hexadecimal value stored at a register. The program runs as a boot sector. I would really appreciate suggestions and help for size optimization and functionality. [BITS 16] [ORG 0x7C00] EntryPoint: ; Setup the stack...
I have if statement with many checks. There must be a better way to implement this. Does someone have an idea on how to improve this method? I have many similar methods in production. I would like to do the refactoring. private void CheckWorkingHoursValidity(WorkingDayRequestDto workingDayDto) { if (!workingDayD...
I frequently use MathJax, and often I need to write matrices. Since writing matrices using MathJax is very tiresome task, I decided to automate it. Code: import numpy as np import pyperclip class Conversion(): def __init__(self, matrix, n = None, m = None): if matrix == None: self.matrix = n...
Create a class called Stack for storing integers. The data members are an integer array for storing the integers and an integer for storing the top of stack (tos). Include member functions for initializing tos to 0, pushing an element to the stack and for popping an element from the stack. The push() function ...
My goal is to code the knapsack problem algorithm. The problem is that a knapsack has a given weight limit, W. I have a collection of items which have a given weight and value in a file that looks like: # test.txt 1234 4456 4321 7654 ... ... Where value is the first column, and weight is the second. My algorithm s...
As part of a larger authentication/authorization system, I've developed a small .NET Core 3.0 service for hashing passwords using PBKDF2 (with a salt) and validating passwords against a stored hash/salt, for use as part of a larger authentication/authorization system. Code organization: IPasswordService is the main i...
ERROR: type should be string, got "https://leetcode.com/problems/greatest-common-divisor-of-strings/\n\nFor strings S and T, we say \"T divides S\" if and only if S = T + ... +\n T (T concatenated with itself 1 or more times)\nReturn the largest string X such that X divides str1 and X divides\n str2.\nExample 1:\n\nInput: str1 = \"ABCABC\", str2 = \"ABC\"\nOutput: \"ABC\"\nExample 2:\n\nInput: str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput: \"AB\"\nExample 3:\n\nInput: str1 = \"LEET\", str2 = \"CODE\"\nOutput: \"\"\n\n\nNote:\n\n1 <= str1.length <= 1000\n1 <= str2.length <= 1000\nstr1[i] and str2[i] are English uppercase letters.\n\n\nI had 30 minutes to solve this.\nplease review this as a real interview.\nwhat is a red flag, remember code will not be prefect.\nusing System;\nusing System.Text;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace StringQuestions\n{\n /// <summary>\n /// https://leetcode.com/problems/greatest-common-divisor-of-strings/\n /// </summary>\n [TestClass]\n public class GreatestCommonDivisorOfStringsTest\n {\n [TestMethod]\n public void TestMethod1()\n {\n string str1 = \"ABABAB\";\n string str2 = \"ABAB\";\n string res = GCDOfStringsclass.GcdOfStrings(str1, str2);\n Assert.AreEqual(\"AB\", res);\n }\n\n [TestMethod]\n public void TestMethod2()\n {\n string str1 = \"ABCDEF\";\n string str2 = \"ABC\";\n string res = GCDOfStringsclass.GcdOfStrings(str1, str2);\n Assert.AreEqual(string.Empty, res);\n }\n }\n\n public class GCDOfStringsclass\n {\n public static string GcdOfStrings(string str1, string str2)\n {\n int min = Math.Min(str1.Length, str2.Length);\n\n StringBuilder build = new StringBuilder();\n //build largest prefix\n for (int i = 0; i < min; i++)\n {\n if (str1[i] != str2[i])\n {\n break;\n }\n\n build.Append(str1[i]);\n }\n\n // no common prefix\n string prefix = build.ToString();\n if (prefix.Length == 0)\n {\n return string.Empty;\n }\n\n while (str1.Length % prefix.Length != 0 || str2.Length % prefix.Length != 0)\n {\n prefix = prefix.Remove(prefix.Length - 1);\n if (prefix.Length == 0)\n {\n return string.Empty;\n }\n }\n\n for (int i = 0; i < str1.Length / prefix.Length; i++)\n {\n for (int j = 0; j < prefix.Length; j++)\n {\n if (str1[j + prefix.Length * i] != prefix[j])\n {\n return string.Empty;\n }\n }\n }\n\n for (int i = 0; i < str2.Length / prefix.Length; i++)\n {\n for (int j = 0; j < prefix.Length; j++)\n {\n if (str2[j + prefix.Length * i] != prefix[j])\n {\n return string.Empty;\n }\n }\n }\n\n return prefix;\n }\n }\n}\n\n"
I have a MediaWiki 1.33.0 website with only one external addon installed (external extension), which is ContactPage. I have created the following script with that logic: if there is an upgrade to either MediaWiki core OR ContactPage these will be upgraded respectively; else, the script keeps the original state (that i...
Problem Given a list and an integer chunk size, divide the list into sublists, where each sublist is of chunk size. Codes Just for practicing, I've coded to solve the problem using JavaScript and Python. There is also a built-in PHP function for that. If you'd like to review the codes and provide any change/improvemen...
NOTE: Here's the latest version of this program, since this question idled out. This is a recreational script made to update my home server w/ the latest anime from HorribleSubs. I'd like to know if there are any obvious syntactical and performance improvements, details on my usage of Selenium and BS4 and whether or ...
I'm exploring multithreading for some code that I want to speed up in C++. I wrote a simple program to facilitate my understanding. The program takes in two arrays of equal length, the value of the length itself, and a threshold. It outputs all indices i (in any order) where abs(array_1[i]-array_2[i]) < threshold. Here...
Description: This is a simple script for scraping Amazon and eBay category, sub-category and product URLs and saving contents to files. In case of previously saved files, the files will be read and no attempts to re-scrape contents will be executed. Documentation: you will find the most of the information needed in th...
Writing a code to return the last 3 items in a list, if the list has 3 or more elements, otherwise return all list items. But the code looks really bad. What is a better way to write the same code? public void test_arrayListItems() { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("ite...
I wrote this program to print how many times each number occurs in a list: class deleteduplicate: def __init__(self): a=[] num=int(input("Enter the number of elements")) for i in range(0,num): try: a.append(int(input("Enter the number {}".format(i)))) ...
I'm creating a couple of dynamic css classes, and the idea is that i get a string from an episerver context and add that to the class list of an element. I know that numbers can be included in css classes, but what is good css code conduct, is it a good idea to include numbers in class names, or should i change it from...
I've made a simple app that shows if the term entered into the search bar is present in a number of common English words. This is the stackblitz: https://stackblitz.com/edit/react-mostusedwords Note how App, SearchBar and ResultsDisplay all have a variable to track the current search. I am looking for a better way as t...
Any chance people can read my game code and see if reformatting or rewriting is necessary for a better overall code? I'd really appreciate it. #I implemened a random module into my program as it is needed to shuffle the 'cpu_choices' list randomly. import random import time #I implemented time module to introduce a ti...
I am implementing a Fibonacci range in C++17 such that it supports #include "fib.h" #include <iostream> int main() { for (int x : Fibonacci()) { std::cout << x << std::endl; if (x > 100000) { break; } } for (int x : Fibonacci(5)) { std::cout << x << std::endl; } for (int x : Fibona...
I have created a chess game in JavaScript. Right now you can only play against another human. "use strict"; function Piece(x, y, type, color) { let char; let moved = false; switch (type) { case "Pawn": char = "\u2659"; break; case "Knight": char = "\u265E"; break; case "Bis...
I am using the code below trying to replicate the mobile phone feature that displays one or more contact names according to the numbers typed. This code is intended to be used on a JavaScript course I am teaching, so I try to keep it as simple as possible in order to walk the students through a possible scenario and th...
This is my solution for the MaxProductOfThree from codility, it scores 100%, but I'm not a fan of the if if if structure it has going on. Task description A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N). For example, array A ...
I need to add an offset to a time variable inside my class. The code below works, how do i make it more efficient, and elegant. #include <array> #include <iostream> #include <string> #include <vector> class Pressure { public: Pressure(int date, int time):m_date(date),m_time(time) { } int GetDat...
This is my first implementation of a "container" using the Rule of Five, any feedback I'll gladly accept. I've tried to make it as Exception-Safe as possible. I've made it for an assignment. Header #pragma once #include <ostream> #include "Vector.h" class String { public: String(); String(char _char); Stri...
I'm currently taking my first class for c++ and our current lab is asking us to: declare an array with a maximum of 100 integer display total of all the scores display the average of scores entered have a negative as a sentinel since the scores all will be positive (the sentinel is -1) afterwards We're then supposed ...
For university, we have just started to learn C++ as a language, and one of our challenges to do in our spare time is to write an algorithm for 'Peasant multiplication'. In the challenge, we have been told that we cannot use the multiplication operator *. My code for it is as follows. #include <iostream> #include <vec...
Before writing this post I looked around for a library that could solve this problem. I didn't find much so I decided to try to write this. My problem is the following: I have two sets of points with coordinates x1, y1, and x2, y2. The sets have different number of elements. I want to find what is the average distance ...
Problem Validate if a given string can be interpreted as a decimal or scientific number. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true " -90e3 " => true " 1e" => false "e3" => false " 6e-1" => true " 99e2.5 " => false "53.5e93" => true " --6 " => false "-+3" => false "95a54e5...
I have a form for an item (Job Item), that has sets of 2 fields based on a type. field and field + _dolar e.g: cogs_paid and cogs_paid_dollar validation example: cogs_paid or cogs_paid_dollar, if both are empty, validation fails. This goes for all sub-fields. What I did, my current Model: class JobItem < ActiveRecord:...
I took a simple BST implementation which is only really a set (i.e. just element, not key value), and decided to add a node count. I was translating this, which is explained here. In particular the put method (below called bst-insert), but it's not the same thing, the difference in the languages seem large, plus the ve...
I finally made tic tac toe as a beginner(took a month and a bit) and I want to know if I made things more complicated than they should. It seems like a lot of code for a simple game but I'm not sure. Still learning and I would like some advice if there's something really bad. PS:I dont know a clear command other than s...
This is my first ever try at making reusable code. The function makes use of two images to give the illusion of turning on and turning off a button in pygame. I would like to know what would you do differently and if I did a good job? Thanks everyone. Also, this is assuming you already loaded your images and gave it a ...
First, I'd like to provide a little explanation on what my code is supposed to do. It is part of a middle-sized project. I restructured the code to work on its own, and also added little comments to help you understand what I'm doing. This is one of the 5 methods how spectrograms can be analyzed. Now let me give you a ...
I wrote the following function which coverts a JSON format into a CSV. I'll be glad to have a code review because I know that it could be done in a simpler way and with less lines and iterations. Before I will show you the code, I will explain what it does. The format of JSON: [ { "subs": [ { "stat...
Problem Validate if a given string can be interpreted as a decimal or scientific number. Examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true " -90e3 " => true " 1e" => false "e3" => false " 6e-1" => true " 99e2.5 " => false "53.5e93" => true " --6 " => false "-+3" => false "95a54e53" =>...
StringBuilder class is a common class that many have become accustom to, including me. An individual posted a question regarding if there was a comparable method in typescript. Several solutions were mention or linked, but none contained a class. Here is a small class that embodies some of the common StringBuilder meth...
tablou = input("Enter values delimited by space: ") b = tablou.split() t = [] # initial list with int() contents for l in b: r = int(l) t.append(r) I have to do multiple assignments which require working with lists of integers/floats. Above is what I'm using for converting a string to a proper list of integ...
Problem Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is a string that contains same characters ([A-Za-z0-9]) and the order of characters can be different. Code I've solved the anagram problem using a few methods with Python and JavaScript. If you'd like t...
I am writing a simple script that will combine two images at a pixel level, selecting every other pixel from one image, and the other pixels from a second image. from PIL import Image import struct print("Photo 1: ", end="") photo1 = Image.open(input()) # First image, 1920 by 1080 photo1 = photo1.convert("RGB") prin...
I have a problem where I need to construct a given string from scratch for a minimum cost by either: Appending a new character for a cost A Appending a substring of my existing string for a cost B E.g. for a string "abcabc" with a cost of A = 10, B = 11 a 10 ab 20 abc 30 abcabc 41 First I tried a greedy algorithm but i...
I've prepared a tenpin bowling scoring game in Java - https://github.com/chalcrow/DiusBowlingGame I'd like a critical review of the code to identify potential improvements. The code runs like this: Main.java package com.dius.bowling; public class Main { private DiusBowlingGame game; public static void main(S...
I have a Web API method that returns the Active Directory security groups for the specific login user. The below code was working fine but it was taking so munch time nearly 45 sec to get the results. DirectoryEntry root = GetDirectoryEntry() using (var groups = root.Children.Find("OU=Sample Security Groups")) ...
I'm posting this after reviewing the Meta Q&A, Non-code formula spreadsheet, and I believe I've got something here that meets the criteria there. Edit: I've added documentation of the formulas below to make them easier to review. Occasionally I find myself analyzing data that I need to turn into a spreadsheet with two ...
#include <iostream> const bool DEBUG = false; template <typename ... Args> void debug(Args ... args); template <typename ... Args> void _debug(Args ... args) { std::cout << "[" << __FILE__ << ":" << __LINE__ << "] "; (std::cout << ... << args) << std::endl; } #define debug(args...) if (DEBUG) _debug(args); ...
I wrote a min-heap using a binary tree. How can I improve the time complexity of insert and delete function to be \$\mathcal{O}(log(n))\$? ''' Min Heap Tree Implementation ''' class Node: def __init__(self, data): self.data = data self.left = None self.right = None class HeapBT: def __...
I am developing a high-performance(real-time) system, it requires message passing between its component. speed and accuracy is at most priority. I have explored a few options. ConcurrentQueue<T> is super fast BlockingCollection<T> provides a better API. also BlockingCollection<T> waits for the producer to produce the m...
What I want to achieve is the following: #include "tree.h" #include <iostream> int main() { Tree<std::string>* tA = new Tree<std::string>("A"); Tree<std::string>* tB = new Tree<std::string>("B", tA); Tree<std::string>* tC = new Tree<std::string>("C", tA); Tree<std::string>* tD = new Tree<std::string>("D", tB...
I am parsing large XML (DB dump). So, the content looks like many different objects with their properties and dependencies (foreign keys). My way to do it - using lxml.etree (iterparse): def insert_db(content): for item in xml_parser(content): if isinstance(item, DPoint): # manip...
I've built a custom control to handle user input in a human-readable format, but save in a machine-format. It needs to have input validation, and to convert UI-input to a base format. I'm interested in knowing: Have I implemented this in a proper and idiomatic Angular way? Are there any UI and typescript mistakes? Hav...
All I would like is for help with putting this code into separate classes as I cant seem to figure it out. I would just like to understand how this would be possible with this set of code. using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace FinalDatabaseConnection { ...
This is our company's first attempt at an API and a mobile friendly web project, primarily we are desktop developers. We are using Identity Server 4 for serving up tokens and authentication, we have a mobile friendly web application and an API. I did a lot of the groundwork setting up the communication between the app...
I've written a class that implements something akin to the token bucket algorithm so that I may rate limit aysnc HTTP requests made from my application. The code works but I'm still not sure if it feels 'right', maybe just because I am new to async programming in Python. Specific concerns: It feels weird/bad how the s...
So I have a loop that works great, but doing some testing I notice it is a bit slow. I get an average time within the loop of about 0.11 seconds. Include that with some arrays containing a length of over 100 and the time starts making a big difference. So I mainly want to improve the speed of the loop without compromis...
Problem Write a function that accepts a string, capitalizes the first letter of each word in the string, and returns the capitalized string. Examples function('a short sentence') => 'A Short Sentence' function('a lazy fox') => 'A Lazy Fox' function('look, it is working!') => 'Look, It Is Working!' Code I've solved the...
Have you ever wanted to get just not one "best" element from a list, but all of them, or a random element of the best ones? That's what the Best class is here for. Opinion-based? Definitely not! Features: Should work with any kind of element. Should always keep track of the best elements seen so far. Should be able to...
I have created a function that will remove outliers from a series of data. Generally the data n dimensional. Loosely, an outlier is considered an outlier if it +/- deviates by 1.5 standard_deviation's from the mean (see code for more detailed explanation of what constitutes an outlier). The function can handle N dimen...
After my previous code review, I'm sharing my new code, and asking for better ways (which always exist) to improve the code, even with new libraries. The only thing that important to me, is the way of receiving the parameters have to be the command line [I am using Linux OS, so it's highly common to use command line pa...
Inspired by gsl::narrow_cast, I created my own implementation with the addition of a couple of features: a static assert on the types to ensure the cast is actually narrowing (if future changes to the code mean the cast is no longer narrowing, we don't want to still have a narrow_cast there) the version without a runt...