instruction
stringlengths
71
95.1k
Small Calculator I made for myself while trying to learn COBOL for fun. Compiler used is GNUCOBOL. Just asks for input and will either do multiplication, subtraction, or addition. Completes run after input is asked. MATH IDENTIFICATION DIVISION. PROGRAM-ID. MATH. DATA DIVISION. WORKING-STOR...
For my job I was tasked with writing a faster version of Arduino's map. The requirements were only use addition and subtraction, since these are cheap operations on our board. For reference, here is Arduino's implementation: long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) ...
I am learning swift and I came across this problem. Converting each start letter to capitalized form if it's lowercase. func upperCaseFirstCharacter(str:String){ let myArr = str.components(separatedBy: " ") var finalStr :String="" for word in myArr { let myStr = word.replacingCharacters(in: ...str.s...
I made this python script to create dated folders within a directory. This is my first practical automation project and I don't want to cement any bad habits so I was wondering if there is anything I can improve in the code I have written here. Any feedback will be appreciated! The main challenge I had was to account f...
I'm writing my own expression tree system, just for fun, but I have a few doubts about my code. My goal here is to create an abstract layer of expressions, and allow different "languages" to extend it. For example, those are my base components : //Base expression class for all expressions in every domain public abstra...
Could anyone review my code for a calculator using tkinter? I'm attempting to use two classes, one with the functions of the calculator and a second which creates the GUI. It seems to work fine (although I'd like to add keyboard functionality), so I'd like to ask if there is anything that I could have done better. The ...
first allow me to explain the what the purpose of this program is: a "barcode" as I'm calling it consists of three parts: plant_id=['ATX','HOU','CHS'] Serial Number: a string of 9-digits mod 10 digit: A digit (as a chr()) between 0-9 that is assigned randomly to the end of a barcode. So a full barcode would look like...
I have written this code that reads a JSON and CSV files compares them and outputs to a text file This output file will contains the association that my program has created in the following format <CSV_SENSOR_ID>:<JSON_SENSOR_ID>. If a flying object was only picked up by one of the sensors, the other sensor’s ID should...
I am working with a data set that has many variables. Currently I am storing the data in many indented dictionaries in the following way: import numpy as np X_POSITIONS = [0,1.5,1] Y_POSITIONS = [0,1,2] CHANNELS = ['left pad', 'right pad', 'top pad', 'bottom pad'] data = {} for x in X_POSITIONS: data[x] = {} ...
I seem to have taught myself the basics of c++ living off grig in the woods of Alaska. Most of this has been done on my android phone using cpp droid. This is the first time anyone has seen any of my code and I am curious what you think of it. There no error checking and the style may look a little strange on a normal ...
Please make code review for command line utility for user data migration from MUBI.com to letterboxd.com. Utility makes Get HTTP request downloads json-data, parses it and saves as CSV-file. Can be found at github // mubi2letterboxd is a simple command line utility for user data migration from MUBI to letterboxd. // Wi...
I am fairly new to Python and have tried to create a tic tac toe game that is completely automatic, where you can see if a player1 has an advantage if you let it start in the middle and I would love some feedback on it and improvement areas. That is, is it something that looks crazy, something that I do wrong or someth...
I need help to optimise the code as it becomes slow with a large dataset. I have an exchange simulation program that takes in market prices from a csv and then allows the user to place bids and offers for the products (currencies) that are up for trade. OrderBookEntry.cpp contains the constructors #include "OrderBookEn...
A link to the pull request in question. I maintain a C++ DLL / Game Maker library that constructs an environment that allows one to call any game maker script/function from within the C++ dll directly. It does this by placing all DLL function calls in a second thread that then communicates function calls to the origina...
I don't know if anyone is interested but I'll give it a chance. I have some basic experience in coding Python and would like to know if there are any suggestions on writing better code to improve myself. There is no need to write the code for me, but if you guys have any tips on how to do it better that would be awesom...
I programmed a calculator with int operations. The calculator stores functions in a dictionary. Also, the calculator stores how many arguments the function takes in a dictionary. The input format is arguments followed by module and function name. These are split by lines and spaces. Input lines that start with a # are ...
For an interview, I had to create a card game called match. The rules were the following: Players can choose a number of packs of playing cards and combine them into a single deck. The deck can be shuffled. Cards are played sequentially from the top of the deck into the pile, If two cards played sequentially match, the...
I am trying to implement a tiny text file read / write class FileIO in order to make the operations of reading / writing pure text files easily. The usage is like: FileIO.Instance.FileWrite("TextFile1.txt", "This is a test1."); FileIO.Instance.FileWrite("TextFile2.txt", "This is a test2."); Console.WriteLine(FileIO.Ins...
I devised a new primality test isPrimeNumber() below which determines if 1000000007 is prime. It works fine but the code looks unprofessional in my opinion. Is there any way to refactor it to make it more readable? Maybe inline the recursive gcd() function so everything is self-contained in the isPrimeNumber() function...
I wrote this to go in my simple static site generator. it takes any plaintext file (but meant for html) and injects the specified file contents and other data at matching tags. This is my first "big" JavaScript project, and most of my knowledge has come from several-year-old posts on StackExchange, YouTube, and Medium,...
My code works as intended. CategoryController class has getAllCategories method, which tells ContentOrderMap class to map differently ordered categories to their respective OrderType enum. The intention is whenever @RequestParam(defaultValue = "DEFAULT") OrderType categoriesOrderType changes from DEFAULT, to lets say, ...
This defines count-pairs which takes a collection of integers returns the number of pairs of integers that are equal to each other. If the input collection has these integers ... 1 2 0 2 1 3 2 ... then count-pairs returns 2 because one pair can be made with the 1's a second pair can be made with the 2's The leftove...
I had like to get some feedback about my Thread Safe Python Client-Server example. Is it really thead-safe? Do you see any dead-locks or other thread-safe problems? https://github.com/icarpis/PyThreadSafeClientServer # Server import socket import sys import threading import select class ServerConnection(): def __...
I am looking for feedback on my code's overall structure and design. I made a few concessions in reusability for the sake of not overcomplicating things (static/const public variables in the Game1 class) but think it's pretty usable otherwise. I would like to make this room generator easy to use and adjust for future p...
This currently runs with 1400+ sockets and manages data correctly and in the manner the application requires. I do have an issue with the HandleData method where the receive channel stacks an excess of messages. They eventually all get processed the channel rarely exceeds 250 items. Besides the obvious of using an off ...
I have written an API for a dating service. This part is related to user authentification, authorization, login and etc. It uses FastAPI, which in turn is based on starlette web server. You may wonder what is fastapi.Depends.... It's internally calling a passed function when the endpoint is requested to satisfy its dep...
Still a bit new to Kotlin and coroutines, so I want to learn best practices. The following code seems to work as expected in it's original context, though the naming has been tweaked here. The list of widgets is retrieved from the database, and the UI is updated correctly. My main question is, in updateList is it appro...
ERROR: type should be string, got "https://github.com/speedrun-program/load-extender\nI posted a version of these programs for review about a week ago and ended up getting good advice on how to improve them. this was the post which shows the old code: C and C++ programs which let you lengthen the time it takes to access files\nNow that I've improved the code, I'm posting the new version here for review since this page says I'm allowed to.\nI did everything suggested by the accepted answer in the original post except for using std::filesystem::path objects in the hash map because I couldn't figure out how to do that.\n*sorry that I've been making so many small adjustments to the code occasionally. But I think at this point it should be complete.\nstruct_and_functions.h:\n#include <stdint.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <atomic>\n#include <vector>\n#include <exception>\n\nstatic bool TOO_BIG_DELAY_SEEN = false;\n\nstruct delay_sequence\n{\n std::atomic<std::size_t> index;\n std::vector<std::chrono::milliseconds> delays;\n bool repeat;\n bool reset_all;\n\n delay_sequence() { index = 0; repeat = false; reset_all = false; }\n delay_sequence(const delay_sequence& copy_sequence)\n {\n index = copy_sequence.index.load();\n delays = copy_sequence.delays;\n repeat = copy_sequence.repeat;\n reset_all = copy_sequence.reset_all;\n }\n delay_sequence& operator=(delay_sequence copy_sequence)\n {\n index = copy_sequence.index.load();\n delays = copy_sequence.delays;\n repeat = copy_sequence.repeat;\n reset_all = copy_sequence.reset_all;\n return *this;\n }\n};\n\nstatic std::size_t setup_delay_sequence(delay_sequence& current_sequence, std::wstring& line, std::size_t start_position)\n{\n std::size_t delay_sequence_length = 1;\n for (std::size_t line_position = start_position; line_position < line.length(); line_position++)\n {\n if (line[line_position] == L'/')\n {\n ++delay_sequence_length;\n }\n else if (line[line_position] == L'-')\n {\n --delay_sequence_length;\n if (delay_sequence_length == 0)\n {\n current_sequence.reset_all = true;\n break;\n }\n current_sequence.repeat = true;\n break;\n }\n }\n return delay_sequence_length;\n}\n\nstatic void remove_non_digits(std::wstring& delay_substr)\n{\n std::size_t position_to_write = 0;\n for (std::size_t i = 0; i < delay_substr.length(); i++)\n {\n if (isdigit(delay_substr[i]))\n {\n delay_substr[position_to_write] = delay_substr[i];\n ++position_to_write;\n }\n }\n delay_substr.erase(position_to_write);\n}\n\nstatic void set_delays(std::vector<std::chrono::milliseconds>& delays, std::wstring& line, std::size_t delay_sequence_length, std::size_t slash_position)\n{\n delays.reserve(delay_sequence_length);\n unsigned long long max_delay = std::chrono::milliseconds::max().count();\n while (slash_position != std::wstring::npos && delays.size() != delay_sequence_length)\n {\n std::size_t next_slash_position = line.find(L'/', slash_position + 1);\n std::wstring delay_substr = line.substr(slash_position + 1, next_slash_position - slash_position - 1);\n remove_non_digits(delay_substr);\n if (delay_substr.length() == 0)\n {\n delays.push_back(std::chrono::milliseconds(0));\n slash_position = next_slash_position;\n continue;\n }\n try\n {\n unsigned long long delay_time = std::stoull(delay_substr);\n if (delay_time > max_delay)\n {\n throw std::out_of_range(NULL);\n }\n delays.push_back(std::chrono::milliseconds(delay_time));\n }\n catch (const std::out_of_range& oor)\n {\n if (!TOO_BIG_DELAY_SEEN)\n {\n printf(\"delay time can only be %llu milliseconds\\n\", max_delay);\n TOO_BIG_DELAY_SEEN = true; // TOO_BIG_DELAY_SEEN only changed here\n }\n delays.push_back(std::chrono::milliseconds(max_delay));\n }\n slash_position = next_slash_position;\n }\n}\n\nstatic void set_key_and_value(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& line)\n{\n std::size_t slash_position = line.find(L'/');\n if (slash_position == std::wstring::npos)\n {\n return;\n }\n std::size_t position_before_whitespace = line.find_last_not_of(L\" \\t\\f\\v\\r/\", slash_position);\n if (position_before_whitespace == std::wstring::npos)\n {\n return;\n }\n std::wstring file_name = line.substr(0, position_before_whitespace + 1);\n delay_sequence current_sequence;\n std::size_t delay_sequence_length = setup_delay_sequence(current_sequence, line, slash_position + 1);\n set_delays(current_sequence.delays, line, delay_sequence_length, slash_position);\n my_rh_map[file_name] = current_sequence;\n}\n\nstatic unsigned char rh_map_setup(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)\n{\n std::size_t line_count = 1;\n std::wstring line;\n std::wifstream my_file;\n my_file.open(\"files_and_delays.txt\");\n if (my_file.fail())\n {\n printf(\"couldn't open files_and_delays.txt\\n\");\n return 1;\n }\n while (std::getline(my_file, line) && line_count < SIZE_MAX)\n {\n ++line_count;\n }\n if (line_count == SIZE_MAX)\n {\n printf(\"can't store %zu delays\\n\", SIZE_MAX);\n return 1;\n }\n my_rh_map.reserve(line_count);\n my_file.clear();\n if (!my_file.seekg(0, std::ios::beg))\n {\n printf(\"seekg on files_and_delays.txt failed\\n\");\n return 1;\n }\n line.clear();\n while (std::getline(my_file, line))\n {\n set_key_and_value(my_rh_map, line);\n line.clear();\n }\n my_file.close();\n return 0;\n}\n\nstatic void delay_file(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& file_name)\n{\n rh::unordered_flat_map<std::wstring, delay_sequence>::iterator rh_map_iter = my_rh_map.find(file_name);\n if (rh_map_iter != my_rh_map.end()) // key found\n {\n printf(\"%ls successfully found in hash map\\n\", file_name.c_str());\n delay_sequence& found_sequence = rh_map_iter->second;\n if (found_sequence.reset_all) // reset all delay sequences\n {\n for (auto& it : my_rh_map)\n {\n it.second.index = 0;\n }\n printf(\"all delay sequences reset\\n\");\n }\n else\n {\n if (found_sequence.repeat) // reset delay sequence\n {\n found_sequence.index = found_sequence.index.load() % found_sequence.delays.size();\n printf(\"%ls delay sequence reset\\n\", file_name.c_str());\n }\n if (found_sequence.index < found_sequence.delays.size())\n {\n // this is defined in the main file so it won't sleep if being used with load_extender_test.exe\n call_sleep_thread(found_sequence.delays[found_sequence.index]);\n found_sequence.index += 1;\n }\n else // delay sequence already finished\n {\n printf(\"%ls delay sequence already finished\\n\", file_name.c_str());\n }\n }\n }\n else // key not found\n {\n printf(\"%ls not found in hash map\\n\", file_name.c_str());\n }\n}\n\nload_extender_test.cpp\n#include <chrono>\n#include <thread>\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\n// this is defined here so delay_file function will use the right version\nstatic void call_sleep_thread(std::chrono::milliseconds duration)\n{\n unsigned long long total_milliseconds = duration.count();\n unsigned long long total_seconds = total_milliseconds / 1000;\n short remaining_milliseconds = total_milliseconds % 1000;\n printf(\"sleep for %llu second(s) and %d millisecond(s)\\n\", total_seconds, remaining_milliseconds);\n}\n\nnamespace rh = robin_hood;\n\n#include \"struct_and_functions.h\" // included here so alias can be used\n\n// these are global so the hooked function can see them\nstatic rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n// SETUP_SUCCEEDED only changed here\nstatic unsigned char SETUP_SUCCEEDED = rh_map_setup(my_rh_map);\n\nstatic void print_rh_map()\n{\n printf(\"\\n---------- hash map current state ----------\\n\");\n for (auto& it : my_rh_map)\n {\n printf(\"%ls / \", it.first.c_str());\n delay_sequence& sequence_to_print = it.second;\n for (std::size_t i = 0; i < sequence_to_print.delays.size(); i++)\n {\n // casted to unsigned long long to get rid of warning message\n // visual studio on windows wants %lu, but gcc on linux wants %llu\n printf(\"%llu \", (unsigned long long)sequence_to_print.delays[i].count());\n }\n if (sequence_to_print.reset_all)\n {\n printf(\"RESET_ALL \");\n }\n else if (sequence_to_print.repeat)\n {\n printf(\"REPEAT \");\n }\n printf(\": INDEX %zu\", sequence_to_print.index.load());\n printf(\"\\n\");\n }\n printf(\"---------------------------------------------\\n\\n\");\n}\n\nstatic void test_all_inputs()\n{\n std::wstring test_path;\n std::wifstream input_test_file;\n input_test_file.open(\"test_input.txt\");\n if (input_test_file.fail())\n {\n printf(\"couldn't open test_input.txt\\n\");\n return;\n }\n if (SETUP_SUCCEEDED == 0)\n {\n print_rh_map();\n while (std::getline(input_test_file, test_path))\n {\n printf(\"testing input: %ls\\n\", test_path.c_str());\n delay_file(my_rh_map, test_path);\n print_rh_map();\n test_path.clear();\n }\n }\n else\n {\n printf(\"setup failed\\n\");\n }\n input_test_file.close();\n}\n\nint main(int argc, char* argv[])\n{\n printf(\"\\ntest start\\n\");\n test_all_inputs();\n printf(\"test finished, press Enter to exit\\n\");\n std::wstring input;\n std::getline(std::wcin, input);\n return 0;\n}\n\nload_extender.cpp\n#include <chrono>\n#include <thread>\n#include <stdio.h>\n#include <dlfcn.h>\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\n#define DISABLE_PRINTF\n\n#ifdef DISABLE_PRINTF\n #define printf(fmt, ...) (0)\n#endif\n\n// this is defined here so delay_file function will use the right version\nstatic void call_sleep_thread(std::chrono::milliseconds duration)\n{\n std::this_thread::sleep_for(duration);\n}\n\nnamespace rh = robin_hood;\n\n#include \"struct_and_functions.h\" // included here so alias can be used\n\n// these are global so the hooked function can see them\nstatic rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n// SETUP_SUCCEEDED only changed here\nstatic unsigned char SETUP_SUCCEEDED = rh_map_setup(my_rh_map);\n\nstatic auto original_fopen = reinterpret_cast<FILE *(*)(const char *path, const char *mode)>(dlsym(RTLD_NEXT, \"fopen\"));\n\nFILE *fopen(const char *path, const char *mode)\n{\n if (SETUP_SUCCEEDED == 0)\n {\n // finding part of path which shows file name\n std::size_t file_name_index = SIZE_MAX; // overflows to 0 and checks entire path if no slash is found\n std::size_t end_index = 0;\n for (; path[end_index] != '\\0'; end_index++)\n {\n if (path[end_index] == '/')\n {\n file_name_index = end_index;\n }\n }\n std::wstring file_name(&path[file_name_index + 1], &path[end_index]);\n delay_file(my_rh_map, file_name);\n }\n return original_fopen(path, mode);\n}\n\nload_extender_dll.cpp\n// allows std::chrono::milliseconds::max().count();\n#define NOMINMAX\n\n#include <chrono>\n#include <thread>\n#include <Windows.h>\n#include <easyhook.h>\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\n#define DISABLE_PRINTF\n\n#ifdef DISABLE_PRINTF\n #define printf(fmt, ...) (0)\n#endif\n\n// this is defined here so delay_file function will use the right version\nstatic void call_sleep_thread(std::chrono::milliseconds duration)\n{\n std::this_thread::sleep_for(duration);\n}\n\nnamespace rh = robin_hood;\n\n// included here so alias can be used\n#include \"struct_and_functions.h\"\n\n// these are global so the hooked function can see them\nstatic rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\nstatic unsigned char SETUP_SUCCEEDED = rh_map_setup(my_rh_map);\n\nstatic NTSTATUS WINAPI NtOpenFileHook(\n PHANDLE FileHandle,\n ACCESS_MASK DesiredAccess,\n POBJECT_ATTRIBUTES ObjectAttributes,\n PIO_STATUS_BLOCK IoStatusBlock,\n ULONG ShareAccess,\n ULONG OpenOptions)\n{\n if (SETUP_SUCCEEDED == 0)\n {\n std::wstring file_path = ObjectAttributes->ObjectName->Buffer;\n // +1 so '\\' isn't included. If '\\' isn't found, the whole wstring is checked because npos is -1\n std::wstring file_name = file_path.substr(file_path.rfind(L\"\\\\\") + 1);\n delay_file(my_rh_map, file_name);\n }\n return NtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions);\n}\n\nextern \"C\" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo);\n\nvoid __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) {\n HOOK_TRACE_INFO hHook1 = { NULL };\n LhInstallHook(\n GetProcAddress(GetModuleHandle(TEXT(\"ntdll\")), \"NtOpenFile\"),\n NtOpenFileHook,\n NULL,\n &hHook1);\n\n ULONG ACLEntries[1] = { 0 };\n LhSetExclusiveACL(ACLEntries, 1, &hHook1);\n return;\n}\n\nload_extender_exe.cpp\n#include <tchar.h>\n#include <iostream>\n#include <string>\n#include <Windows.h>\n#include <easyhook.h>\n\nvoid get_exit_input()\n{\n std::wcout << \"Press Enter to exit\";\n std::wstring input;\n std::getline(std::wcin, input);\n std::getline(std::wcin, input);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n WCHAR* dllToInject32 = NULL;\n WCHAR* dllToInject64 = NULL;\n LPCWSTR lpApplicationName = argv[0];\n DWORD lpBinaryType;\n if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))\n {\n std::wcout << \"ERROR: This exe wasn't identified as 32-bit or as 64-bit\";\n get_exit_input();\n return 1;\n }\n else if (lpBinaryType == 0)\n {\n dllToInject32 = (WCHAR*)L\"load_extender_32.dll\";\n }\n else\n {\n dllToInject64 = (WCHAR*)L\"load_extender_64.dll\";\n }\n DWORD processId;\n std::wcout << \"Enter the target process Id: \";\n std::cin >> processId;\n\n wprintf(L\"Attempting to inject dll\\n\\n\");\n\n // Inject dllToInject into the target process Id, passing \n // freqOffset as the pass through data.\n NTSTATUS nt = RhInjectLibrary(\n processId, // The process to inject into\n 0, // ThreadId to wake up upon injection\n EASYHOOK_INJECT_DEFAULT,\n dllToInject32, // 32-bit\n dllToInject64, // 64-bit\n NULL, // data to send to injected DLL entry point\n 0 // size of data to send\n );\n\n if (nt != 0)\n {\n printf(\"RhInjectLibrary failed with error code = %d\\n\", nt);\n PWCHAR err = RtlGetLastErrorString();\n std::wcout << err << \"\\n\";\n get_exit_input();\n return 1;\n }\n else\n {\n std::wcout << L\"Library injected successfully.\\n\";\n }\n\n get_exit_input();\n return 0;\n}\n```\n\n"
Background I have a script that either takes a text file that contains a list of player_ids or not. If the user provides a player_id list i ensure that all the ids are part of the tranche date they provided and then run the process job for all the player ids in the list. If the user has not provided a list of players t...
The code below is an implementation of purely recursive solution to find a powerset of any given set. The input set is a string, and the output - array of strings. Both of them are wrapped into a structure for convenience. The underlying algorithm is pretty common one. The recursive function executes exactly 2^n - 1 t...
us = 'US Dollar [$]' sr = 'Saudi Riyal [S.R]' # Questions for the user :) print('Which Currency You Want?\n') print("1 - Saudi Riyal To US Dollar\n") print("2 - US Dollar To Saudi Riyal\n") def convert(): amount = input('Please enter the amount: ') def option1(): ...
I want to fix number of digits after '.' in digit represented by string. Is there better solution than mine? My code def convert(s): """ Convert 1234.12345678 to 1234.123""" vec = s.split('.') if len(vec) == 2 and len(vec[1]) > 3: return vec[0] + '.' + vec[1][:3] return s
I wrote the following C++ code a while ago to generate random graphs for a project I was working on: #include "stdafx.h" #include <iostream> #include <algorithm> // std::min_element, std::max_element #include <sstream> #include <fstream> #include <string> #include <iterator> #include <random> #include <vector> #d...
I have implemented a C code in order to answer an interview question. I would be appreciated if someone would improve the code. Task is an easy, however I want to achieve best efficiency in terms of readability and simplicity. Pardon my English again. Sorry that I have just printed out the result. The edit distance...
I have attempted to implement a similar version of the STL Vector; several functions are missing but I'd like a few words of advice on whether I am indeed on the right track or whether I should change my approach. My goal here is to understand how the vector works behind the scenes, rather than using it for my applicat...
I'm currently trying to develop an easy to use TCP networking library based on boost::asio. This is my first attempt to work with boost::asio and therefore I've got some questions: Firstly, is my code okay and easy to understand? Are there any misleading conventions? Are there any memory leaks? Is there any improvemen...
I have some questions about a code I found on stackoverflow. The code does what I want to do. Redirects to HTTPS and WWW when doesn't exist in URL. But, I want now to understand what I'm doing. So, here is the code I use: # Redirect non HTTPS to HTTPS # RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}/...
On my app I'm checking the equality between an objects array property and a nested object property - based on the results I return a new objects array. The items objects array: [{name: 'test', value: 1, category: 'a'},{name: 'test2', value: 2, category: 'b'},{name: 'test3', value: 3, category: 'c'}] The itemList objec...
I have an Android quiz app that I am building to learn kotlin / android app development. Here is an object I have which acts as one of many question builders. Is there a better way of writing this? package com.maxcell.sumitup import java.security.SecureRandom import kotlin.math.roundToInt object MultiplicationFac...
This is an updated question with new code, taking into account your comments from last time: Car computer in python / GPS tracking I have an old car that I use for long distance driving and have coded an onboard computer based on a Raspberry Pi 3 and a few other modules. I use a FONA 808 from Adafruit as the cellular m...
I have an array of objects, reviews which I get from an API endpoint. This object looks like this: [ { name: "Facebook", count: 50 }, { name: "Google", count: 43 }, { name: "TripAdvisor", count: 67 }, { name: "Other", count: 130 } ] I have a chart.js Pie chart that I'm feeding this data to. I'm using the name ...
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...
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...
I need to update a nested array of settings. There are several difficulties that I managed to solve, but I'm pretty sure the code can be written much simpler. I just don't know how, which is why I'm asking for a simpler solution. Problem: I have a nested array of settings in the database. I have a form with fields tha...
I created a rest controller with Spring Boot, I am trying to learn what I should write on my tests, right now I only check status codes and keys existence. I am planning to build an API to showcase at interviews. I would like you to tell me what do you think of my tests class and what I should add. I will use your advi...
This is a follow-up question for A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++, A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++ and A Function Applier for Applying Various Algorithms on Nested Container Things...
(This is the Non-const version, I have to implement the const one too). Could someone please review this implementation? This is made for std::vector I'm unsure whether I respected all requirements for LegacyRandomAccessIterator; so if I'm missing something, please do let me know. namespace random_access { template...
This is from a leetcode question I am working on. The problem is the following: create an algorithm that works in the the following fashion: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] the output is: [2,7,14,8] by applying the following series of operations: The XOR values for queries are: [0,1] = 1 xor 3 = 2 ...
I have a function to filter a 2-d array. It works. But I am not sure if the following mechanism is a sensible concept. The idea is: loop over the input array which is received as input_arr(y,x) store the values in temp_arr(x,y), since in order to resize the y-dimension it needs to be last dimension, so I have to tran...
I am trying to generate sequences containing only 0's and 1's. I have written the following code, and it works. import numpy as np batch = 1000 dim = 32 while 1: is_same = False seq = np.random.randint(0, 2, [batch, dim]) for i in range(batch): for j in range(i + 1, batch): if np.array...
In general, I'd love some comments on this basic queue using dynamic allocation. In particular, I want comments about whether this queue is good in embedded systems, for example say a a sensor network gateway, which has to queue up packets to be forwarded on say a UART. I hear normally that mallocs are a bad idea for e...
I'm using a function to determine if resources can be used again or not. This is the numpy array I'm using. 'Resource_id', 'Start_date', 'end_date', 'start_time', 'end_time', 'overload' [548, '2019-05-16', '2019-05-16', '08:45:00', '17:40:00',2], [546, '2019-05-16', '2019-05-16', '08:45:00', '17:40:00',2], [5...
As a little standard exercise, I wrote an integer to roman numerals converter in F03. The result looks already neat enough, for my standards, but I wonder whether it could be made snappier without sacrificing clarity. For folks not familiar with the simple syntax of modern Fortran, I suggest the following quick modern ...
Original problem: Given \$x\$ number of tests that should run in \$y\$ number of seconds shift the time per test so that each test takes a little longer than the next. Example: If running 10 tests over 10 seconds, the equal time per test would be 1 second each. Instead, have the first test take .5 seconds and the last ...
Problem I'm seeking a clean and efficient way to determine whether one string is an initialism/acronym of another. Example: IBM => International Business Machines However, a key condition for my use case is that an initialism might be constructed using more than one letter from each consecutive word. Example: ANEXAIST ...
I have written Haskell code to my spec to help me grasp types and syntax, because I am learning. I hope to generalize it further to accommodate more kinds of equations. I am (perhaps prematurely) worried that repeated usage of delta in multiple places is going to slow down my code, but I don't see how I can avoid it. I...
I've written a working and complete proof of concept that shows a spectrograph in Matplotlib. I want to nail down this proof of concept before I continue with development, and I'm not thrilled with the way I've had to hack around using numpy. The graph shows the spectrum as divided into five harmonics. Each harmonic se...
Just looking for some feedback and constructive criticism. This is the second script I ever made. Just recently started learning the basics. Anyway just wanted to post the script and see if maybe I can get some input on where I can maybe do things better. The script is for extracting the compressed file types you run i...
Background The function computes moving arrange and offers some other minor widgets like possibility to return data frame in original order or automatically derive variable name for the moving average. In majority of actual use cases similar results could be easily achieved using combinations of usual suspects like acr...
This is my first ever created program I've made. It's not very good but I'm pretty proud of it. If you have any suggestions I could add into the calculator I would gladly do that. using System; using System.IO; using System.Linq; using System.Collections.Generic; namespace CSharp_Shell { public static class Progra...
I have written a program that takes the original file (the script of 'the bee movie') and does a word count, a unique word count and replaces some of the words. This is really just a rushed version, so if there are any errors or ways of fixing/making the code more efficient, please let me know. Link to the script: http...
I have 2 files wholesaler_a.csv id;ean;manufacturer;product;description;packaging product;foo;packaging unit;amount per unit;items on stock (availability);warehouse 12345600001;23880602029774;Drinks Corp.;Soda Drink, 12 * 1,0l;Lorem ipsum usu amet dicat nullam ea;case 12;bar;bottle;1.0l;123;north and wholesaler_b.jso...
I started learning Python these days and made my first code. Guess_The_Number and I would like some comments to improve or if I am on the right track. Thank you very much in advance P.s: I am trying to create my own function. def guess_number (answer): trys = 0 while trys < 5: guessing = int(in...
EDIT To me JSON.stringify is not the solution here, as it is much slower than recursion JSON.stringify(fakeData) .replace(/,/g, ';') .replace(/:(?={)/g, '') .replace(/"/g, '') //Result Recursion with reduce x 816,321 ops/sec ±7.38% (80 runs sampled) JSON.stringify x 578,221 ops/sec ±1.72% (...
I wrote a simple encryption function that uses argon2d as the KDF and XChaCha20-Poly1305 as the AEAD. Since it is very easy to not get things right when dealing with encryption, I would appreciate if someone could review my script and tell me if it has any vulnerabilities and could be used in the real world to encrypt ...
I have a an if statement that works just fine, however, it has become a bit long and I need help to figure out how I can reduce the lines of code and thereby the readability. I have a defaultMonth and set of months and a corresponding price. I need to add or reduce the price depending on the defaultMonth and month sele...
I have a training dataset from which I want to draw samples in a random fashion such that all samples are used before getting randomly shuffled again. For this reason I implemented a simple random index generator. For a dataset of 10 samples, the output looks something like this: 0 1 2 3 4 5 6 7 8 9 4 3 7 8 0 5 2 1 6 ...
Several years ago (must have been 2012 or so) I wrote a module to manage command-line parameters in a unix-like fashion. At the time, the compilers I had access to were still working their way up to the 2003 standard. In particular, allocatable strings and class(*) still had issues. So far, the module has served me wel...
This checks if a given username is valid, before doing any database lookups. (I know it's possibly better to use regular expressions, but I wanted to be able to give specific errors.) I'm curious if there is a cleaner way to represent the set of valid characters. bool check_username_valid(const string& str, string &out...
I am trying to implement a Java version sub-string extractor with "start keyword" and "end keyword" and the extracted result is from (but excluded) the given start keyword to (but excluded) end keyword. The output sub-string follows the rules as below. The leading/trailing spaces in output sub-string is removed. If th...
I wrote some template function, which helps me with reading input from terminal, doing error handling, validating input. The full code with template specialisation for strings looks like this: template <typename T> T getInput(const std::string& prompt, std::istream& istream, std::ostream& ostream, std::funct...
Hello guys could you help me please how to render this code as OOP? I want to improve this code and follow the OOP anyone could help me, please thank you in advance this is class Expression class Expression { public int type; public int value; public Expression leftOp; public Expression ...
I need a queue in C for an embedded application in which I cannot allocate memory dynamically. I avoided using void* for the queue elements (which is not convenient lifecycle-wise) by having the user provide their underlying array. user_code.c: #include "generic_queue.c" typedef struct custom_t { /* whatever */ } ...
I am trying to emulate Java 8's predicate chaining in JavaScript. So far it works, but is there a more efficient way to write this? Furthermore, I had to create get and run methods to return the predicate so that is can be passed into a filter function. Update: I added an _unwrap method to unwrap the internal predicate...
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 6689664...
I have implemented an exhaustive depth-first grid search that searches for all possible words in the 8 connected regions. Is there any way I can make this faster or memory efficient than it is now? I feel like passing a copy of the seen set in dfs(xx, yy, seen.copy(), word + grid[x][y]) is an overhead that can possibly...
I have some logic on my JSX for an element in a grid, if element is selected, then add to redux, if element is not selected then remove from redux... is working ok, but I sense a bad smell... <GridSelector items={items} onChange={(categoryId, isSelected) => { favorites[categoryId] = isSe...
STR2INCHES is an Excel VBA Function that will convert string text for Imperial length measurements to a decimal number of Inches. It handles both English and Spanish words, abbreviations and symbols for yards, feet and inches. Dashes are treated like they are spaces, and so it just does not care where dashes are used o...
I have a string containing several items listed in the following notation: myString = '[A][B][C]' And I would like to parse that to a python list of several strings: ['A', 'B', 'C'] I know this can be solved with: myString = myString.lstrip('[') myString = myString.rstrip(']') myList = myString.split('][') I'd just ...
This is my first neural net, previously I had it with just one hidden layer. I have now given it an adjustable number of hidden layers. It all works perfectly (asin I dont get nans and infs). I have specifically avoided the use of pointers since I am still very new to coding and want to keep things as simple as possibl...
I'm writing an application with two basic class types: DocumentObject Property (of document object). Property instances are attributes of the DocumentObject class and The Property class has several simple attributes of its own (value, unit, etc.) and some methods. In trying to make the scripting as user friendly as p...
I wrote a simulator that simulates chess games. The game uses probability to determine the player that is most likely to win. though they might be upsets(a low rated player winning the game). I would love insights and suggestions on how to improve on the algorithm, general review is also welcomed. NOTE: The names and r...
I have written a function splitAtPredicate that splits the list at element x satisfying p, dropping x and returning a tuple. -- | 'splitAtPredicate', applied to a predicate @p@ and a list @xs@, -- splits the list at element @x@ satisfying @p@, dropping @x@. splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a]) splitAtPr...
Hello I've created to do app with some additional functionality. Since I am new in JS I would love some feedback if you guys could point out some obvious mistakes/good practices/better solutions or implementations I will be grateful. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta...
Thanks to ASP.NET Core dependency injection, there's no need to follow the Singleton pattern; any class will do. What I want to do is to have a class that will store a value that'll be used by another methods inside the app. A specific class is in charge of updating this value. What I'm concerned is the problem of a th...
I made a simple Hangman game in Python: import random class Hangman: def __init__(self): self.words = ["bike", "monkey", "planet"] self.random_word = random.choice(self.words) self.lenght = len(self.random_word) self.no_of_try = int(self.lenght) + 3 self.empty_word = ["_"]...
I'm new to python and curious if this is the most efficient way to read addresses from a SAP database, geocode them, read the results, and then write the information back to the database. Everything below works, I'm just curious if this would make an expert cry beginner bad, or acceptable code for my first try. :-) I'm...
The task is relatively simple and until now it was always performed by some poor admin soul. There is a large table that needs to be filtered based on a simple criteria and each view has to be saved as a new spreadsheet. The code is as simple as the task (and as my coding skills) so I would love to get some feedback a...
I have a problem with macro running too slow and I guess it is just because of lack of my knowledge. I have a macro that is copying data from "database" and paste it to another sheet. Macro is taking the names from the list in Sheet1 and looks for matches in Sheet2. When the match is found is copying a specific cell. R...
This code searches for the word "Disbursements" and copies all of the rows with data below it, including the row with the specified word. After the rows are copied to a new sheet, the unnecessary rows below the contiguous range of data are deleted. In order to search for the last cell, I used a function that finds the ...
I have written a game. Its a very simple clone of the Dwarf Fortress. The game seems to be working fine at least from my testing. I would like to improve my programming game and fix all the bad design, bad practices and possible performance bottlenecks in my code. So any comment that would help me become a better devel...
typedef const bool* const TypeID; template<typename> TypeID TypeIdOf() noexcept { static const bool idLoc(0); return &idLoc; } I'm using this function to return from some derived classes to differentiate them at runtime, by returning from this function, templated as the class. ie: class Object { ... ...
I am a beginner in FPGAs, and I am studying Verilog HDL. Could you please check the quality of my code (a shift register)? Any comments are welcome. The shift register serializes parallel from wr_data_i data to serial_data_o and has two variations of first serialized bit. It may be most significant bit or least signifi...
The Plain vanilla JS needs to converted in to advanced ECMA. The below 3 snippets shown yields the correct result. Need to identify which among them is performance oriented this.allUserDetails.forEach((el, indx) => { if (type === 0 && flagResumeAll === false) { if (el.extensionTime === time && el.userProcto...
The app when works fine, but people are saying that the code is not written with good code style and following OOP principles. Can I improve on any parts of my code? Especially regarding: Code comments Variable naming Separation of concerns Single responsibility principle etc. import javafx.application.Application; i...
For my game engine that I'm trying to write without using STL I implemented dynamic array class(some kind of std::vector). I would like to know whether this code suits best practices. I'm also not enough knowledged about move semantics and all that stuff, so please tell if I should add them somewhere in my code. My eng...
I tried to create a .Net core API using Microsoft Documentation but I ran into some issues. The app is working but only for a "single" table. The includes are empty. var contact = await _context.Contacts .Include(c => c.ContactSkills) .ThenInclude(cs => cs.Skill) .AsNoTra...
I have different function for different task below this function. To reduce the code, I have written following function. Is this the best way to apply OOPs? or any better way to do? Function def ML_algorithm(algo_name, y_train, y_test, y_pred_algoname, y_predtest_algoname): print(algo_name) print() err=mean_squar...
I've been searching for methods to convert a bitarray into integer. Now I'm using this code: def bin2int(bin_array): int_ = 0 for bit in bin_array: int_ = (int_ << 1) | bit return int_ where bin_array is a bitarray randomly filled. I'm curios about other methods that you know of, like functions fro...
Assume we are given a number and a prime p. The goal is to count all subnumbers of number that are divisible by p. A subnumber of number is formed of any number of consecutive digits in the decimal representation of number. Following answers to my first question about code to solve this problem, I improved my code as f...