instruction
stringlengths
71
95.1k
I have very large method who insert child of TreeView, basically I do two different querys and set little changes I.E. firs foreach insert first child of parent and the second foreach insert child of child created before. Foreach query just change conditional AND [ParentDesignKey] IS NULL, but inside it variables are...
This was written for a coding challenge for a company I recently starting working for. I'm looking for any suggestions on how to clean up the code, as well as any issues anyone thinks may occur as it is written now. Fairly new to React.js, always looking to improve. Currently the data is passed through the app componen...
I am coming to a problem where I am writing a function that accepts a pointer to a C-string as its argument. The function should count the number of vowels appearing in the string and return that number. Then, I am writing another function that accepts a pointer to a C-string as its argument. This function should coun...
Some JavaScript libraries relies on window innerWidth and innerHeight to do their calculations window.innerWidth is not 100% reliable, which may lead to bugs matchMedia().matches is 100% accurate but it returns a boolean value come around: use matchMedia to verify window.innerWidth value; if it returns false use match...
My goal is to move a 'monster' (mX, mY) in a 2d grid towards the player (pX, pY). The monster can move 8 directions. I have working code for this, but I'm very new to Python and have a strong inclination it is awful and there is faster ways to do it. I do this by creating a 3 x 3 array around the monsters position (arr...
I've been working on this one for a while. Took me a while to figure out all the logic rules for dates and months. The goal of this method is to return the number of years, months, days, hours, minutes, seconds, and milliseconds between two times. I'm going to be implementing this algorithm in a Xamarin app I'm making...
I have written a python script using regex to extrapolate a poorly formatted text file data table into an actual data table. I am currently printing the output using . C:\my file location\file.csv in the command prompt. Is there a better way to cause my script to run for an entire directory of files and programmaticall...
Context: I'm currently toying with the Google Geocode API to break down address strings into a more machine-friendly format. The problem is that neither the user input or API output are 100% consistent, and I would receive less entries in the JSON response than expected. For example, requesting "Times Square NY" gives ...
I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize! import hashlib import mysql.connector from tk...
I have encountered to this question and applied a brute force algorithm off top of my head and couldn't find a better optimized solution. I was hoping I could get some insight to implement a better optimized code in terms of complexity. My solution has \$O(n^2)\$ time and space complexity. class Solution: def long...
I'm a beginner in programming and I would like to have feedback and tips to improve. He's a simple command line program. It's a Rock, Paper, Scissors game. I guess I could use an enum for the "Attack", but I don't know how to use it with cout after that... Thanks! #include <iostream> #include <string> #include <cstdlib...
Given the following definitions of Functor and Coproduct from fp-course: class Functor f where (<$>) :: (a -> b) -> f a -> f b class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b class Functor t => Traversable t where traverse :: Applicati...
I have found similar posts which has some optimizations on Winning-checking logic: React Tic Tac Toe My primary focus for this post is about hook setters being asynchronous. So to check if anyone wins, I used useEffect to listen to the board. useEffect( () => { if (winning()) { setMessage(`Player $...
This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, ...
I'm developing a webpage displaying the scheduled pipelines from all projects of a GitLab instance. The scheduled time is expressed using CRON expressions, i.e. five digits as follows: Because not all future users of my webpage are familiar with CRON expressions, I wrote a script for translating it into a human-readab...
I was doing an exercise in PHP, and it works perfectly, no problems. But I think that maybe I coded it so long, and I think it can be shorter than it is now, but I don't know how to make it shorter and that works exactly the same way. I will explain what this code is doing for you so it's faster if you are going to hel...
I have a dictionary: x = {'[a]':'(1234)', '[b]':'(2345)', '[c]':'(xyzad)'} and a dataframe df = pd.DataFrame({'q':['hey this is [a]', 'why dont you [b]', 'clas is [c]']}) I want to append the values from dictionary to the corresponding keys. My expected output is: q ...
My team has been given care of an old embedded C project. Its main part is a security critical RPC API and I'm trying to create a new design of its internal interfaces to make it more robust against the inevitable bugs. My main goals are: Make it easy to write memory safe code (no buffer overflows, information disclos...
Given a 2-D input matrix, I need to pick elements from it. constraint: you can pick one number at each row, each column given: number boards are given expected output: print least sum of numbers what you took! I think I found a firm framework like method for DPS in python. But I want this to be confirmed, please comm...
So I made a bruteforce program for sha-X hashes and MD5 using wordlists in Python. I know Python is probably one of the worst languages for this, but it's only for learning purposes. I think this was a good way for me to learn optimization. I am still a beginner in coding, so my code might have some things that aren't ...
From leet code question: https://leetcode.com/problems/lru-cache/ Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. pu...
Here is my implementation of Conway's Game of Life in C++ which takes advantage of multi-threading. I'm using SFML 2.5.1 for a graphics library and CMake. I also use SFML's Vector classes for convenience. Right now the game runs in a fixed sized grid world and the update() function that applies the game rules splits th...
This is a rework of a small program for faster(?) switching working directories, and it looks like a pile of crap, I must admit. Could you give me pointers how to make it maintainable? dt_tag_entry.hpp #ifndef NET_CODERODDE_DT2_TAG_ENTRY_HPP #define NET_CODERODDE_DT2_TAG_ENTRY_HPP #include <string> namespace net { na...
I'm quite new to C++ and want to focus on writing performant multithreaded code because I will try to port our company internal GUI framework which is currently implemented in C#. So I'd love to get some recommendations about code style and Performance on a reader-writer spin lock that favors writers I wrote: namespace...
Context: I'm making a Codepen-like app but I want it to support sophisticated JS libraries/frameworks like Vue or Angular 2+ for example. I want to have a live preview of my snippet which updates in a reasonable time. So I came up with an idea that when I create a new snippet I'll initialize a blank starter project on ...
I created a class which creates chained translations (for example, Japanese translated to English, then back to Japanese, then to English). Some concerns: Is my usage of recursion good? Is the class pythonic? Is there anything else to make it more pythonic? I used instantiated Translator twice in my code. Is there any...
The code's structure has been changed to make the program more readable. I've also commented and split up the program into blocks for better readability as well. The recursion in the player and computer moves have been replaced with a loop instead. The user can now determine the first player. The algorithm to determine...
This is a project I came up just as an exercise with to familiarize myself with Python syntax and data types. I am just learning how to code and would like to avoid establishing bad habits. On the other hand, I wanted this program to function so when I found something that worked, I left it as is, even if I suspected t...
As the title says, I'm trying to implement a merge sort algorithm in C++ that's also adaptive. This is a personal exercise, and I don't have any specific application in mind. My main goal is to write something that's succinct and easy to understand but also has reasonably good performance. I'm aware that implementati...
Looking over Rock, Paper, Scissors. C++ from a beginning programmer prompted me to think about how I'd program this simple game in C++. The RockPaperScissors class contains the essential features of printing and evaluating each round of the game, as well as generation of randomly selected moves. I didn't encode a pla...
I'm new at PowerShell and I like it. I had the change to write a script that uninstall Erlang and RabbitMQ and I want the same script to then remove the Erlang folder and the RabbitMQ folder. But in order to do so I need the script to respect the tasks order. My way out was to use Write-Verbose (line 13) so the scri...
I'm learning C# and currently having an assignment on Tic Tac Toe. I'd love to have some feedback on where I can improve. I've managed to create the end game functions but I feel it could be improved. I'm just not sure how to do it and was hoping someone here could help me. I hope the information I've provided is enou...
This is the bash script responsible for changing the directories via textual tags. (See here the entire project.) dt_script ~/.dt/dt $@ > ~/.dt/dt_tmp COMMAND_TYPE=$(head -n 1 ~/.dt/dt_tmp) if [ $# -eq 0 ]; then NEXT_PATH=$(~/.dt/dt prev | tail -n 1) # Let dt return pwd if no prev tag. ~/.dt/dt --update-prev $(...
In the below GameOutcome class I'm checking for wins/ties in Tic Tac Toe. I'm pretty set on breaking the checks into 5 different functions because I'm specifically practicing making functions short and single-purposed. But I'm not at all set on my 5 if statements in the find_winner_or_tie method. Does somebody know a m...
i'm trying to make a French timetable in Python, but there's too many if and elif. class Teacher: def __init__(self, name, room): self.room = room self.name = nam def __str__(self): return '{}: {}'.format(self.name, self.room) class Day: def __init__(self, name, week, lessons): ...
I did another exercise, this time it simulates n games of craps(dice game) and outputs the wins and win percentage! #craps.py -- Simulates multiple games of craps # and estimates the probability that the player wins. import random def output(wins, total): winrate = wins / total print("The player won {0} of ...
I have coded multiple variations on this and would like to make it generic, to avoid coding any more variations. Comments and suggested improvements, please, (typos also), and what about that ToDo ? I often want to parse a text file and split it into chunks, generally those lines between two lines containing known keyw...
I have been given a list of simple Customer objects to work with. This would be an example of a customer list: customers = [ Customer(active=True, age=38, gender='F'), Customer(active=False, age=18, gender='M'), None, Customer(active=False, gender='F'), None, Customer(age=64), Customer(activ...
I am working on a utility function to get the current date and time. My objective is to do this in a generic and portable way. I would like to stay way from platform specific code to allow the functionally of this method to be portable. I had originally asked a question over at Stack Overflow followed up by another que...
qsquarelayout.h #ifndef QSQUARELAYOUT_H #define QSQUARELAYOUT_H #include <QLayout> #include <QLayoutItem> class QVSquareLayout : public QLayout { Q_OBJECT public: QVSquareLayout(QWidget* parent=nullptr); ~QVSquareLayout(); // QLayoutItem interface public: virtual QSize sizeHint() const; virtual v...
Preface At some point I was tired of writing & supporting __repr__ methods, so I've decided to write it once and reuse everywhere in my classes. Since I'm trying to write classes as simple as possible, most of them ends in something like class MyClass: def __init__(self, param, other_param, ...): self.par...
This is a C++17 is_integral trait implementation. Most implementations exhaust all integral types: bool char, char16_t, char32_t, wchar_t [unsigned] short [unsigned] [long [long]] int However, it is possible that the implementation defines some extended signed integer types and extended unsigned integer types. One w...
For the moment I'm executing my code as follows: foreach (int data in dataList) { PreProcess(data); } foreach (int data in dataList) { Process(data); } First I have to loop over some data (from a list) and to do some pre-processing after which then I do have to loop again over the same data list and do some pr...
I was playing arround with some CSS and ended up in making some 3D hover icons with font awesome. I wanted to ask for some feedback on my CSS: Best-practices, any other comments, maybe bad things that you should not do... article { position: relative; left: 50%; transform: translateX(-50%); min-height: 100%; } a...
I wrote a function to implement a generalised version of binary search that can find the minimum or maximum index in a given sorted list that satisfies a provided predicate. My Code def xbinsearch(pred, lst, type = "min", default = None): """ * Finds the minimum or maximum index of a sorted list such t...
I implemented a console version of the classic snake game. I wanted it to be portable but some of the functions like setting console position and _kbhit weren't available on Non-Windows operating systems, thus as is, this code is Windows only but I tried to isolate the non-portable parts in controls.h. I would especial...
This quiz is on The Rust Programming Language online ebook. Given a list of integers, use a vector and return the mean (the average value), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list. As a novice Rust programmer, I'd...
I've been working for few days to develop a basic Java Swing Calculator that could Add, Subtract, Multiply or Divide two numbers and also has other options like inverse(1/x) and square root I would like you to analyze my code that it follows basic OOPS concepts like Abstraction, Encapsulation, Polymorphism etc. impor...
So I am learning hooks and context, and I wanted to make a simple router. I wanted a simple API where you can just pass in routes. initialRoute should be optional, and it should pick it up from the pathname, otherwise it defaults to the first route. I want to expand it to be able to work when server side rendering, sin...
I use ImageMagick to crop image, encapsulate the related code to functions. Here is the code: convertc2(){ convert $1 -crop $2 "two.png" } converto3(){ Delimeter="placeHolder" if [[ $2 == *"x"* ]]; then Delimeter="x" else Delimeter="X" fi First="${2%$Delimeter*}" Fourth="${2##*+}" Lhs="${2...
I'm looking at implementing the basic functional not-quite-Eratosthenes prime stream in Rust. I like to try it when I start learning a language. Here's the bog standard Haskell version: primes :: [Integer] primes = sieve (2 : [3, 5..]) where sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p /= 0] in Rust, I think ...
I'm working on requirement that involves creating a N x N table of blocks, with each block having a weight. Consider the following classes Block - The fundamental unit of the table, having a weight RowBlock - A set of blocks that join together one row BlockTable - A set of rows that join together to form the table Th...
Function getMarkets Makes a call to get Cryptocurrency Exchange data based on asset (USD, USDC, USDT) It calls the endpoint 3 times to return 3 arrays which are then returned to the callee. I have an endpoint which hits gets exchange-markets/prices for any asset. In my case I need to check all the paired cryptocurr...
Help me with code code review. Helium is my pet project, written in Golang. Helium is a small, simple, modular constructor with some pre-built components. https://github.com/im-kulikov/helium Simple example how to use it package main import ( "context" "github.com/davecgh/go-spew/spew" "github.com/im-kul...
I am developing a simple taskbar for X11 using the Athena widgets. The current code is very limited: it assumes an EWMH-compliant window manager and only adds the initially running windows to the taskbar. Here is a screenshot: The program depends on the libX11, libXt and libXaw development packages. It can be compiled...
I'd like to create directories on a remote VM, but only if they do not exist. What's more, if creating the directory results in an error (exit status != 0) I'd like the script to exit as well, or at least print an error. Is there a more succinct way to do this than what I have below? UPDATE: Just to clarify, I want to...
The official Rust book chapter 13.1 includes an exercise to expand on the example provided in the chapter: Try modifying Cacher to hold a hash map rather than a single value. The keys of the hash map will be the arg values that are passed in, and the values of the hash map will be the result of calling the closure on ...
I'm currently tasked with using recursion to find pairs that add up to a given sum. How would I make the function recursiveFixedSumPairs function more efficient and truncate this code? Also, what is the current runtime? I believe it is n since it will go through the array only once always starting at the first index. p...
I got this question during my practice interview. Matrices - N Spiral Matrix Prompt Given an integer N, output an N x N spiral matrix with integers 1 through N. Examples: Input: 3 Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]] Input: 1 Output: [[1]] My solution is below: function spiralMatrix(n) { c...
I made a program to read the source code from a url. To reach this url I need to specify a token. After read the source code, I extract a url in json format, andIi redirect my domain to this url. It's not relevant to what I'm asking, but I want explain what I'm doing. As you can see, on my domain http://localhost/test,...
I'm creating an Angular widget which combines a dropdown with a custom input. I've made it generic and am preparing a blogpost explaining my setup, and would love to get a review before I do so. The most basic usage of this component would look like this: <select-with-custom-input baseOptions="['one', 'two', 'three']...
I'm building a procedure which compares two JSON objects and return two JSON objects with differences between each (compared keys and values). But I have relatively superficial SQL knowledge, so I need your review to avoid any simple mistakes and improve my code. Compares "first" against "second" and returns the values...
I just figured out how to do a building menu with a progression feature in c++ console application. What this code does: It simply offers you a choice to build a building and then prints the progression like: 1% - 9% erasing and printing one number at a time (Which is the kind of the core feature that I struggled a lo...
I have a server where shell commands to the supervisor-service must be executed by the specific user lx. I have written a bash function that does exactly that. function supervisor { if [ `id -nu` != lx ]; then sudo su - lx -c "supervisor \"\$@\"" -- supervisor "$@" else sh -s "$@" <<EOF supervisor "$@" EOF fi }...
I've made a simple website from scratch using HTML and CSS, for practice purposes only. I got the website to look the way I want but I would appreciate some feedback on the code, especially the CSS feels quite hacky to me. The HTML file index.html <!DOCTYPE html> <html> <head> <!-- Global site tag (gtag.js) - Googl...
Codewars Kata: Given integers a and b, count all primes p where a ≤ p < b and the digits of p are all prime. b may be as large as 107. To start with, I hardcoded all valid 1903 primes in \$[1, 10^7]\$ that can be formed from digits \$\{2, 3, 5, 7\}\$ and stored it in a list. Then I use binary search to locate the index...
(See the next follow-up here.) Problem definition Given \$X = (x_1, \dots, x_n)\$ such that \$x_1 \leq x_2 \leq \dots \leq x_n \$. Let \$x_{\min} = \min X = x_1\$, \$x_{\max} = \max X = x_n\$ and \$r = x_{\max} - x_{\min}\$. Also, let \$m = n - 1\$. Finally, $$ \ell = \frac{r}{m} $$ is the average gap length. The clust...
I need to be able to create an Excel document with multiple tabs for a dataset with multiple results\data tables. I have a stored procedure with 3 selects in them, fairly simple ones pulling data from the sys tables in SQL Server. Below is my script where I am assuming there will be 5 tables, if there are more then it ...
This Python script extracts data from txt files containing raw numerical data, notably the increase average, the relative evolution and the standard deviation of the values. All of these values require a period on which they are calculated. This period is set via the command line. #! /usr/bin/env python3 import stat...
With HTML5 you can add captions to your video using the <track /> element. However, only vtt files are officialy supported, while the current most populair subtitle format is the well known srt format. So instead of converting all the srt files to vtt files, I had the idea of writing a script which will do all of this ...
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. class DailyCodingPro...
Context For one of my projects I have to use a library which works similarly to the following code : enum LibEntry { Int1, Char1, Float1, Int2, Char2, Float2 }; union ValueUnion { int i; float f; char c; }; class Object {}; void getValue(Object*, LibEntry entry, ValueUnion* val) { //Real code...
Edit: The goal of this Question was only seeking code review and guidance in learning or tips for improvement. I apologize if that was not clear or aligned properly with the goals of this forum. Script Goal: audit file existence and differences between two red hat Enterprise Linux Servers Place information in sql s...
Code first, elaboration later: // Fizzbuzz: 1..100, %3->fizz, %5->buzz, %15->fizzbuzz // noif: do not use if/switch statements or ternary expressions // LIMIT must be a power of 10 // WIDTH must be equal to log10(LIMIT) #include <stdio.h> #include <string.h> #define LIMIT 100 #define WIDTH 2 char * itoa(int n) { ...
I've created a personal API for creating elements for an HTML page. I would like feedback on efficiency, particularly in creating buttons and labels. Any and all feedback is appreciated and considered tag.js /* * Shortcuts for creatings different tags */ function createLabel(text) { let label_tag = document.createE...
Imagine you have two string sequences: val s1 = Seq("c", "a", "b", "z", "a", "b") val s2 = Seq("a", "b") You need to come up with an algorithm that generates a binary membership mask of s2 in s1, e.g.: algorithm(s1, s2) => 011000 Here are some other examples: val s1 = Seq("a", "b", "z", "c", "a") val s2 = Seq("a", "b...
I'm trying to develop a program in Python that allows the user to import datasets and perform operations on them using pandas and numpy so she/he can skip writing all the preprocessing code her/himself. I have two questions. Am I using my functions poorly? For example, can I create cleaner, more efficient code by using...
The intention is to implement an xmlHttpRequest in plain vanilla js while considering all possible errors and problem situations without crashing in the browser. Result and faults are to be properly communicated back to the caller. function get() { return new Promise(function(resolve, reject){ var xmlHttpRe...
I have an older class that I am working on and I'm updating it to remove "Windows" specific code. It had some "Thread Protection Code" that used CRITICAL_SECTION. I'm in the process of changing the use of CRITICAL_SECTION to use std::mutex and std::lock_guard. One thing to take note of is that my class does have static...
Given a sorted list of integers, square the elements and give the output in sorted order. For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81]. My solution 1: const square = el => el * el; const sortAsc = (a, b) => a - b; const sortSquare = list => list .map(square) .sort(sortAsc); console.log(sortSqu...
A an integer permutation array[] is said to be cyclic if and only if we can choose an arbitrary element at position i, move it to the array[i]'s position, move the array[i]'s element to array[array[i]]'s position, and finally end up to the ith position. For example, \$\langle 1, 2, 0 \rangle\$ is cyclic, whereas \$\lan...
I came up with this solution to an exercise out of John Zelle's Python Programming book. #bust.py --- Simulates multiple games of blackjack with each possible dealer starting card and estimates # the probability that the dealer will bust import random def intro(): pass def takecard(): card = random.randint...
This is my React component for looping a component i.e. I don't want to use MAP or FOREACH in React Component's HTML. import React from 'react'; /** * @param {items} from props * @description -> Works with array of items and render only one children object inside it, ith data object will be available in children com...
I have the following function that is called via signal. 1) check if incluencer exists. 2) Increase discount by +1. Currently, I hit the database twice. Is there a better way to write that? Additionally, I wonder I can check 2) all on a database level so I don't need the for-loop. @receiver(signal=charge_succeeded) @tr...
I've wrote a function which take in a list of ranges (the ranges being tuples) and then returns a list of dictionaries which are a summary of how these ranges overlap with each other There's not a lot of context to this to take into consideration, I was just aiming to find the overlaps pairwise from a list of ranges. T...
This is my first game. This header defines the constants: Constants.h: #ifndef CONSTANTS_H_INCLUDED #define CONSTANTS_H_INCLUDED #define WIN_WIDTH 800 #define WIN_HEIGHT 600 #define BALL_SPEED_X 4 #define BALL_SPEED_MAX_Y 4 #define BAR_FROM_BORDERS 40 #define BAR_SPEED 7 #define MAX_FPS 60 #endif // CONSTANTS_H_...
I am trying to write multiple dataframes into an excel file one after another with the same logic. Nothing changes for any of the data frame, except the number of columns or number of records. The functions are still the same. For example, writer = pd.ExcelWriter(OutputName) Emp_ID_df.to_excel(writer,'Sheet1',index ...
This is a very stripped-down version of a crypto library I am writing. There are cryptographic algorithms like RSA, DSA, ECDSA, EdDSA, ... which all have a similar pattern of having a private key, a public key, a signature and operations like sign data with a private key that gives a signature result, verify signature ...
I have two functions here, each one displays the gradient slightly differently with up to 5 gradients. Function 1: Function addCellColor(ByVal c As Range, ByVal color As Long) Dim c1 As Long, c2 As Long, c3 As Long, c4 As Long 'creates a gradient pattern if one doesn't already exist With c.Interior ...
This is my first rust program. I don't mind this being a strict review. What I want Reviewed? Idiomatic code. Performance improvements. Clean code! Program Requirements: Input a unsigned integer and calculate it's factorial. If q is given as input exit application. Implementation Use a big unsigned int implementat...
I was asked by a friend to write a simple page for selecting members to various tasks. The members are listed in a textfile, along with how much they are willing to contribute (Usually a number between 0 and 1). Bellow is an example of such a list: name, mebershipdegree Noen, 4 John Doe, 1 The rock, 0.5 Ally MacBeal, 0...
I'm new to programming. I tried to find a way to convert numbers into letters with Python. I would like to receive some advice to improve myself. This program works for numbers between 1 and 106 and I would like to know how the logic of the program can be improved. def changeNumberIntoLetter(value): number=numToLe...
I created a function that finds internal and external IP addresses, returns them in dict with the keys external_ips and local_ips: def get_address_types(address_list): """ determine whether an IP address is local or external from a given list of ip addresses returns a dict containing external and inter...
I am supposed to make a basic RSA encryption/decryption code, where I am only given e. I wrote this code to randomly generate two primes and then find their totient. But the totient is supposed to not be co-prime with e which is given as 65537. So this code would technically return a good value eventually, but in rea...
Given input such as: foos = [ [], [{'a': 1}], [{'a': 1}, {'a': 2}], [{'a': 1}, {'a': 2}, {'a': None}], [{'a': 1}, {'a': 2}, {'a': None}, {'a': None}], [{'a': 1}, {'a': None}, {'a': 2}], [{'a': 1}, {'a': None}, {'a': 2}, {'a': None}], [{'a': 1}, {'a': None}, {'a': 2}, {'a': None}, {'a'...
I am reading through K&R C 2nd Edition, and I am on exercise 1-13. The exercise is to write a program to print a histogram of the lengths of words in its input. I wrote a program that successfully does this; however, after looking at the program, I noticed that it was somewhat messy, and I'm sure that there is a better...
I'm currently working on doing some fundamental practice around Objects after spending years coding in C# but in a very procedural way, I'm also starting to try and learn SOLID. My main concerns on my code are the validation rules inside the Auction class and throwing so many exceptions as it feels wrong, I feel like I...
import keyboard import os import sys from colorama import Fore, Back, Style, init init() clear = lambda: os.system('cls') cwd = os.getcwd() header = """ ____ _ ____ _ _ _ ___ _ / ___|___ (_)_ __ / ___|__ _| |_ _| | __ _| |_ ___ _ __ / _ \\ / | | | / _ \\| ...
I have two objects, one input = Array<Type> and one stored = Array<{..., Type}> What's the best (cleanest) way to put the elements in the first array into the sub-elements of the second? We can assume they're of the same size. My current code below works, but looks bad due to the double iterator usage. var count = 0; s...
I just made this simple XOR encryptor and decryptor. It needs a file with the "private" key string inside. usage: encryptor "file to encrypt/decrypt" "file with the private key" "output file" To decrypt, just do the same but for the inputfile, use the already encrypted file and the same file with the key. /* * Encryp...