instruction
stringlengths
71
95.1k
I have been working on this code to meet the best OOP standards for production. The code is working but I wish to make this a more efficient code. Could someone help me out here to make this efficient using best practices of ruby. class Item @@items = {} def initialize(name, price) @@items[name] = price end ...
I came across this question in a coding contest (Java-restricted) and I got TLE. I am unable to provide the link of the question as the contest is closed now. Can I know how can I optimise this? Four Functions Given four functions A(x) = Number of i where 1 <= i <= x and gcd(i,x) = 1 B(x) = Sum of A(d) where d divide...
Hello fellow programmers. I started learning C last week and today I wanted to see if I can make a working program, so I made this game: /* * TESTED IN LINUX - 2020 */ #include <stdio.h> #include <stdlib.h> int player = 1, choice; int places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; void switchPlaye...
folks. I have recently started writing software using Modern C++ 11-14. I have been developing software for more than a decade and just wanted to broaden my skillset. I am practicing building some simple design components using Modern C++. I dont have any friend or a colleague who knows c++ and noone can review my prac...
I am building the list of items (TEST) with loadMore button with filter and want to have loading state in LoadMore button and items itself. After loading the item I will fetch the detail of the first item for the first time and after that load the detail of the test. This code does not contain the fetching of the deta...
Back from a long C++ hiatus. I thought to implement mergesort from memory, using containers and not based on CLRS's pseudocode and arrays. The compiles and runs ok on the test cases. /* TODOs * Optimizations: * [1] Have Mergesort sort values in-place: leftVec and rightVec contains references * * Improvements: * ...
We have a new service where an admin can upload a spreadsheet of new users they want to add to our application. During our processing we make a union map of all the users both existing and new additions, and check to make sure that the users will still be in a valid tree structure(s) after the update goes through. Requ...
I've made a Discord Bot in Python that uses the Psycopg module to make calls to a PostgreSQL database in order to display information. https://github.com/Chombler/cardbot Specifically, I call this function when a user calls the bot: def pullCardRecord(recordName): success = True try: print("Trying") ...
What I wanted to do As part of a larger project, I needed a simple text editor with line numbers. The editor should also be able to highlight the current line (line number in bold) and define the tab size. The result looks like this: My solution After searching the internet for a while, I found out about the possibi...
I wrote a bash script to move certain files within a group of directories with filenames that match certain conditions to another group of directories, but it is very cluttered. If possible, I want some help and tips regarding optimizing it: #!/bin/bash #Asks for user confirmation echo "This will move all files in the...
ERROR: type should be string, got "https://github.com/CascadeIllusion/DesmOEIS\nRecently began work on a Python project called DesmOEIS to build up my portfolio. It's a simple console program that looks up integer sequences from the OEIS, parses them, and converts them into Desmos lists using the Desmos API.\nThe program works fine, I just want general feedback to make sure I'm doing things the right way (not just code-wise, but also in terms of project structuring). Unit tests succeeded on my end, but then again maybe I'm not building good unit tests.\nconsole.py\nimport sys\nimport webbrowser\nfrom parsing import *\nfrom desmos import *\nfrom sequence import Sequence\n\n\ndef main():\n\n intro = \\\n \"DesmOEIS\\n\" \\\n \"A tool for converting OEIS sequences to Desmos lists.\\n\" \\\n \"\\n\" \\\n \"Type id=<OEIS id> (without the brackets) to convert a sequence. \\n\" \\\n \"Type help for a list of all valid commands. \\n\" \\\n \"Type exit to close the application. \\n\" \\\n\n help = \\\n \"\\nSyntax: (Command Name)=(Argument)\\n\\n\" \\\n \"id: Attempts to convert an OEIS id argument into a Desmos list. \\n\" \\\n \"The \\\"A\\\" is optional, and trailing zeros may be excluded.\\n\\n\" \\\n \\\n \"name: Assigns the resulting Desmos list to a variable with the given name. \\n\" \\\n \"Names must be exactly one letter character (except \\\"e\\\"), no numbers or special characters.\\n\\n\" \\\n \\\n \"trim: Filters a list using Python-style slicing syntax. For A:B:C:\\n\" \\\n \"A is the starting index (inclusive), default 0.\\n\" \\\n \"B is the ending index (exclusive), default is the list length.\\n\" \\\n \"C is a step value that is used to skip every C elements, default is 1 (don't skip anything).\\n\\n\" \\\n \\\n \"ext: Pass Y to this to output the extended version of the OEIS sequence.\\n\" \\\n \"WARNING: Passing an entire extended sequence this way is usually not a good idea, as such\\n\" \\\n \"sequences can be hundreds of elements long, and can cause your browser to hang. You may want\\n\" \\\n \"to combine this with trimming syntax to reduce the number of elements.\\n\\n\" \\\n \\\n \"view: Opens the .html file containing the last converted sequence since starting the program. \\n\" \\\n \"Does not work if used before converting a sequence.\\n\\n\" \\\n \\\n \"help: View a list of all valid commands.\\n\\n\" \\\n \\\n \"exit: Closes the application.\" \\\n\n print(intro)\n\n file = None\n\n while True:\n cmd = input()\n\n if cmd == \"help\":\n print(help)\n continue\n\n if cmd == \"view\":\n if file is None:\n print(\"No sequence converted yet.\")\n continue\n webbrowser.open(f\"file://{os.path.realpath(file)}\")\n continue\n\n if cmd == \"exit\":\n sys.exit()\n\n # Multiple commands are comma separated\n cmds = cmd.split(', ')\n cmds[-1] = cmds[-1].replace(',', '')\n\n if not cmds[0].startswith(\"id\"):\n print(\"First argument must be id.\")\n continue\n\n args = dict()\n\n for i in cmds:\n i = i.split(\"=\")\n\n cmd = i[0]\n value = i[1]\n\n args[cmd] = value\n\n id = parse_id(args)\n\n results = find_id(id)\n\n if results:\n sequence = Sequence(id)\n sequence.args = args\n sequence.results = results\n else:\n print(\"Invalid id.\")\n continue\n\n sequence.integers = parse_integers(sequence)\n\n name = sequence.args.get(\"name\")\n\n if name:\n if len(name) > 1:\n print(\"Variable names must be one character only.\")\n continue\n\n if str.isdecimal(name) or name == 'e':\n print(\"Numeric names and the constant e (2.71828...) are not allowed.\")\n continue\n\n sequence.name = name\n\n file = create_expression(sequence, create_desmos_list)\n\n print(\"Sequence converted successfully! \\n\")\n\n\nif __name__ == '__main__':\n main()\n\nparsing.py\nimport requests\n\n\ndef parse_id(args):\n\n id = args.get(\"id\")\n\n # Remove the preceding A if included\n id = id.replace('A', '')\n\n # Add trailing zeros if necessary\n length = len(id)\n if length < 6:\n for i in range(0, 6 - length):\n id = \"0\" + id\n\n # Add A at the beginning of the query\n id = 'A' + id\n\n return id\n\n\ndef find_id(id):\n\n url = f\"https://oeis.org/search?q=id:{id}&fmt=text\"\n r = requests.get(url)\n\n if \"No results.\" in r.text:\n return None\n\n return r\n\n\ndef parse_integers(sequence):\n\n text = sequence.results.text\n\n text = str.splitlines(text)\n\n rows = []\n\n if sequence.args.get(\"ext\") == \"Y\":\n\n b_id = sequence.id.replace('A', 'b')\n url = f\"https://oeis.org/{sequence.id}/{b_id}.txt\"\n r = requests.get(url)\n sequence.results = r\n text = r.text\n text = str.splitlines(text)\n\n for line in text:\n space = line.find(\" \")\n row = line[space + 1:]\n row = row.split(', ')\n rows.append(row)\n\n else:\n\n for line in text:\n if line.startswith('%S') or line.startswith('%T') or line.startswith('%U'):\n # integers start 11 characters into the line\n row = line[11:]\n row = row.split(',')\n rows.append(row)\n\n rows = [row for integer in rows for row in integer]\n\n # Remove empty elements resulting from commas at the end of the %S and %T rows\n rows = list(filter(None, rows))\n\n trim = sequence.args.get(\"trim\")\n\n if trim:\n if \":\" not in trim:\n print(\"Trim argument missing colons ( : ).\")\n return\n trim = trim.split(\":\")\n if not (trim[0] is \"\" or trim[1] is \"\"):\n for i in trim:\n if i.isdigit() and trim[0] >= trim[1]:\n print(\"Start value must be less than the end value.\")\n return\n if trim[0] is \"\":\n trim[0] = '0'\n if trim[1] is \"\":\n trim[1] = len(rows)\n for i in trim:\n i = str(i)\n if not i.isdigit():\n print(\"Invalid input for trim argument.\")\n return\n trim = list(map(int, trim))\n start = trim[0]\n end = trim[1]\n if len(trim) == 3:\n if trim[2] is 0:\n print(\"Step value cannot be zero.\")\n return\n step = trim[2]\n rows = rows[start:end:step]\n else:\n rows = rows[start:end]\n\n return rows\n\ndesmos.py\nimport os\nfrom sequence import Sequence\n\ndef create_expression(sequence, func):\n\n graph = open(\"../resources/desmos_graph_base.html\")\n graph = graph.read()\n\n expr = func(sequence)\n\n # Add another placeholder comment below the expression to allow for further expressions\n graph = graph.replace(\"<!-- PLACEHOLDER -->\", f\"{expr} \\n <!-- PLACEHOLDER -->\")\n\n sequence.graph = graph\n\n dir = \"../graphs/\"\n if not os.path.exists(dir):\n os.makedirs(dir)\n filename = f\"{dir}{sequence.id}.html\"\n out_graph = open(filename, \"w\")\n out_graph.write(graph)\n\n return filename\n\n\ndef create_desmos_list(sequence):\n\n integers = sequence.integers\n\n desmos_list = str(integers)\n desmos_list = desmos_list.replace(\"'\", \"\")\n\n name = sequence.name\n\n if sequence.args.get(\"name\") is not None:\n name = name + \"=\"\n else:\n name = \"\"\n\n expr = f\"calculator.setExpression({{ id: 'graph1', latex:\\\"{name}{desmos_list}\\\" }});\"\n return expr\n\nsequence.py\nclass Sequence():\n\n def __init__(self, id):\n self._id = id\n\n @property\n def id(self):\n return self._id\n\n @property\n def args(self):\n return self._args\n\n @args.setter\n def args(self, args):\n self._args = args\n\n @property\n def integers(self):\n return self._integers\n\n @integers.setter\n def integers(self, integers):\n self._integers = integers\n\n @property\n def results(self):\n return self._results\n\n @results.setter\n def results(self, results):\n self._results = results\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\ntest_parsing.py\nimport unittest\nfrom parsing import *\nfrom sequence import *\n\n\"\"\"\n# Example sequences used:\nhttp://oeis.org/A000045\nhttp://oeis.org/A000047\nhttp://oeis.org/A139827\n\"\"\"\n\n\nclass TestIdParsing(unittest.TestCase):\n\n def test_parse_id(self):\n args = {\"id\": \"A000045\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_no_prefix(self):\n args = {\"id\": \"000045\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_no_trailing_zeros(self):\n args = {\"id\": \"A45\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_no_trailing_zeros_no_prefix(self):\n args = {\"id\": \"45\"}\n self.assertEqual(\"A000045\", parse_id(args))\n\n def test_parse_id_six_digit(self):\n args = {\"id\": \"A139827\"}\n self.assertEqual(\"A139827\", parse_id(args))\n\n def test_parse_id_six_digit_no_prefix(self):\n args = {\"id\": \"139827\"}\n self.assertEqual(\"A139827\", parse_id(args))\n\n\nclass TestIdFinding(unittest.TestCase):\n\n def test_find_id_success(self):\n id = \"A000045\"\n self.assertNotEqual(None, find_id(id))\n\n def test_find_id_fail(self):\n id = \"A123ABC\"\n self.assertEqual(None, find_id(id))\n\n\nclass TestIntegerParsing(unittest.TestCase):\n\n def test_parse_integers(self):\n\n args = {\"\": \"\"}\n\n id = \"A000045\"\n\n integers = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946,\n 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578,\n 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155]\n\n integers = list(map(str, integers))\n\n url = f\"https://oeis.org/search?q=id:{id}&fmt=text\"\n r = requests.get(url)\n\n sequence = Sequence(id)\n sequence.integers = integers\n sequence.results = r\n sequence.args = args\n\n self.assertEqual(integers, parse_integers(sequence))\n\n # Use a different sequence because most extended sequences are too big to reasonably fit\n def test_parse_integers_ext(self):\n\n args = {\"ext\": \"Y\"}\n\n id = \"A000047\"\n\n integers = [1, 2, 3, 5, 8, 15, 26, 48, 87, 161, 299, 563, 1066, 2030, 3885, 7464, 14384, 27779, 53782, 104359,\n 202838, 394860, 769777, 1502603, 2936519, 5744932, 11249805, 22048769, 43248623, 84894767,\n 166758141, 327770275, 644627310, 1268491353, 2497412741, 4919300031, 9694236886, 19112159929]\n integers = list(map(str, integers))\n\n url = f\"https://oeis.org/search?q=id:{id}&fmt=text\"\n r = requests.get(url)\n\n sequence = Sequence(id)\n sequence.integers = integers\n sequence.results = r\n sequence.args = args\n\n self.assertEqual(integers, parse_integers(sequence))\n\n\nif __name__ == '__main__':\n unittest.main()\n\n"
I made a simple console basketball game using Java. /* * Java Basketball * by Clint * 2020.07.08 | 3:59AM * This Java program let's the player play basketball in console. */ import java.util.Random; import java.util.Scanner; public class Basketball { static String[] shoot = {"1 POINT!", "2 POINTS!", "3 POI...
My main problems are making draw case and any player can choose a place which is chosen by another player here is the code : #include <iostream> using namespace std; char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}}; static int turnnumber = 1 ; bool winner = false, flag = false ; bool win(){ ...
I've spent some time on this as an answer elsewhere, and did my best to optimize it. But looking at the hill of indents seems like this can be improved. I've tried to implement an any() statement to replace the for break part, without any luck. Does anyone have any suggestions? Groups = [[['NM1', 'OP', '1', 'SMITH', 'J...
I need to log in users to web app in Javascript and PHP. So I have Javascript interface which send me accessToken to PHP which stores users data to DB and log user in. But the result code does not look like OOP but like a peace of garbage. May be I dont know how to write that code, so the question is if this peace of P...
I am new to programming and have been taking the time to learn C# by reading, doing some classes online for Unity, and using Youtube. I think you learn more from doing your own projects so I decided to write a program that asked the user to enter a movie they have not seen and then store the movie titles into a list an...
I'm beginning (for the third time in 5 years) to learn Haskell and decided to do a "More or less" console game (game pick a random number, you then have to guess which). First the code, then my question : import System.Random import Text.Read(readMaybe) main :: IO () main = do gen <- getStdGen let maxSecret = 1...
I searched on the internet for an algorithm for permutations in C and I found the following function: void permute(char *a, int l, int r) { int i; if (l == r) printf("%s\n", a); else { for (i = l; i <= r; i++) { swap((a + l), (a + i)); permute(a, l + 1, r)...
Any advice on how to make this code; cleaner, more effective, just overall better! Program creates a 'post' in the console. The post has a: message create on date score for 'upvotes' and 'downvotes' Users are able to upvote or downvote the post using upvote or downvote with a simple trim and to lower applied to the s...
Initially, this is not an attempt at early optimization, though it's thoroughly possible I'm looking in the wrong place :). The following function returns a height value for aliased columns in a kind of voxel-style height-map renderer. It is called many, many times for both AI and player controlled entities and used fo...
Given an integer , compute the minimum number of operations(+1, x2, x3) needed to obtain the number starting from the number 1. I did this using this code: #include<iostream> #include<algorithm> #include<vector> using namespace std; int main() { int n; cin >> n; vector<int> v(n+1, 0); v[1] = 1; f...
So i have a server which I send a Request to and it sends me back a list of rooms,Now i made a window for joining rooms and I'm trying to refresh it every 3 seconds but when i use the Timer thread to refresh the list it doesn't work if I use the normal refresh method with the Timer it works just fine. Here's some code:...
Is this a performant strategy to implement a stack in Kotlin to compare and delete values? Expect Create a stack in order to compare an array of asteroids (ASTs) and handle collisions (deletions), returning the final array of ASTs after collisions. Each AST moves at the same speed Negative numbers move left, positive ...
Since i develop in Java, i got into the habit of not putting hardcoded text in my code. For paths to files and folders I use the code below. I did it in a way that it was easy to set up and quick to understand, but i want to know if there are any solution more clean to do the same work ? A lib just for this ? So if you...
Hey I always used to create some pretty messy endpoints and I decided that it's about time to start writing cleaner code, I'll provide an example of how would I design an endpoint and I'll be thankful for any insights why is it good or bad practice to do it like this also I'd be more than happy if you provide your own...
The easiest way to explain this problem is to show these two test cases: assert solution('ABC') == ['A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC'] assert solution('ABCD') == ['A', 'B', 'C', 'D', 'AB', 'AC', 'AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'ACD', 'BCD', 'ABCD'] my solution is below: def subsolution(lst, length): re...
My attempt at creating a snake game, in pygame. I tried to make it as simple as possible, but i feel it could be better in terms of best practice, and efficiency, along the idea of avoiding redundant code. It would be appreciated, if anyone can give me advice in that regard. import pygame import time import random pyga...
I have a text data file in SPWLA format; I cannot find a specification for it. It contains physical measurements and/or rock descriptions from wellbore core samples. It's fairly gross. The example here is substantially simplified: text = """\ 30 1 2001.10 0.00 2.11 40 1 2 -1002.0000 34.5678 30...
this post is sort of a continuation of my answer on the following question: Fast Algorithm to Factorize All Numbers Up to a Given Number. As this post explains - We need to factorize all the numbers up to a large N. At first I gave a python solution which was pretty slow (since - you know, python), than I decided to wr...
I have an array with 40000 numbers that are floats or ints. I need to perform some calculation. To do this I have used nested for loop, but the code is really slow. Can I use something instead of nested the for loop? Is there any other way to reduce the execution time? When I changed to a list comprehension the executi...
I have a system with 2 different processes. Process 1 starts process 2 and sets up an AnonymousPipe between the 2. Process 1 needs to run some code and needs to interact with process 2 to get info and commit changes. Process 2 runs on Python with references to C# code (since I'm more familiar with C#) so process 2 has ...
The "game of 24" as I called it in the title is a maths game in which you are given four numbers and have to combine them in an expression using only the four basic arithmetic operations +, -, × and ÷ (and possibly using parenthesis) to achieve the final result of 24. You must use each digit exactly once. For example, ...
I'm coming from languages like Java and Python and I'm completely new to C++. Therefore, my knowledge is somewhat limited. My goal is to implement a listener in C++ myself and I came up with a solution using function pointers and lambdas. The design is different from other questions that I have seen on this site so I h...
I have a pandas dataframe (called base_mortality) with 1 column and n rows, which is of the following form: age | death_prob --------------------------- 60 | 0.005925 61 | 0.006656 62 | 0.007474 63 | 0.008387 64 | 0.009405 65 | 0.010539 66 | 0.01...
Basic idea (foo and foa are filenames): using System; using System.Collections.Generic; using System.IO; namespace FileIndexer { class FileIndexTrie { private class CachablePath { public string filename; public int cachedPath; //stolen from: https://stackov...
I am slowly creating a flow field pathfinding solution for Unity3D. I'm trying to follow Elijah Emerson's description, which appears in the book 'Game AI Pro' (volume 1). In this question I ask about the Coordinates object which I use here. I have subsequently cached some variables. In my tests, the stop watch has re...
Cross-Posted from Stack Overflow I am new to using condition_variables and unique_locks in C++. I am working on creating an event loop that polls two custom event-queues and a "boolean" (see integer acting as boolean), which can be acted upon by multiple sources. I have a demo (below) that appears to work, which I woul...
This is my very first interaction with databases. The goal is to setup a safe playground on an Arch box to create tables and make queries. I want to learn the basics without risking sudo rm -rf /. #!/usr/bin/env bash # This script initializes a new MariaDB database, # without root privileges, # and connects to it. #...
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time! Problem In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1. Some nodes initial are initially infected by malware. Whenever two nodes are di...
Any advice on how to make this code; cleaner, more effective, just overall better! Program setup object that is coming from the database. it loop the object adding to the viewmodel object. Then the object has a certain properties base on type. The config type will only have the setting and value objects. class Program ...
I followed the SLAP principle in the below code. But with "Mixing Level Of Abstraction" (refer below code) I can avoid the single line methods. My question is - is it good to avoid the single line method in this case? But I believe the code with "SLAP Principle" has better readability than the other one. Please share y...
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time! Problem Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy all of the following rules: Each of the digits 1-9 must occur exactly once in each row. Each of the di...
I have a json file - WorkflowNames.json with contents as - ["ImportOrder", "ValidateOrder", "ProcessOrder", "ArchiveOrder"] My C# code to read this json file is - private Dictionary<string, bool> GetWorkflowNames() { var appDataFolder = ConfigurationMgr.GetAppPath("App_Data"); var jsonFilePath = Path.Combine(appDa...
Hello i'm coding a social site and I need to know how clean this code is. I read other answers people told me from my previous questions like this and used it as guidelines. So now I wanna know if anything could be improved. Thank you. <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); error_reporting(-...
I am a beginner in Python and I have attempted to create a small script/program which allows the user to do the following: Generate a single random password Generate a number of passwords specified by the user of a certain length specified by the user to a text file in a location of their choice Test the strength of...
I am learning to use parameters and arguments in Java to make my coding efficient. I am open to suggestion if I've done something wrong with this code of mine. import java.util.Scanner; public class paramsAndArgs { static String name, feeling; public static void main(String[] args) { doesSomething(na...
Since memmem() isn't cross-platform, I'm trying to rewrite it from scratch. How does this look? #define MemContainsStr(Str, StrLen, Substr) MemContainsMem(Str, StrLen, SubStr, sizeof(SubStr)) void *MemContainsMem(const void *StrStart, register unsigned long StrLen, const char *Substr, register const unsigned char Subst...
I am working with an API of coupons from sites like Groupon. There are 2 fields in the JSON response (url and imgUrl) that return a url which directs them to the actual coupon and a picture of the business, respectively. Problem is that they contain sensitive information (my API KEY). Below is my service (using spring ...
I'm fairly new to Java and I'd like to know if there's any way to improve or refactor the prompt on validating integer values for best practices. import java.util.Scanner; public class Triangle { public static void main(String[] args) { int a, b, c; Scanner in = new Scanner(System.in); // Prompt for a Syst...
I have rewritten my little chat application and tried to pay attention to former hints and tips. The viewer and the writer have to run as seperate applications. the Writer.class basically stores messages as property files. The directory, where the files get stored, is watched by the Viewer.class and gets scanned every ...
Good morning, I've made the loop for the range, which is copied from one sheet to another. However I have no solution for trimming my code down, which looks like this: Sub sunrise() Dim i As Single With Worksheets("7") .UsedRange.Clear .Range("a1").Value = "Latitude" .Range("b1").Value = "-18" .Range("c1").Val...
Hello I've started learning javascript and today made my first calculator I would like to hear any suggestions how could I did it better and good coding practices. // Inputs fields used in program let elements = document.getElementsByClassName("buttons"); let screen = document.getElementById('output'); let history = ...
I have a pandas dataframe, df1: id level val 1 l1 0.2 1 l2 0.1 and another dataframe which contains type for l1 level, df2: id type 1 A Similarly, df3 which contains type for l2 level as well as new ids: id new_id type 1 19 A 1 19 B 1 20 A 1 20 B Now I want type for l1 ...
I implemented Quicksort in JavaScript. I'm trying to follow the best principles in JavaScript. In Ruby when you declare classes your able to use private for the methods that are private. I don't think there is anything like that in JavaScript. class QuickSort { sort(a) { a = this.shuffle(a); //Shuffling is neede...
I have this JSON code that I got from a get request with Azure API. Everything works how I want it but it doesn't look good. There must be an easier way to parse the data. import json #GET REQUEST code here, it works now the code below is grabbing the result and loading it. formatted_response = {'cost': 0, 'timespan': ...
My abstract class. Product will have multiple child classes those will be different types of Product public abstract class Product { private int productId; public int ProductId { get { return pro...
I've started working on a text-based adventure game that has procedurally-generated levels. I am unfamiliar with the more popular methods so I just decided to generate the dungeon using a recursive method. However, my code looks quite amateur-ish with all the if statements and I am unsure of whether or not it could run...
For a personal project (reading media file metadata) I created a small/fast utility class for working with RIFF chunks. Support: defining chunks by 32 bit integral value defining chunks using 4 ASCII characters splitting chunks into 2 16 bit integral values (useful for parsing RIFF headers) comparing chunks for equali...
win_xept.hpp - a basic windows api exception #include "../utl_macro.hpp" namespace xept { using win_t = struct utl_exception // utl_exception randomly generates a name // this hides exception names from rtti { DWORD e = GetLastError( ); }; } ramfile.hpp - an ...
I was trying to solve one programming challenge : First input is a list of connections which is made of pair of IPv4 address. Each IP has its own state which starts with false, each connection also has state which is made up by logical AND of state of its IPs Second input is a toggle IPs list , these toggles the stat...
I wrote a class for some MongoDB operations. So far I'm self-taught and mostly I follow the style from already existing code at my workplace (a startup). We don't have a code-review culture, so I'm pretty new to the process, but I'm open fortips for everything from code optimization, better logging, better documentatio...
I have written a function to multiply two numpy arrays. def ra(self): """Multiply Rotation with initial Values""" rva = self.r_array() * self.va_array() rva = np.sum(rva, axis=1) # Sum rows of Matrix rva = np.array([[rva[0]], # Transpose Matrix [rva[1]], [rva[2]...
I feel like there's something wrong with the way my code is styled but I can't quite place what's wrong with it. Perhaps the way I've represented the snake is a little convoluted? const HEIGHT = 20; const WIDTH = 20; const snake = function() { const snakeCoordinates = [[0, 0], [1, 0]]; const moveDirections = [...
I wrote a simple FIFO based on pieces of code I found online. It's intended for embedded systems with very restricted RAM. It's supposed to be very simple and efficient. The size is always power of 2 (8, 16, 32, 64, 128 etc). fifo.h #ifndef FIFO_H #define FIFO_H struct fifo { volatile uint8...
using System; using System.IO; class Solution { static void Main(String[] args) { int t = Int32.Parse(Console.ReadLine()); for(int a = 0; a < t; a++){ int currentNumber = Int32.Parse(Console.ReadLine()); int allSum = 0; for(int i = 3;i<currentNumber;i+=3)**Calculate sum of 3** {...
I'm making an API call in my parent component in React. I'm making a weather app, and theres two different endpoints I'm getting data from. I'm getting 5 day forecast, and the current weather data. I have two separate functions for the API calls, and I then call them functions in the componentDidMount function. I'm usi...
For my second week of learning C, I decided to remake the Tic Tac Toe game I made last week, but in a different style (as some of you recommended me). This is my final product on the whole Tic Tac Toe game idea, so I tried my best. I feel like it is a bit overkill, but I want to know your opinion. Here is the code: /* ...
I inherited a Xamarin project and I'm trying to find my way. The first task I completed involved creating a new reusable view and adding it to an existing screen. This was iOS specific, so I went and created a new .xib file to add in the relevant storyboard. I had some trouble figuring out how to attach the outlets cor...
I am trying to learn Haskell and figured I would kill two birds with one stone and also learn about data compression. My ultimate goal is to implement the DEFLATE compression algorithm in Haskell. To start I have implemented lz77. import Data.List import Data.Maybe import System.IO import ...
Please take a review of my simple bit manipulator: #ifndef BIT_STREAM_H #define BIT_STREAM_H #include <cstdint> class BitStream { public: explicit BitStream(uint8_t* buffer, size_t buffer_size) : m_Buffer(buffer), m_BufferSize(buffer_size) { } virtual ~BitStream() = default; public: inline uint64_t...
I am using the function below to change the environment. If it sees the wrong environment values, it clicks on it and it changes the environment. In this function, I am just using if and else statement. Is this a good code practice? This does the job however it does not seem clean. class SettingsPage extends Page { ch...
This is my /forums page <div class="card-body"> <h5 class="card-title">2019/2020 Premier League Forum</h5> <a href="/Leagues/EnglishDivision/PremierLeague" class="btn btn-primary">View</a> </div> For the above code you can see the href pointing to a directory to premierLeague.hbs. This is how my file structure loo...
Hello all I have a short question. Is this a good and secure way to connect to my DB ? session_start(); $servername = "localhost"; $un = "username"; $password = "password"; $dbname = "project"; $timezone = date_default_timezone_set("America/New_York"); // Create connection $con = mysqli_connect($servername, $un, $pa...
Background The platform I'm coding for is an esoteric scripting engine coded some time ago that only has limited capabilities. Because I cannot produce a version of the engine that can be run on its own (it needs to attach to a running instance of a game), I have translated the code into C# with limitations to mimic th...
I'm trying to come up with a function to convert byte arrays to their integer representation, using both endianness, and with a signed/unsigned option. enum class ByteOrder { LITTLE, BIG } fun ByteArray.toInt(byteOrder: ByteOrder = LITTLE, signed: Boolean = true): Int { if (isEmpty()) { throw Unsup...
I have the same array set up as a variable inside of each function - I want to make this easier to manage. The array contains multiple strings of values. I’ve attached code below that I've been working on. I would like to save this array to PropertiesService making it persistent across all executions. I already tried m...
I need to extract unique Product Group names along with its corresponding services from a table in a worksheet. The table is generated by a bot and is not filtered, I have sorted it by alphabetical order. The data is not fixed and can contain anywhere from 5 - 100 rows of data, depending on the month which the report f...
NOTE: This post was moved from stackoverflow as codereview.stackexchange is a better place to discuss the performance of this code problem/solution. I want to split an array into n subarrays. I don't care how many elements end up in each array but the elements must be spread through all the available sub arrays. e.g: S...
I wrote a memory management class that is supposed to be used in a game. I decided to use "Blocks" as an in-code representation. It is written in MSVC++ and is currently not meant for portability. I am actually not really experienced in C++ - I just wanted to "try it out". The pool is not meant to grow - it is initiali...
I just started coding c# 4 days ago. I just finsihed my first ever Console Program. I would like to hear some suggestions, on how I could improve my code. I would also like to add that this is my first programming language, so I'm still very new to coding. Also, the namespace says FourFunctionCalcProgram, but the calcu...
Basically you've got a canvas, and you can click it to launch a ball in a certain angle and speed, everything is working fine, except for the arrow tip of the vector thing. I can't get it to draw correctly. Sometimes it can't detect collisions. It seems to happen when the ball has a really high speed. I managed to solv...
I am trying to create a Binary Search Tree, which has STL support (iterators etc.). This is my first attempt. Everything is unit tested using Catch2. Could you please review what I missed and what I could do better? This is not homework, I am trying to create a repository with unit tested C++ algorithms at https://gitl...
Inspired by the following leet-code Suppose you are given the following code: class FooBar { public void foo() { for (int i = 0; i < n; i++) { print("foo"); } } public void bar() { for (int i = 0; i < n; i++) { print("bar"); } } } The same instance of FooBar will be passed to two ...
Having the following array of objects of ingredients used by cooks images = [{id:1, cook:"jim", ingredients:"chicken salsa mayo ketchup tomato"}, {id:2, cook:"steve", ingredients:"pasta mozzarela chicken"}, {id:3, cook:"jim", ingredients:"bread lettuce tomato onions"}, {id:4, cook:"jim...
This is GildedRose refactoring kata. Can this code be written to be more readable, and maintainable? class GildedRose: def __init__(self, items): self.items = items can I improve this part of code? @staticmethod def update_min_max_quality(item): """Updates min and max values of items""" ...
I've been working on my first real "project" and decided to make the periodic table that can simulate each atom after you press on it. I'm unsure if the code is good and can be used on my resume and therefore need your help :) Please tell me anything I can improve on regarding the code and also if it reflects good know...
import java.util.StringTokenizer; public class HTMLChecker { private String text; private String[] tags; private int tagNum; private ArrayStack<String> stack; public HTMLChecker (String input) { tags = new String[5]; text = input; stack = new ArrayStack<String>(); ...
I have this piece of code in my service layer and registers and student for a course. As you can see if have alot of if statements and i was wondering if any could suggest a nicer way of writing this code? public async Task<bool> RegisterStudentForCourseAsync(RegisterStudentForCourseRequest registerStudent) { ...
Any tips or review points are appreciated, I'm not much familiar with server-side web-dev (PHP) and DB. Few things of note: I see no reason to separate codebase into different files and bother with imports - provided code is ALL the project and some paradigm boilerplate approach makes no sense. Also saves few disk rea...
I wonder if there is a better approach to validate the object fields. For specific types of objects some fields cannot be empty: public class CredentialsValidator { public boolean validateCredentialsRequest(ValidationCredentialsRequest credentialsRequest) { switch (credentialsRequest.getCredentialType()) { ...
I was wondering if we could speed-up lookup in a hash table of strings by only storing the difference between them, like HAMT. Taking this idea to its end, I ended up with a binary PATRICiA prefix-tree data-structure. There is an example of pretty much what I'm doing in the section on PATRICiA trees in Crochemore, Lecr...
I created a python class called Score, I intend to use it to assign scores depending on 2 parameters, first the type of score - score name and second the user_input, so for example if I want to get the score of loan term, I will enter 'loan_term' as the first parameter and loan term value 36 as the second parameter; a ...
See the first block of code. here i am doing cross join between a ** list and datatable** from where i am calling a function called ExtractStandardValueFromLinkText this function has many loop which take times to complete. tell me how could i refactor the code in 2nd block to speed up the execution. all element start w...
I have built a super simple tip calculator to help me try and get a hold of the javascript knowledge I've gained. I just wanted to see if there was any feedback I could get for it... Basic functionality is: If a letter or incorrect character is input in either the bill or the number of persons input, a message should a...
I would like your opinion of my PowerShell script for file deletion. Do I follow conventions, do I use some anti patterns? Every critique is welcome! This is an example of a report log: This is the Settings.cfg file for script parameterization: WRITE_OUTPUT=true SEND_REPORT=true SMTP=smtp.mail.com PORT=25 RECEIVER=sys...
CRITICAL = 0 MEDIUM = 1 LOW = 0 test = { "version": "0", "id": "85fc3613-e913-7fc4-a80c-a3753e4aa9ae", "detail-type": "ECR Image Scan", "source": "aws.ecr", "account": "123456789012", "time": "2019-10-29T02:36:48Z", "region": "us-east-1", "resources": [ "arn:aws:ecr:us...
I am new to ML and I wanted to implement a Linear Regression to predict a golfer's scores based on certain feature supplied to my model. I would like a review to see if I'm implementing this correctly and any tips to make my model more efficient. Here is my code import pandas as pd import numpy as np from sklearn.linea...
I'm diving into front-end stuff for the first time. I thought a good way to get started was to try to do a mockup of a website. I took the top part of Microsoft's home page. Here's a link to the codepen. Full code at the end of the question as well. Not a full/exact replica. Would need much more time for me. Used HTML...
Any comment on my code? Data model public class LoanRepaymentPlan { public decimal TotalRepaymentAmount { get; private set; } public decimal CurrentOutstandingAmount { get; private set; } public decimal MonthlyRepaymentInterestAmount { get; private set; } public decimal MonthlyRepaymentAmount { get; pri...
I am accepting dynamic input from the user if they have any i.e - Children/Siblings/Previous Employement etc through Vue Components. A form is created and they input their data which is validated and then submitted. Submitted data is displayed in another Vue table component from which they can delete data if needed. Th...