instruction stringlengths 71 95.1k |
|---|
A part of my day job is load-testing of our infrastructure. I wanted a tool to quickly write a load scenario for some application (DB, HTTP, ...). I have tried to write something in Haskell (a fairly new language for me). Would someone help me improve by reviewing the code?
This is the main module:
module Load.Core
... |
I would very much appreciate it if someone could review the php script below for any security risks.
I have a live website using shared hosting. There's a page that accepts text submissions from users. The message is sent to a phpmyadmin database table; nothing is printed immediately to HTML. The messages are stored in... |
I'm currently learning C# in hopes of making games on my own using Unity.
I'm using the Udemy class by Denis Panjuta and followed 8 sections before making my first app by myself.
The 8 sections include Datatypes and Variables, Functions and Methods, Making decisions, Loops, OOP, Arrays and List, and Debugging.
I know h... |
I had a task to create a simple hangman game using O.O.P. with Javascript. It had to render the puzzle and remaining guesses to the DOM but didn't require any C.S.S.
This is what I created.
This is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=... |
I want to find the largest element in a sorted array, where the differences between the consecutive elements of the array are increasing, that is smaller than x.
For example:
[1, 3, 10, 17, 50, 1000] is a valid input , because the consecutive differences (2,7,7,33,950) are in increasing order.
[1, 3, 4, 10, 18] is no... |
I've recently started working on my own game engine and I have been thinking about creating my own model format. Since text usually takes a long time to load and process I decided to make a binary file. After a little work, I already had the basic concept:
The concept
The header:
The header of the file contains the ma... |
I’m learning python and have built a very simple program that just renames files. It makes all letters lowercase and replaces spaces and %20-instances with underscores and then copies them into a ‘Finished’ folder. I’m looking for better methods and approaches of writing and structuring my code.
Can anybody find any ob... |
Overview
A "from scratch" generic quicksort implemented in C, which allows predicate (returning bool, like C++ rather than int like C), and any type via void*.
Using memcpy for the swap() implementation was the general solution. But this was about twice as slow as declared types for small types (int, float, double etc)... |
I'm trying to implement a function (a template-helper function) which provides a simple merge-like functionality for both arrays and objects. The two functions are basically looks identical:
const mergeArrays = (first, ...rest) =>
rest.reduce((acc, curr) => ([ ...acc, ...curr]), first);
const mergeObjects = (first, ... |
This code works, and I'm pretty sure it's mathematically/algorithmically correct:
model = tf.keras.applications.MobileNet(include_top=False,input_shape=INPUT_SHAPE)
model.trainable = False
model = tf.keras.Sequential([
model,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(
1, "sigmoid"
),
])
... |
This is a (more or less) continuation of a previous post I made: Generic implementation of a hashtable with double-linked list.
I got lots of valuable feedback, so I decided to rewrite the entire module from scratch to improve readability, performance and also to add new features.
Specifications:
The hashmap implement... |
System76 sells laptops that come preloaded with their Ubuntu spinoff Pop_OS. The laptop keyboards have backlights that can change color and brightness, but so far I haven't found any way to keep the setting when I restart the machine; it goes back to bright white.
Here's someone else struggling with the same problem so... |
Just finished my canvas game that is more or less replica of the old school arcade game "Space Invaders".
The code below chooses two random enemies every second (approximately) from the enemies array to shoot projectiles. If there are two or more enemies left in the array I want two random enemies to shoot every second... |
I am trying to create an optimized 16-bit division algorithm for the AVR ATMEGA1284. The goal is to reduce the number of clock cycles as much as possible.
AVR INSTRUCTION SET MANUAL:
https://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf
AVR200: Multiply and Divide Routines:
https:/... |
This is the first project I am attempting in Python, and my first time on Stack Exchange, so please be kind.
The game uses a text file with lots of words. I was wondering how to improve the game by having different difficulty levels. E.g. easy for 1-4 letters, medium for 5-8 letters, hard for 9+ letters in the word.
Al... |
The idea of a prime sieve is fascinating - but it has to be segmented to increase the locality of the code if you want it to be fast.
Walish's segmented_sieve.cpp (see below)showed me that it works - fast. It took me some time to understand how the segments are managed. Once my version was working, it was 5% faster tha... |
The program takes 2 decimals as input and an operator (+, -, *, /, ^) so far. Any suggestions to make this code cleaner or shorter?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
class Program
{
static void Main... |
This is a follow-up question for A recursive_transform Template Function Implementation with std::invocable concept in C++, A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++, A recursive_transform for std::vector with various return type and A recursive_invok... |
The question is: To select 2 numbers out of n positive integer inputs (order matters), where the number that is placed anywhere before the second must be greater than the second by a given number m. Count the total number of selections.
An example answer would be, given the inputs 5 1 3 2 4 and m is 0, the total number... |
My goal was to have a single page display bulk amounts of media without the need to load new pages. I also wanted it to be able to load fast, so the generator uses a JavaScript array to display one item at a time. The user can move through the array backwards and forwards with the use of two buttons.
Images, video and ... |
I try to use unittest for conference class, but I am not sure that I have considered all condition or more complex tests should be added?
conference.py
from datetime import timedelta, datetime
class Conference:
def __init__(self):
self.inputs ='input.txt'
self.outputs = 'output.txt'
self.... |
I just finished a small assignment and I would like to get some feedback about the implementation here. Basically, it was all about distributing items ("talks" in this case) throughout the day based on the time constraints (their duration). For instance, a given place have different "tracks" each of which has a morning... |
Today I am working on refactoring and documenting some ancient Delphi code. In that language, which is derived from Pascal, there are three forms of comments:
(* This is the original Pascal style comment, which is never used in my files *)
{ this is TurboPascal-style comment which I want to remove }
// This is a Delph... |
Here's my very basic String class. This is my first attempt, to try to design and write a basic String class in C++, without using the absolute new features provided by newer C++.
class MyString {
public:
MyString(): pSize{0}, pStr{nullptr} {}
MyString(const char* cstr):
pSize{compute_... |
The following SQL code serves the purpose of assessing basic SQL Server literacy.
I am creating database and tables schemas, inserting data from .csv files.
Constructing 8 simple queries as answers to assignment tasks.
The code works well, but as I am very new to MSSQL Server I need some advice on the following:
Are t... |
I am practically brand new to coding and this is my first "real" project I've been attempting. It's an attempt at a vanilla JS game with selectable layout and win conditions (partially implemented). ATM it only has a vertical win condition included as I didn't want too much cluttering of the code (horizontal and diagon... |
input: 800(days)
output:
2 years
2 months
10 days
Conditions are required to match: only to facilitate the calculation, consider the whole year with 365 days and 30 days every month. In the cases of test there will never be a situation that allows 12 months and some days, like 360, 363 or 364.
I have solved this probl... |
public sealed class Client
{
private Simulation _simulation;
public Client(ITickProvider tickProvider, ICommandReceiver commandReceiver)
{
_simulation = new Simulation();
tickProvider.Tick += HandleTick;
commandReceiver.CommandReceived += HandleCommandReceived;
}
private void H... |
I am trying to implement a 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. For example:
Input String
Start Keyword
End Keyword
Output
"C# was developed around 2000 by Microsoft as part of its .NET ... |
Please find the following scenario, I've dynamic JS date format string from API but I am looking for the best way to convert the format that accepts in PHP date format. For now, I wrote it my own way but I doubt there should be a standard solution.
JS time format: YYYY-MM-DD / YYYY/MM/DD
Need PHP format: Y-m-d / Y/m/d... |
Please review my ostream logger, ologger, which attempts to make logging as easy as using cout. The ostream operator<< is leveraged so that anything that can be logged to cout can be logged to this logger. To log custom classes/structs the user would need to overload operator<< in their custom class.
Any feedback wo... |
I'm writing a multi-threaded program where some external part of the program needs access to a large piece of data that's controlled by my class. I'm trying to return a reference to this data in a thread-safe way.
class Chunk
{
public:
Chunk(){
chunkData = std::make_shared<vector<XMFLOAT3>>();
chun... |
I got tasked with writing a page that will add as many profile entries as the user wants, and web programming is not at all my field. There are multiple input groups but I'm just using the "age" one as an example. Currently I'm using a function to create DOM elements, then I assemble them together and return the comple... |
Edit: this is a base library for including in larger projects for the overall management of JSON Web Tokens (JWT) that should be compatible with other JWT libraries that share an encryption secret - also remote systems can reach out to the issuing system (with my library or a different JWT library) to verify the token... |
I found these two videos by Marcel Vos: (1) (2) that show how you can make hedge mazes that are very hard for the simple roller coaster tycoon 2 park guest AI to solve. Long story short, he eventually makes mazes that cover the entire map and leaves the guest to wander for what we'll just call eternity.
Because the mec... |
I am writing an immutable interpreter in C++ for fun. Originally standard vectors and dequeues were used to create a double ended queue data type, but it was very slow, because each operation require a whole new copy of the original container to be created.
So it was redone using a custom immutable single linked node ... |
I'm wondering if there is a more efficient way of filtering a dataframe down based on certain unique values in several columns. Once I have it filtered down, I then want to extract keep one the largest value and I do this by dropping all indexes from the original dataframe. However, this process is slow and as the iter... |
I have a short function written in JavaScript using jQuery which takes a message and appends it to a div. It does this one character at a time with a small delay between characters, and then returns the time that it took it will take for the function to finish running.
const log = $('#log')
function logMessage(message... |
Currently, I can set the the current_user in the views.py for a form, which requires the user object to validate the post (and its origin).
Is there a better way to more eloquently set the user in a form than what I've posted below? Note, this is in views.py and I have no altered forms or models to tackle this aspect.
... |
Here is an example where I'm trying to understand the concepts of buffered channels> I have three functions and create a buffered channel of length 3. And also passed a waitgroup to nofiy when all the goroutines are done. And finally collecting the values through range.
Could you please help me in reviewing this code? ... |
Recently on SO there was this question
i am trying to get sequence index of each array of array like I have
an element of the array and that 5 arrays have multiple elements and I
want to get the first index of each array then the second and so.
below is my array data const arrData = [[1,2,4,6],[3,8,7],[12,13],[],[9,10... |
I am trying to re-organise my mp3 collection based on its id3 meta data into folders based on the artist. I'm new to nodeJs and more importantly promises. I was hoping I could get some feedback on my script. I can manage the creating of folders and copying of files quite easily, but I'm a little unsure on the async rea... |
I am writing a python module to interact to the ROD (remedy on demand) BMC ticketing product. So far I have only written the log in and log out methods and tests. Before I crack on with the more complex methods I hope someone can review the current test strategy and happy to hear any suggestions for improvements.
rodAP... |
This is a follow-up question for A recursive_transform for std::vector with various return type and A recursive_transform Template Function Implementation with std::invocable concept in C++. Besides the recursive version std::ranges::transform, I am trying to implement a recursive version std::ranges::copy_if.
The expe... |
I have done a sorting program, it works but I am new to the coding world and I would love to hear your thoughts.
public class CorrectPlacement {
public void placer(int... numbers) {
System.out.println("Before : " + Arrays.toString(numbers) + " ");
for (int i = -1; i <= numbers.length - 2; i++) ... |
Purpose of the code :
To assign the corresponding label of the centroids to the points which are close to it. Below is a graphical (2D) example.
Variable X is a matrix, rows represent the points, columns collectively represent the coordinates
idx is the list of centroids assigned to every example
Inefficient MATLA... |
I made a quick script, that inputs file paths(made for C files), function names and 2 indexes. The script goes over all of the files and switches the indexes of the 2 functions. e.g.:
Running the following code:
python switch_args.py temp_funct 0 1 tmp.c
If tmp.c contains this code:
int my_func(a, b, c, d)
after the ... |
I'm new to Java so I have given myself small projects to help myself learn the ropes of java. My project was to create a function that would summate an expression no matter how high the degree or value of n.
I ended up being able to complete it but I wanted someone who knew what they were doing to look over it and see ... |
I created a function to give me an estimated date of hearing back from grad school applications using the median length of days between each theGradCafe submission and January 1st. I separated submissions into three categories -- general, Interview, Acceptance, Rejection.
This is my first R project and I would love to ... |
An unsigned integer version of pow() is fairly easy to code, yet I also wanted:
overflow detection
portability
only modest performance impact due to overflow detection.
The below codes uses a simple >= test in the loop to see if the calculation is nearing overflow. When needed, in a 2nd loop, more expensive / tests ... |
I have a PHP script that uploads an image file, checks it for size, extension, and type. It then converts it to png, saves it to a folder outside the web root with a randomly generated name, then moves it to a specific folder inside the web root with a new filename that matches the user's username. By default, users ha... |
I made a program that will take in a time and a weekday, and return which parts of the
world are at times closest to the one specified. Part of the program focuses on extracting a date and country out of a user input.
Here are some example inputs and outputs:
"In what part of the world is it 4:00 PM Friday right now?" ... |
Next: Advent of Code 2020 - Day 2: validating passwords
Problem statement
I decided to take a shot at Advent of Code 2020 to exercise my Rust knowledge. Here's the task for Day 1:
Day 1: Report Repair
[...]
Specifically, they need you to find the two entries that sum to 2020
and then multiply those two numbers togeth... |
As part of my training, I implemented a dataset class in C++ that allows me to create synthetic datasets to get more familiar with features that C++ offers such as object oriented programming.
This implementation uses a simple method to create two intertwined spirals as shown in the following image.
The output looks a... |
This code is a revised version of implementation which asked for an improvement. Original question is asked here:
remove kth last element from singly-linked list
credits to: Toby, Andreas, Arkadiusz
What has changed:
remove length from xllist struct
check if k is bigger than list length on the fly
Code:
#include <std... |
def alphabetlist():
print("alphabet1 = [a,b,c,d,e,f]")
print("alphabet2 = [g,h,i,j,k,l]")
print("alphabet3 = [m,n,o,p,q,r]")
print("alphabet4 = [s,t,u,v,w,x]")
print("alphabet5 = [y,z]")
print("Guess a word.")
print("Now i will try to figure out the word you guessed.")
totalletters=int(input("tota... |
happy 2021 everyone!
I started coding some months ago for fun and recently I challenged myself to build a JSON parser in Python (v3.8).
The basic idea was to avoid loading the whole file at once, instead parsing a file line by line. But of course I'm still a newb, so there is probably a lot of absurdities in there. Con... |
I am currently learning React and tried building the UI of a basic minesweeper game as a first project. My goal was to write simple, re-usable components. I will go over each of them and do my best to explain the rationale behind them and, after that, explain how they are all tied together in the main App component. Pl... |
So I implemented a simple console-based, offline player vs. player chess game in C++17. I am aware that there are multiple chess-specific features I have not yet added, but the core gameplay works perfectly fine. This is quite a big project for a review, but I would be very grateful for any kind of advice. The code is... |
I need some review on my implementation of input iterator. I am currently re-implementing std::vector, and need input_iterator for a specific constructor.
Any criticism is much appreciated! Thank you.
#ifndef INPUT_ITERATOR
#define INPUT_ITERATOR
template<typename T>
class input_iterator
{
private:
T* input_iter;
... |
I'm developing a class for connection to LCD (Liquid Crystal Display).
It can connect in two modes: 4-bit and 8-bit. And the number of modes may be increased. The mode can be configured in the constructor.
A lot of behavior depends on the mode. But! The mode can be changed in run-time, so I can't create the Lcd abstrac... |
I've searched this site and find many similar questions, but not exactly the same as the one I'll post.
This attempts to solve Leetcode 239:
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in ... |
In order to learn rust and concurrency , im trying to share a common hashmap between actix web server and a parallel thread
Theres one thread which updates a hashmap with the current timestamp every 10 seconds
theres a GET API which returns the latest timestamp provided in the hashmap
heres my code
use actix_web::{we... |
The set-cover problem is explained here.
I am using lists that are being treated as sets. As I found lists were easier to manipulate in python than sets.
The first part of the algorithm uses input validation.
import json
from copy import deepcopy
import random
s = input("Input list of integers (no repeating elements)... |
As I'm doing the MOOC Java course I decided to write a small program to count the word occurrences that accepts as the first (mandatory) input a path to a text file (extension not enforced) and as many words you want to check (optional). It prints out the results to the terminal. Checked with books in .txt format from ... |
I have some JavaScript code to manage a 2D map in a game. I have a function to create a new room in the map which is at map[x][y]. I need to create that property and also initialize the monsters property. The code I wrote looks like this, which works fine.
'use strict';
let map = {};
function newRoom(x, y) {
if (... |
I'm making a Unity game with a "1-bit" color palette, a la Downwell - the vast majority of the screen will end up being in black and white, but unlike true 1-bit graphics, some highlights and visual effects will use additional colors. In my case, those effects will output values along a range of colors making up a sing... |
I'm learning C# .NET 5 Intrinsics and interested in best practices. It's really hard now to find enough information about how SIMD instructions (logically/internally) work in .NET. In addition i'm not familiar with C++ and Assembly languages.
The purpose of the solution - apply Sobel Operator filter to the loaded image... |
I made a fork bomb virus in Assembly. Now, I want to make my code better.
Here is my code:
section .text
global _start
_start:
mov eax, 2
int 0x80
jmp _start
Makefile:
DIR=build
$(shell mkdir -p $(DIR))
$(shell nasm -f elf64 Program.asm -o Program.o)
$(shell ld Program.o -o build/ForkBomb)
$(shell rm ... |
Previous: Advent of Code 2020 - Day 1: finding 2 or 3 numbers that add up to 2020
Next: Advent of Code 2020 - Day 3: tobogganing down a slope
Problem statement
I decided to take a shot at Advent of Code 2020 to exercise my Rust knowledge. Here's the task for Day 2:
Day 2: Password Philosophy
[...]
To try to debug the... |
I've been tasked with writing a function that executes a passed function every interval, passed to the function by the user. Below is the code, and how to call it:
import time
from typing import Callable
last_milliseconds: int = 0
def set_timer(interval: int, function: Callable) -> bool:
global last_milliseconds
... |
I am trying to implement a monochromic image container with std::unique_ptr.
The example usages
The example usages is as below.
int main()
{
auto test_data = std::make_unique<unsigned char[]>(100 * 100);
for (size_t i = 0; i < 100 * 100; i++)
{
test_data[i] = 3;
}
auto test = DigitalImagePro... |
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. It's my first project in Python and while I've already gotten some help, I now have a version of my project which works quite well.
I use a FONA 808 from Adafruit as the cellular ... |
I needed a way to automatically update my IP forwarding rules on Google Domains for my home web server running behind my router. (I'm not paying for a static IP!). After writing a simple functional script for myself, I decided to refactor it to be object oriented and make it work for anyone.
I know you could write a si... |
I've been trying to build 3D rendering engine for some time. My main source of knowledge about OpenGL is amazing www.learnopengl.com so is my code design heavily inspired by Joe's examples. What I didn't like about his approach - I know educational code is different beast from enterprise solutions - is no connections b... |
I have created helper class for configuration validation, the main purpose is to find any human "errors"
in the configuration for the app.
the case is that any type of "message" can be configured in more then one place, the application is ok with that and do no not limit this, in some very rare cases this is needed but... |
I reinvented a c++ smart pointer, shared_ptr to be precise. It is meant for practice purpose and does not attempt to replace the standard implementation. To the best of my knowledge, the code works as expected. I decided to skip the custom deleter because I want to keep things simple for now. I would love feedbacks and... |
You are assigned to put some amount of boxes onto one truck. You are given a 2D vector of box_types where box_type[0] is the number of a type of box and box_type[1] is the units per box for that type. You are also given an integer value for the truck size, this the maximum boxes you can put in the truck. Return the max... |
For my CS class I the task given was to take a given Person Class with a name and age attributes.
Then, with an existing list of Person Objects, create a function that returns a tuple of (mean, median, mode) on the given age attribute.
Simple enough, but I wondered if my solution is really all that efficient. I basical... |
I made a tree structure (Tree) that represents an algebraic expression that contains two binary opperators the "question mark" Q/"?" and the "exclamation mark" E/"!".
Both are associative (that means a!(b!c)=(a!b)!c, and the same for the questionmark; this means the order of evaluation doesn't matter and we can omit th... |
I'm working on making a text adventure using Electron. I have the basics of the engine working, you can walk around an infinite map. Maps contain things, and you can enter a few basic commands. I'm wondering if the fundamentals of the game (what I currently have) can be improved at all before I go through adding the ga... |
The Debounce technique allow us to “group” multiple sequential calls in a single one - The debounce() function forces a function to wait a certain amount of time before running again.
I wrote both debounce_1 & debounce_2 functions while solving a programming challenge, they produce the same result but I want to know wh... |
My pet project, is a community driven lyrics archive, it is still a work in progress, and all code is open sourced on GitHub.
I have a local git branch tests/add-controller-tests where I wish to add some unit tests on my controllers. I have purposefully kept my controllers basic, for example here is my HTTP GET Index a... |
you can find the challenge here for more details, but the subject says it all;
Check a provided list of entries for 2 numbers which sum to 2020, return the product of those addends.
I waited until the event was over to keep things fair.
/*This will search for 2 numbers in the `list that sum to `target`
Assumption;... |
I need to sort a list of strings that I'm reading in but the sorted order of that list is not predetermined (I can't hard code it); I read in the sort order from a source and build a comparator by assigning a numerical value to each entry in a map and then use that to determine the order.
My implementation is pretty si... |
I'm solving Euler exercise number 7 and trying to go a bit further on bigger primes.
It is too slow with big numbers. I've been reading ways to optimize the sieve, but I would like to ask people with more experience with this.
import time
from math import log, ceil
start = time.time()
primes = [2]
op_count = 0
limitN ... |
ERROR: type should be string, got "https://github.com/speedrun-program/load-extender\nIt’s a pair of programs for extending load times, one for Windows and one for Linux. The Windows version is written in C++, and the Linux version is written in C so it can work with LD_PRELOAD.\nI'm mainly interested in making sure I'm not doing anything that could cause a crash since I know these languages have a lot of undefined behavior, but I'll try to fix any other problems that get pointed out too. I'm sure there are problems with how it's written because I have very limited coding experience, and this is the first thing I've ever written in C/C++.\nHere's the code for Linux:\nfopen_interceptor.c:\n#define _GNU_SOURCE\n\n#include <stdio.h>\n#include <dlfcn.h>\n#include <time.h>\n#include <pthread.h>\n#include \"khash.h\"\n// thank you for making this hash map, attractivechaos.\n// here's his github: https://github.com/attractivechaos\n\n// these are global so fopen and khash_destruction can see them\nstatic pthread_mutex_t lock;\nstatic unsigned char LOCK_SUCCESS = 0; // used so it won't try to destroy lock if it failed to be made\nstatic unsigned char SETUP_SUCCEEDED = 0; // if this is 0 then the fopen interception function skips to calling the real fopen function\nstatic const int khStrInt = 32;\nKHASH_MAP_INIT_STR(khStrInt, unsigned int*)\nstatic khash_t(khStrInt) *my_khash_map;\n\n#include \"khash_setup_header.h\" // included here so it recognizes kh_khStrInt_t\n\nstatic void __attribute__((constructor)) khash_setup();\nstatic void khash_setup()\n{\n my_khash_map = kh_init(khStrInt);\n if (pthread_mutex_init(&lock, NULL) != 0)\n {\n printf(\"mutex init failed\\n\");\n return;\n }\n LOCK_SUCCESS = 1; // LOCK_SUCCESS only changed here\n FILE *my_file;\n FILE *(*original_fopen)(const char*, const char*);\n original_fopen = dlsym(RTLD_NEXT, \"fopen\");\n my_file = original_fopen(\"./files_and_delays.txt\", \"r\");\n if (my_file == NULL)\n {\n printf(\"error opening files_and_delays.txt\\n\");\n return;\n }\n // longest_name, longest_sequence, longest_delay, and line_count made here so they can be printed in fopen_interceptor_test\n size_t longest_name = 1; // starts at 1 for null character\n size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence\n unsigned char longest_delay = 1; // starts at 1 for null character\n unsigned int line_count = 1; // starts at 1 because there's always at least 1 line. khash map largest value is UINT_MAX\n unsigned char khash_succeeded = prepare_to_setup(my_khash_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);\n fclose(my_file);\n if (khash_succeeded == 0) // khash failed to be made. Error message is printed in khash_setup_header in prepare_to_setup.\n {\n return;\n }\n SETUP_SUCCEEDED = 1; // SETUP_SUCCEEDED only changed here\n}\n\nstatic void __attribute__((destructor)) khash_destruction();\nstatic void khash_destruction()\n{\n khiter_t khash_map_iter;\n for (khash_map_iter = 0; khash_map_iter < kh_end(my_khash_map); ++khash_map_iter) // kh_destroy doesn't free keys and values, they need to be freed like this\n {\n if (kh_exist(my_khash_map, khash_map_iter))\n {\n free((char*)kh_key(my_khash_map, khash_map_iter));\n kh_key(my_khash_map, khash_map_iter) = NULL;\n free((unsigned int*)kh_val(my_khash_map, khash_map_iter));\n kh_val(my_khash_map, khash_map_iter) = NULL;\n }\n }\n kh_destroy(khStrInt, my_khash_map);\n if (LOCK_SUCCESS == 1)\n {\n pthread_mutex_destroy(&lock);\n }\n}\n\nFILE *fopen(const char *path, const char *mode)\n{\n if (SETUP_SUCCEEDED == 1) // skip to calling original fopen if setup failed\n {\n short slash_index = -1;\n for (unsigned short i = 0; path[i] != '\\0'; i++) // look for start of filename by finding last occurence of '/' character\n {\n if (path[i] == '/')\n {\n slash_index = i % SHRT_MAX; // will cause key to not be found, but prevents unsigned int overflow\n }\n }\n // +1 so '/' isn't included. If '/' not found in path, slash_index stays -1 and entire path argument is checked as key since \"path + -1 + 1\" is the same as just \"path\"\n khiter_t khash_map_iter = kh_get(khStrInt, my_khash_map, path + slash_index + 1);\n if (khash_map_iter != kh_end(my_khash_map)) // key found\n {\n unsigned int *delay_sequence = kh_val(my_khash_map, khash_map_iter);\n pthread_mutex_lock(&lock); // don't let other threads change delay sequence when it's being read or changed\n if (delay_sequence[2] == UINT_MAX) // reset all delay sequences\n {\n unsigned int *sequence_to_reset;\n kh_foreach_value(my_khash_map, sequence_to_reset, {sequence_to_reset[1] = 2;});\n pthread_mutex_unlock(&lock);\n }\n else if (delay_sequence[1] < delay_sequence[0])\n {\n if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence\n {\n delay_sequence[1] = 2;\n }\n unsigned int sleep_time = delay_sequence[delay_sequence[1]];\n delay_sequence[1] += 1;\n pthread_mutex_unlock(&lock);\n long time_nanoseconds = (sleep_time % 1000) * 1000000;\n struct timespec ts = {sleep_time / 1000, time_nanoseconds};\n nanosleep(&ts, NULL);\n }\n else // delay sequence already finished\n {\n pthread_mutex_unlock(&lock);\n }\n }\n }\n FILE *(*original_fopen)(const char*, const char*);\n original_fopen = dlsym(RTLD_NEXT, \"fopen\");\n return (*original_fopen)(path, mode);\n}\n\nfopen_interceptor_test.c:\n#define _GNU_SOURCE\n\n#include <stdio.h>\n#include <time.h>\n#include <pthread.h>\n#include \"khash.h\"\n// thank you for making this hash map, attractivechaos.\n// here's his github: https://github.com/attractivechaos\n\n// these are global so fopen and khash_destruction can see them\nstatic pthread_mutex_t lock;\nstatic unsigned char LOCK_SUCCESS = 0; // used so it won't try to destroy lock if it failed to be made\nstatic unsigned char SETUP_SUCCEEDED = 0; // if this is 0 then the fopen interception function skips to calling the real fopen function\nstatic const int khStrInt = 32;\nKHASH_MAP_INIT_STR(khStrInt, unsigned int*)\nstatic khash_t(khStrInt) *my_khash_map;\n\n#include \"khash_setup_header.h\" // included here so it recognizes kh_khStrInt_t\n\nstatic void __attribute__((constructor)) khash_setup();\nstatic void khash_setup()\n{\n my_khash_map = kh_init(khStrInt);\n if (pthread_mutex_init(&lock, NULL) != 0)\n {\n printf(\"mutex init failed\\n\");\n return;\n }\n LOCK_SUCCESS = 1; // LOCK_SUCCESS only changed here\n FILE *my_file;\n /*FILE *(*original_fopen)(const char*, const char*);\n original_fopen = dlsym(RTLD_NEXT, \"fopen\");\n my_file = original_fopen(\"./files_and_delays.txt\", \"r\");*/\n my_file = fopen(\"./files_and_delays.txt\", \"r\");\n if (my_file == NULL)\n {\n printf(\"error opening files_and_delays.txt\\n\");\n return;\n }\n size_t longest_name = 1; // starts at 1 for null character\n size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence\n unsigned char longest_delay = 1; // starts at 1 for null character\n unsigned int line_count = 1; // starts at 1 because there's always at least 1 line. khash map largest value is UINT_MAX\n unsigned char khash_succeeded = prepare_to_setup(my_khash_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);\n fclose(my_file);\n if (khash_succeeded == 0) // khash failed to be made. Error message is printed in khash_setup_header in prepare_to_setup.\n {\n return;\n }\n printf(\"\\nlongest filename (plus null character and whitespace in file): %zu\\n\"\n \"longest delay sequence (+2 for current delay and sequence length): %zu\\n\"\n \"most digits in delay (+1 for null character, max delay is UINT_MAX): %u\\n\"\n \"lines in file (overestimates slightly): %u\\n\"\n \"khash map size (lines should be less than 70%% of this): %zu\\n\", longest_name, longest_sequence, longest_delay, line_count, kh_n_buckets(my_khash_map));\n SETUP_SUCCEEDED = 1; // SETUP_SUCCEEDED only changed here\n}\n\nstatic void __attribute__((destructor)) khash_destruction();\nstatic void khash_destruction()\n{\n khiter_t khash_map_iter;\n for (khash_map_iter = 0; khash_map_iter < kh_end(my_khash_map); ++khash_map_iter) // kh_destroy doesn't free keys and values, they need to be freed like this\n {\n if (kh_exist(my_khash_map, khash_map_iter))\n {\n free((char*)kh_key(my_khash_map, khash_map_iter));\n kh_key(my_khash_map, khash_map_iter) = NULL;\n free((unsigned int*)kh_val(my_khash_map, khash_map_iter));\n kh_val(my_khash_map, khash_map_iter) = NULL;\n }\n }\n kh_destroy(khStrInt, my_khash_map);\n if (LOCK_SUCCESS == 1)\n {\n pthread_mutex_destroy(&lock);\n }\n}\n\nstatic void fopen_test(const char *path, const char *mode)\n{\n if (SETUP_SUCCEEDED == 1) // skip to calling original fopen if setup failed\n {\n short slash_index = -1;\n for (unsigned short i = 0; path[i] != '\\0'; i++) // look for start of filename by finding last occurence of '/' character\n {\n if (path[i] == '/')\n {\n slash_index = i % SHRT_MAX; // will cause key to not be found, but prevents unsigned int overflow\n }\n }\n // +1 so '/' isn't included. If '/' not found in path, slash_index stays -1 and entire path argument is checked as key since \"path + -1 + 1\" is the same as just \"path\"\n khiter_t khash_map_iter = kh_get(khStrInt, my_khash_map, path + slash_index + 1);\n if (khash_map_iter != kh_end(my_khash_map)) // key found\n {\n unsigned int *delay_sequence = kh_val(my_khash_map, khash_map_iter);\n printf(\"%s successfully found in khash map\\n\", path + slash_index + 1);\n pthread_mutex_lock(&lock); // don't let other threads change delay sequence when it's being read or changed\n if (delay_sequence[2] == UINT_MAX) // reset all delay sequences\n {\n unsigned int *sequence_to_reset;\n kh_foreach_value(my_khash_map, sequence_to_reset, {sequence_to_reset[1] = 2;});\n pthread_mutex_unlock(&lock);\n printf(\"all delay sequences reset\\n\");\n }\n else if (delay_sequence[1] < delay_sequence[0])\n {\n if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence\n {\n delay_sequence[1] = 2;\n printf(\"%s delay sequence reset\\n\", path + slash_index + 1);\n }\n unsigned int sleep_time = delay_sequence[delay_sequence[1]];\n delay_sequence[1] += 1;\n pthread_mutex_unlock(&lock);\n long time_nanoseconds = (sleep_time % 1000) * 1000000;\n struct timespec ts = {sleep_time / 1000, time_nanoseconds};\n //nanosleep(&ts, NULL);\n printf(\"sleep for %ld second(s) and %ld millisecond(s)\\n\", ts.tv_sec, ts.tv_nsec / 1000000);\n }\n else // delay sequence already finished\n {\n pthread_mutex_unlock(&lock);\n printf(\"%s delay sequence already finished\\n\", path + slash_index + 1);\n }\n }\n else // key not found\n {\n printf(\"%s not found in khash map\\n\", path + slash_index + 1);\n }\n }\n /*FILE *(*original_fopen)(const char*, const char*);\n original_fopen = dlsym(RTLD_NEXT, \"fopen\");\n return (*original_fopen)(path, mode);*/\n}\n\nstatic size_t find_longest_input_length(FILE *test_input) // find how much space to give to array used to hold input\n{\n size_t longest_input = 1;\n size_t current_input = 1; // starts at 1 for null character\n char ch = '\\0';\n while (ch != EOF && current_input < SIZE_MAX)\n {\n ch = fgetc(test_input);\n if (ch == '\\n' || ch == EOF)\n {\n if (current_input > longest_input)\n {\n longest_input = current_input;\n }\n current_input = 1;\n }\n else\n {\n current_input += 1;\n }\n }\n if (current_input == SIZE_MAX)\n {\n return SIZE_MAX; // a test path was too big\n }\n return longest_input;\n}\n\nstatic void print_khash()\n{\n printf(\"\\n---------- khash map current state ----------\\n\");\n const char *key_to_print;\n unsigned int *sequence_to_print;\n kh_foreach(my_khash_map, key_to_print, sequence_to_print,\n {\n printf(\"%s / \", key_to_print);\n for (unsigned int i = 0; i < sequence_to_print[0]; i++)\n {\n if (sequence_to_print[i] == UINT_MAX) // it's a reset point\n {\n printf(\"RESET\"); // it doesn't need a space because the line always ends here\n }\n else\n {\n printf(\"%u \", sequence_to_print[i]);\n }\n }\n printf(\"\\n\");\n });\n printf(\"---------------------------------------------\\n\\n\");\n}\n\nstatic void test_all_inputs(FILE *test_input, size_t longest_input)\n{\n char *input_array = (char*)malloc(longest_input); // find_longest_input_length accounts for null character. Always greater than 0, shouldn't return NULL\n if (input_array == NULL)\n {\n printf(\"malloc failed in test_all_inputs\\n\");\n return;\n }\n size_t ch_position = 0;\n char ch = '\\0';\n while (ch != EOF)\n {\n ch = fgetc(test_input);\n if (ch == '\\n' || ch == EOF)\n {\n input_array[ch_position] = '\\0';\n ch_position = 0;\n if (ch != EOF) // avoids extra test\n {\n printf(\"testing fopen input: %s\\n\", input_array);\n fopen_test(input_array, \"r\");\n print_khash();\n }\n }\n else\n {\n input_array[ch_position] = ch;\n ch_position += 1;\n }\n }\n free((char*)input_array);\n input_array = NULL;\n}\n\nint main()\n{\n FILE *test_input;\n test_input = fopen(\"./test_input.txt\", \"r\");\n if (test_input == NULL)\n {\n printf(\"error opening test_input.txt\\n\");\n return 1;\n }\n size_t longest_input = find_longest_input_length(test_input);\n if (longest_input == SIZE_MAX) // check_file will return SIZE_MAX if a test path is too big\n {\n printf(\"a test path is too big\\n\");\n fclose(test_input);\n return 1;\n }\n if (fseek(test_input, 0, SEEK_SET) != 0)\n {\n printf(\"fseek on test_input.txt failed\\n\");\n fclose(test_input);\n return 1;\n }\n printf(\"\\nlongest test path (+1 for null character): %zu\\n\", longest_input);\n printf(\"\\ntest start\\n\");\n print_khash();\n test_all_inputs(test_input, longest_input);\n fclose(test_input);\n printf(\"test finish\\n\\n\");\n return 0;\n}\n\nkhash_setup_header.h:\n#include <stdint.h>\n\nstatic unsigned char TOO_BIG_DELAY_SEEN = 0; // used so user won't be alerted more than once that they entered a delay that's too big\n\n// checks line count to know how much space to give to khash\n// updates longest_name and longest_sequence to know how much space to give to arrays used to hold key and value\nstatic void check_file(FILE *my_file, size_t *longest_name, size_t *longest_sequence, unsigned char *longest_delay, unsigned int *line_count, unsigned char digits_in_uint)\n{\n unsigned char checking_sequence = 0; // 0 if checking a filename's length, 1 if checking a delay sequence's length\n size_t current_name = 1; // starts at 1 for null character\n size_t current_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence\n unsigned char current_delay = 1; // starts at 1 for null character\n char ch = '\\0';\n // longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints\n while (ch != EOF && current_name < SIZE_MAX && current_sequence < (SIZE_MAX / sizeof(unsigned int)) && *line_count < UINT_MAX && current_sequence < UINT_MAX)\n {\n ch = fgetc(my_file);\n if (ch == EOF || ch == '\\n')\n {\n if (checking_sequence == 1)\n {\n if (current_delay > *longest_delay)\n {\n *longest_delay = current_delay;\n }\n if (current_sequence > *longest_sequence)\n {\n *longest_sequence = current_sequence;\n }\n checking_sequence = 0;\n current_sequence = 3;\n current_delay = 1;\n }\n *line_count += 1; // if for some reason there are a lot of hash collisions, the user can put empty lines in files_and_delays.txt to try to fix it\n current_name = 1;\n }\n else if (ch == '/')\n {\n if (checking_sequence == 0)\n {\n if (current_name > *longest_name)\n {\n *longest_name = current_name;\n }\n checking_sequence = 1;\n }\n else\n {\n if (current_delay > *longest_delay)\n {\n *longest_delay = current_delay;\n }\n current_sequence += 1;\n current_delay = 1;\n }\n }\n else if (checking_sequence == 0)\n {\n current_name += 1;\n }\n // ignores non-digits and leading zeros. maximum space is digits_in_uint + 1. +1 is for null character\n else if (((ch >= 49 && ch <= 57) || (ch == 48 && current_delay > 1)) && current_delay < digits_in_uint + 1)\n {\n current_delay += 1;\n }\n }\n if (current_name == SIZE_MAX || current_sequence == (SIZE_MAX / sizeof(unsigned int)) || current_sequence == UINT_MAX)\n {\n *line_count = UINT_MAX; // something was too big\n }\n}\n\n// reads the next filename and writes it in name_array\nstatic size_t read_name(FILE *my_file, char *ch, char *name_array)\n{\n size_t ch_position = 0;\n *ch = fgetc(my_file);\n while (*ch != EOF && *ch != '\\n' && *ch != '/')\n {\n name_array[ch_position] = *ch;\n ch_position += 1;\n *ch = fgetc(my_file);\n }\n name_array[ch_position] = '\\0';\n if (*ch == '/') // filename given and line didn't end abruptly\n {\n for (; ch_position > 0 && (name_array[ch_position - 1] == ' ' || name_array[ch_position - 1] == '\\t'); ch_position--)\n {\n name_array[ch_position - 1] = '\\0'; // remove whitespace between '/' and end of filename if the user has it written like that\n }\n }\n return ch_position + 1; // +1 for null character\n}\n\nstatic unsigned int my_atoi(char *delay_array, unsigned int max_power_of_ten, unsigned char digits_in_uint, unsigned char number_position)\n{\n unsigned char delay_too_big = 0;\n unsigned int current_power_of_ten = 1;\n unsigned int accumulator = 0;\n if (delay_array[0] == '\\0') // no digits found, assume delay is 0\n {\n return 0;\n }\n // delay has more digits than UINT_MAX or it has as many digits and the most significant digit is bigger in the delay than in UINT_MAX\n else if (delay_array[0] == '+' || (number_position == digits_in_uint && delay_array[0] - 48 > UINT_MAX / max_power_of_ten))\n {\n delay_too_big = 1;\n }\n else\n {\n number_position -= 1;\n for (; number_position > 0; number_position--) // sum everything except most significant digit\n {\n accumulator += ((delay_array[number_position] - 48) * current_power_of_ten);\n current_power_of_ten *= 10;\n }\n // checking that adding final value won't make accumulator overflow\n // delay_array[0] won't be bigger than UINT_MAX / max_power_of_ten here because the other else if block checks for that\n if (current_power_of_ten == max_power_of_ten && UINT_MAX - ((delay_array[0] - 48) * max_power_of_ten) - 1 < accumulator)\n {\n delay_too_big = 1;\n }\n else\n {\n accumulator += ((delay_array[0] - 48) * current_power_of_ten);\n }\n }\n if (delay_too_big == 1)\n {\n if (TOO_BIG_DELAY_SEEN == 0)\n {\n printf(\"\\nWARNING: maximum delay time is %u\\n\", UINT_MAX - 1);\n TOO_BIG_DELAY_SEEN = 1; // TOO_BIG_DELAY_SEEN only changed here\n }\n return UINT_MAX - 1;\n }\n return accumulator;\n}\n\n// reads the next delay sequence and writes it in sequence_array\n// also returns how many numbers are in the sequence so the right amount will be copied into the array given to khash\n// there can't be more than UINT_MAX delays in one sequence\nstatic unsigned int read_sequence(FILE *my_file, char *ch, char *delay_array, unsigned int *sequence_array, unsigned int max_power_of_ten, unsigned char digits_in_uint)\n{\n unsigned char number_position = 0; // next digit in current delay time. Also used in my_atoi to see if delay is too big\n size_t sequence_position = 2; // starts at 2 because first two indexes are used to store sequence length and what the next delay is\n delay_array[0] = '\\0'; // initializing to use in condition\n while (*ch != EOF && *ch != '\\n')\n {\n *ch = fgetc(my_file);\n if (*ch == EOF || *ch == '\\n')\n {\n delay_array[number_position] = '\\0';\n unsigned int last_delay = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input\n if (last_delay != 0) // no point adding 0 as final delay time\n {\n sequence_array[sequence_position] = last_delay;\n sequence_position += 1;\n }\n }\n else if (*ch == '/') // end of current delay, about to read next delay\n {\n delay_array[number_position] = '\\0';\n sequence_array[sequence_position] = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input\n sequence_position += 1;\n number_position = 0;\n }\n // ch is a digit and the digit isn't a leading zero and the maximum delay isn't reached\n else if (((*ch >= 49 && *ch <= 57) || (*ch == 48 && number_position > 0)) && delay_array[0] != '+')\n {\n if (number_position != digits_in_uint) // if it's already equal to digits_in_uint then the delay is too big\n {\n delay_array[number_position] = *ch;\n number_position += 1;\n }\n else\n {\n delay_array[0] = '+'; // '+' used to check if the delay is too big in my_atoi\n }\n }\n else if (*ch == '-')\n {\n sequence_array[sequence_position] = UINT_MAX; // used for saying reset should happen\n sequence_position += 1;\n break; // no point checking delay times beyond where reset happens\n }\n }\n while (*ch != EOF && *ch != '\\n') // finish reading line if it's not already read\n {\n *ch = fgetc(my_file);\n }\n if (sequence_array[sequence_position - 1] != UINT_MAX) // numbers entered and not a reset-all-sequences file\n {\n for (unsigned int i = sequence_position - 1; i > 1 && sequence_array[i] == 0; i--) // don't copy pointless zeros\n {\n sequence_position -= 1;\n }\n }\n return sequence_position;\n}\n\nstatic unsigned char set_keys_and_values(kh_khStrInt_t *my_khash_map, FILE *my_file, size_t longest_name, size_t longest_sequence, unsigned char longest_delay, unsigned int line_count, unsigned int max_power_of_ten, unsigned char digits_in_uint)\n{\n khiter_t khash_map_iter;\n char *name_array = (char*)malloc(longest_name); // array for filename text. Always greater than 0, shouldn't return NULL.\n unsigned int *sequence_array = (unsigned int*)malloc(longest_sequence * sizeof(unsigned int)); // array for delay sequence. Always greater than 0, shouldn't return NULL.\n char *delay_array = (char*)malloc(longest_delay); // array for delay text. Always greater than 0, shouldn't return NULL.\n if (name_array == NULL || sequence_array == NULL || delay_array == NULL)\n {\n return 0;\n }\n if ((size_t)(UINT_MAX / 2) < line_count) // khash resizes by powers of two, so if line_count is this big then khash can't resize any bigger\n {\n kh_resize(khStrInt, my_khash_map, UINT_MAX);\n }\n else\n {\n kh_resize(khStrInt, my_khash_map, (unsigned int)((line_count / 0.7) + 1)); // khash map will always be at 70% or less capacity\n }\n sequence_array[0] = 2; // first index stores length of array\n sequence_array[1] = 2; // second index stores what the next delay to use in the sequence is\n size_t chars_to_copy;\n unsigned int numbers_to_copy;\n char ch = '\\0';\n while (ch != EOF)\n {\n chars_to_copy = read_name(my_file, &ch, name_array); // accounts for null character\n if (ch != EOF && ch != '\\n') // checks if the line had a delay sequence. If it didn't, moves on to next line\n {\n numbers_to_copy = read_sequence(my_file, &ch, delay_array, sequence_array, max_power_of_ten, digits_in_uint);\n if (numbers_to_copy > 2) // read_sequence returns 2 if either the sequence was pointless or the user didn't enter anything for it\n {\n int ret;\n sequence_array[0] = numbers_to_copy;\n char *key_for_khash = (char*)malloc(chars_to_copy); // always greater than 0, shouldn't return NULL\n unsigned int *value_for_khash = (unsigned int*)malloc(numbers_to_copy * sizeof(unsigned int)); // always greater than 0, shouldn't return NULL\n if (key_for_khash == NULL || value_for_khash == NULL)\n {\n return 0;\n }\n for (size_t i = 0; i < chars_to_copy; i++)\n {\n key_for_khash[i] = name_array[i];\n }\n for (unsigned int i = 0; i < numbers_to_copy; i++)\n {\n value_for_khash[i] = sequence_array[i];\n }\n khash_map_iter = kh_put(khStrInt, my_khash_map, key_for_khash, &ret);\n kh_val(my_khash_map, khash_map_iter) = value_for_khash;\n }\n }\n sequence_array[0] = 2;\n sequence_array[1] = 2;\n }\n free((char*)name_array);\n name_array = NULL;\n free((unsigned int*)sequence_array);\n sequence_array = NULL;\n free((char*)delay_array);\n delay_array = NULL;\n return 1;\n}\n\nstatic unsigned char prepare_to_setup(kh_khStrInt_t *my_khash_map, FILE *my_file, size_t *longest_name, size_t *longest_sequence, unsigned char *longest_delay, unsigned int *line_count)\n{\n unsigned int max_power_of_ten = 1; // biggest power of 10 less than UINT_MAX, used in my_atoi\n unsigned char digits_in_uint = 1; // how many digits are in UINT_MAX, used for helping to see if a delay is too big\n for (; UINT_MAX / max_power_of_ten > 9; max_power_of_ten *= 10)\n {\n digits_in_uint += 1;\n }\n check_file(my_file, longest_name, longest_sequence, longest_delay, line_count, digits_in_uint);\n if (fseek(my_file, 0, SEEK_SET) != 0)\n {\n printf(\"fseek on files_and_delays.txt failed\\n\");\n return 0;\n }\n // longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints\n if (*line_count == UINT_MAX) // check_file will return UINT_MAX if something is too big\n {\n printf(\"filename, delay, delay sequence, and/or number of files is too big\\n\");\n return 0;\n }\n unsigned char khash_succeeded = set_keys_and_values(my_khash_map, my_file, *longest_name, *longest_sequence, *longest_delay, *line_count, max_power_of_ten, digits_in_uint);\n if (khash_succeeded == 0) // set_keys_and_values returns 0 if malloc fails\n {\n printf(\"malloc failed in set_keys_and_values\\n\");\n return 0;\n }\n return 1;\n}\n\nHere's the code for Windows:\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}\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\nload_extender_dll.cpp:\n#include <string>\n#include <mutex>\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\nnamespace rh = robin_hood;\n\n// included here so alias can be used\n#include \"rh_map_setup_header.h\"\n\nstatic class rh_map_handler // this is used to free all the unsigned int array memory when the program ends\n{\npublic:\n rh::unordered_flat_map<std::wstring, unsigned int*> obj_map;\n\n ~rh_map_handler()\n {\n for (auto it = obj_map.begin(); it != obj_map.end();)\n {\n free((unsigned int*)it->second);\n it->second = NULL;\n it = obj_map.erase(it); // erasing so obj_map's destructor doesn't have to do as much\n }\n }\n};\n\n// my_map_handler is global so it will free all the unsigned int arrays when the program ends\n// my_rh_map and mtx are global so the NtOpenFile hook function can see them\nstatic rh_map_handler my_map_handler;\nstatic rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map = my_map_handler.obj_map;\nstatic std::mutex mtx;\n\nstatic unsigned char rh_map_setup()\n{\n FILE* my_file = NULL;\n if (fopen_s(&my_file, \".\\\\files_and_delays.txt\", \"r\") != 0)\n {\n return 0;\n }\n size_t longest_name = 1; // starts at 1 for null character\n size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence\n unsigned char longest_delay = 1; // starts at 1 for null character\n size_t line_count = 1; // starts at 1 because there's always at least 1 line\n unsigned char rh_map_succeeded = prepare_to_setup(my_rh_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);\n if (my_file != NULL) // this makes a warning go away\n {\n fclose(my_file);\n }\n if (rh_map_succeeded == 0) // rh map failed to be made. Error message is printed in rh_map_setup_header in prepare_to_setup.\n {\n return 0;\n }\n return 1;\n}\n\nstatic unsigned char SETUP_SUCCEEDED = rh_map_setup(); // if this is 0 then the hook function skips to calling the real function\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 if (SETUP_SUCCEEDED == 1) // skip to calling original NtOpenProcess if setup failed\n {\n std::wstring file_path = ObjectAttributes->ObjectName->Buffer;\n // +1 so '\\' isn't included. If '\\' not found in path, the whole wstring is checked because npos is -1\n std::wstring file_name = file_path.substr(file_path.rfind(L\"\\\\\") + 1);\n rh::unordered_flat_map<std::wstring, unsigned int*>::const_iterator rh_map_iter = my_rh_map.find(file_name);\n if (rh_map_iter != my_rh_map.end()) // key found\n {\n unsigned int* delay_sequence = rh_map_iter->second;\n mtx.lock(); // don't let other threads change delay sequence when it's being read or changed\n if (delay_sequence[2] == UINT_MAX) // reset all delay sequences\n {\n for (auto& it : my_rh_map)\n {\n it.second[1] = 2;\n }\n mtx.unlock();\n }\n else if (delay_sequence[1] < delay_sequence[0])\n {\n if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence\n {\n delay_sequence[1] = 2;\n }\n unsigned int sleep_time = delay_sequence[delay_sequence[1]];\n delay_sequence[1] += 1;\n mtx.unlock();\n Sleep(sleep_time);\n }\n else // delay sequence already finished\n {\n mtx.unlock();\n }\n }\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_test.cpp:\n#include <tchar.h>\n#include <Windows.h>\n#include <iostream>\n#include <string>\n#include <mutex>\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\nnamespace rh = robin_hood;\n\n// included here so alias can be used\n#include \"rh_map_setup_header.h\"\n\nstatic class rh_map_handler // this is used to free all the unsigned int array memory when the program ends\n{\npublic:\n rh::unordered_flat_map<std::wstring, unsigned int*> obj_map;\n\n ~rh_map_handler()\n {\n for (auto it = obj_map.begin(); it != obj_map.end();)\n {\n free((unsigned int*)it->second);\n it->second = NULL;\n it = obj_map.erase(it); // erasing so obj_map's destructor doesn't have to do as much\n }\n }\n};\n\n// my_map_handler is global so it will free all the unsigned int arrays when the program ends\n// my_rh_map and mtx are global so the NtOpenFile hook function can see them\nstatic rh_map_handler my_map_handler;\nstatic rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map = my_map_handler.obj_map;\nstatic std::mutex mtx;\n\nstatic unsigned char rh_map_setup()\n{\n FILE* my_file = NULL;\n if (fopen_s(&my_file, \".\\\\files_and_delays.txt\", \"r\") != 0)\n {\n printf(\"error opening files_and_delays.txt\\n\");\n return 0;\n }\n size_t longest_name = 1; // starts at 1 for null character\n size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence\n unsigned char longest_delay = 1; // starts at 1 for null character\n size_t line_count = 1; // starts at 1 because there's always at least 1 line\n unsigned char rh_map_succeeded = prepare_to_setup(my_rh_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);\n if (my_file != NULL) // this makes a warning go away\n {\n fclose(my_file);\n }\n if (rh_map_succeeded == 0) // rh map failed to be made. Error message is printed in rh_map_setup_header in prepare_to_setup.\n {\n return 0;\n }\n printf(\"\\nlongest filename (plus null character and whitespace in file): %zu\\n\"\n \"longest delay sequence (+2 for current delay and sequence length): %zu\\n\"\n \"most digits in delay (+1 for null character, max delay is UINT_MAX): %u\\n\"\n \"lines in file (overestimates slightly): %zu\\n\", longest_name, longest_sequence, longest_delay, line_count);\n return 1;\n}\n\nstatic unsigned char SETUP_SUCCEEDED = rh_map_setup(); // if this is 0 then the hook function skips to calling the real function\n\nstatic void NtOpenFile_test(std::wstring file_path)\n{\n if (SETUP_SUCCEEDED == 1) // skip to calling original NtOpenFile if setup failed\n {\n // +1 so '\\' isn't included. If '\\' not found in path, the whole wstring is checked because npos is -1\n std::wstring file_name = file_path.substr(file_path.rfind(L\"\\\\\") + 1);\n rh::unordered_flat_map<std::wstring, unsigned int*>::const_iterator rh_map_iter = my_rh_map.find(file_name);\n if (rh_map_iter != my_rh_map.end()) // key found\n {\n unsigned int* delay_sequence = rh_map_iter->second;\n printf(\"%ls successfully found in hash map\\n\", file_name.c_str());\n mtx.lock(); // don't let other threads change delay sequence when it's being read or changed\n if (delay_sequence[2] == UINT_MAX) // reset all delay sequences\n {\n for (auto& it : my_rh_map)\n {\n it.second[1] = 2;\n }\n mtx.unlock();\n printf(\"all delay sequences reset\\n\");\n }\n else if (delay_sequence[1] < delay_sequence[0])\n {\n if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence\n {\n delay_sequence[1] = 2;\n printf(\"%ls delay sequence reset\\n\", file_name.c_str());\n }\n unsigned int sleep_time = delay_sequence[delay_sequence[1]];\n delay_sequence[1] += 1;\n mtx.unlock();\n //Sleep(sleep_time);\n printf(\"sleep for %u second(s) and %u millisecond(s)\\n\", sleep_time / 1000, sleep_time % 1000);\n }\n else // delay sequence already finished\n {\n mtx.unlock();\n printf(\"%ls delay sequence already finished\\n\", file_name.c_str());\n }\n }\n else // key not found\n {\n printf(\"%ls not found in khash map\\n\", file_name.c_str());\n }\n }\n // NtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions);\n}\n\nstatic size_t find_longest_input_length(FILE* test_input) // find how much space to give to array used to hold input\n{\n size_t longest_input = 1;\n size_t current_input = 1; // starts at 1 for null character\n wchar_t ch = L'\\0';\n while (ch != WEOF && current_input < SIZE_MAX)\n {\n ch = fgetwc(test_input);\n if (ch == L'\\n' || ch == WEOF)\n {\n if (current_input > longest_input)\n {\n longest_input = current_input;\n }\n current_input = 1;\n }\n else\n {\n current_input += 1;\n }\n }\n if (current_input == SIZE_MAX)\n {\n return SIZE_MAX; // a test path was too big\n }\n return longest_input;\n}\n\nstatic void print_rh_map()\n{\n printf(\"\\n---------- khash map current state ----------\\n\");\n for (auto& it : my_rh_map)\n {\n printf(\"%ls / \", it.first.c_str());\n unsigned int* sequence_to_print = it.second;\n for (unsigned int i = 0; i < sequence_to_print[0]; i++)\n {\n if (sequence_to_print[i] == UINT_MAX) // it's a reset point\n {\n printf(\"RESET\"); // it doesn't need a space because the line always ends here\n }\n else\n {\n printf(\"%u \", sequence_to_print[i]);\n }\n }\n printf(\"\\n\");\n }\n printf(\"---------------------------------------------\\n\\n\");\n}\n\nstatic void test_all_inputs(FILE* test_input, size_t longest_input)\n{\n wchar_t* input_array = (wchar_t*)malloc(longest_input * sizeof(wchar_t)); // find_longest_input_length accounts for null character. Always greater than 0, shouldn't return NULL\n if (input_array == NULL)\n {\n printf(\"malloc failed in test_all_inputs\\n\");\n return;\n }\n size_t ch_position = 0;\n wchar_t ch = L'\\0';\n while (ch != WEOF)\n {\n ch = fgetwc(test_input);\n if (ch == L'\\n' || ch == WEOF)\n {\n input_array[ch_position] = L'\\0';\n ch_position = 0;\n if (ch != WEOF) // avoids extra test\n {\n printf(\"testing NtOpenFile input: %ls\\n\", input_array);\n NtOpenFile_test((std::wstring)input_array);\n print_rh_map();\n }\n }\n else\n {\n input_array[ch_position] = ch;\n ch_position += 1;\n }\n }\n free((wchar_t*)input_array);\n input_array = NULL;\n}\n\nstatic void get_exit_input()\n{\n printf(\"Press Enter to exit\\n\");\n std::wstring input;\n std::getline(std::wcin, input);\n}\n\nstatic int _tmain(int argc, _TCHAR* argv[])\n{\n LPCWSTR lpApplicationName = argv[0];\n DWORD lpBinaryType;\n if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0)\n {\n printf(\"\\nERROR: couldn't read if this file is 32 bit or 64 bit\\n\");\n get_exit_input();\n return 1;\n }\n else if (lpBinaryType != 0)\n {\n printf(\"\\nError: this file was incorrectly identified as not 32-bit\\n\");\n get_exit_input();\n return 1;\n }\n else\n {\n printf(\"\\nthis file was correctly identified as 32-bit\\n\");\n }\n FILE* test_input;\n if (fopen_s(&test_input, \".\\\\test_input.txt\", \"r\") != 0)\n {\n printf(\"error opening test_input.txt\\n\");\n get_exit_input();\n return 1;\n }\n size_t longest_input = find_longest_input_length(test_input);\n if (longest_input == SIZE_MAX) // check_file will return SIZE_MAX if a test path is too big\n {\n printf(\"a test path is too big\\n\");\n if (test_input != NULL) // this makes a warning go away\n {\n fclose(test_input);\n }\n get_exit_input();\n return 1;\n }\n // test_input != NULL check makes warning go away\n if (test_input != NULL && fseek(test_input, 0, SEEK_SET) != 0)\n {\n printf(\"fseek on test_input.txt failed\\n\");\n if (test_input != NULL) // this makes a warning go away\n {\n fclose(test_input);\n }\n get_exit_input();\n return 1;\n }\n printf(\"\\nlongest test path (+1 for null character): %zu\\n\", longest_input);\n printf(\"\\ntest start\\n\");\n print_rh_map();\n test_all_inputs(test_input, longest_input);\n if (test_input != NULL) // this makes a warning go away\n {\n fclose(test_input);\n }\n get_exit_input();\n return 0;\n}\n\nrh_map_setup_header:\n#include <stdint.h>\n\n// printf calls are used for debugging in load_extender_test.exe\n\nstatic unsigned char TOO_BIG_DELAY_SEEN = 0; // used so user won't be alerted more than once that they entered a delay that's too big\n\n// checks line count to know how much space to give to robin_hood map\n// updates longest_name and longest_sequence to know how much space to give to arrays used to hold key and value\nstatic void check_file(FILE* my_file, size_t* longest_name, size_t* longest_sequence, unsigned char* longest_delay, size_t* line_count, unsigned char digits_in_uint, size_t map_max_size)\n{\n unsigned char checking_sequence = 0; // 0 if checking a filename's length, 1 if checking a delay sequence's length\n size_t current_name = 1; // starts at 1 for null character\n size_t current_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence\n unsigned char current_delay = 1; // starts at 1 for null character\n wchar_t ch = L'\\0';\n // longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints\n while (ch != WEOF && current_name < SIZE_MAX && current_sequence < (SIZE_MAX / sizeof(unsigned int)) && *line_count < SIZE_MAX && current_sequence < UINT_MAX)\n {\n ch = fgetwc(my_file);\n if (ch == WEOF || ch == L'\\n')\n {\n if (checking_sequence == 1)\n {\n if (current_delay > * longest_delay)\n {\n *longest_delay = current_delay;\n }\n if (current_sequence > * longest_sequence)\n {\n *longest_sequence = current_sequence;\n }\n checking_sequence = 0;\n current_sequence = 3;\n current_delay = 1;\n }\n *line_count += 1; // if for some reason there are a lot of hash collisions, the user can put empty lines in files_and_delays.txt to try to fix it\n current_name = 1;\n }\n else if (ch == L'/')\n {\n if (checking_sequence == 0)\n {\n if (current_name > * longest_name)\n {\n *longest_name = current_name;\n }\n checking_sequence = 1;\n }\n else\n {\n if (current_delay > * longest_delay)\n {\n *longest_delay = current_delay;\n }\n current_sequence += 1;\n current_delay = 1;\n }\n }\n else if (checking_sequence == 0)\n {\n current_name += 1;\n }\n // ignores non-digits and leading zeros. maximum space is digits_in_uint + 1. +1 is for null character\n else if (((ch >= 49 && ch <= 57) || (ch == 48 && current_delay > 1)) && current_delay < digits_in_uint + 1)\n {\n current_delay += 1;\n }\n }\n if (current_name == SIZE_MAX ||\n current_sequence == (SIZE_MAX / sizeof(unsigned int)) ||\n current_sequence == UINT_MAX\n || *line_count > map_max_size)\n {\n *line_count = SIZE_MAX; // something was too big\n }\n}\n\n// reads the next filename and writes it in name_array\nstatic void read_name(FILE* my_file, wchar_t* ch, wchar_t* name_array)\n{\n size_t ch_position = 0;\n *ch = fgetwc(my_file);\n while (*ch != WEOF && *ch != L'\\n' && *ch != L'/')\n {\n name_array[ch_position] = *ch;\n ch_position += 1;\n *ch = fgetwc(my_file);\n }\n name_array[ch_position] = L'\\0';\n if (*ch == L'/') // filename given and line didn't end abruptly\n {\n for (; ch_position > 0 && (name_array[ch_position - 1] == L' ' || name_array[ch_position - 1] == L'\\t'); ch_position--)\n {\n name_array[ch_position - 1] = L'\\0'; // remove whitespace between '/' and end of filename if the user has it written like that\n }\n }\n}\n\nstatic unsigned int my_atoi(wchar_t* delay_array, unsigned int max_power_of_ten, unsigned char digits_in_uint, unsigned char number_position)\n{\n unsigned char delay_too_big = 0;\n unsigned int current_power_of_ten = 1;\n unsigned int accumulator = 0;\n if (delay_array[0] == L'\\0') // no digits found, assume delay is 0\n {\n return 0;\n }\n // delay has more digits than UINT_MAX or it has as many digits and the most significant digit is bigger in the delay than in UINT_MAX\n else if (delay_array[0] == L'+' || (number_position == digits_in_uint && delay_array[0] - 48 > UINT_MAX / max_power_of_ten))\n {\n delay_too_big = 1;\n }\n else\n {\n number_position -= 1;\n for (; number_position > 0; number_position--) // sum everything except most significant digit\n {\n accumulator += ((delay_array[number_position] - 48) * current_power_of_ten);\n current_power_of_ten *= 10;\n }\n // checking that adding final value won't make accumulator overflow\n // delay_array[0] won't be bigger than UINT_MAX / max_power_of_ten here because the other else if block checks for that\n if (current_power_of_ten == max_power_of_ten && UINT_MAX - ((delay_array[0] - 48) * max_power_of_ten) - 1 < accumulator)\n {\n delay_too_big = 1;\n }\n else\n {\n accumulator += ((delay_array[0] - 48) * current_power_of_ten);\n }\n }\n if (delay_too_big == 1)\n {\n if (TOO_BIG_DELAY_SEEN == 0)\n {\n printf(\"\\nWARNING: maximum delay time is %u\\n\", UINT_MAX - 1);\n TOO_BIG_DELAY_SEEN = 1; // TOO_BIG_DELAY_SEEN only changed here\n }\n return UINT_MAX - 1;\n }\n return accumulator;\n}\n\n// reads the next delay sequence and writes it in sequence_array\n// also returns how many numbers are in the sequence so the right amount will be copied into the array given to robin_hood map\n// there can't be more than UINT_MAX delays in one sequence\nstatic unsigned int read_sequence(FILE* my_file, wchar_t* ch, wchar_t* delay_array, unsigned int* sequence_array, unsigned int max_power_of_ten, unsigned char digits_in_uint)\n{\n unsigned char number_position = 0; // next digit in current delay time. Also used in my_atoi to see if delay is too big\n size_t sequence_position = 2; // starts at 2 because first two indexes are used to store sequence length and what the next delay is\n delay_array[0] = L'\\0'; // initializing to use in condition\n while (*ch != WEOF && *ch != L'\\n')\n {\n *ch = fgetwc(my_file);\n if (*ch == WEOF || *ch == L'\\n')\n {\n delay_array[number_position] = L'\\0';\n unsigned int last_delay = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input\n if (last_delay != 0) // no point adding 0 as final delay time\n {\n sequence_array[sequence_position] = last_delay;\n sequence_position += 1;\n }\n }\n else if (*ch == L'/') // end of current delay, about to read next delay\n {\n delay_array[number_position] = L'\\0';\n sequence_array[sequence_position] = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input\n sequence_position += 1;\n number_position = 0;\n }\n // ch is a digit and the digit isn't a leading zero and the maximum delay isn't reached\n else if (((*ch >= 49 && *ch <= 57) || (*ch == 48 && number_position > 0)) && delay_array[0] != L'+')\n {\n if (number_position != digits_in_uint) // if it's already equal to digits_in_uint then the delay is too big\n {\n delay_array[number_position] = *ch;\n number_position += 1;\n }\n else\n {\n delay_array[0] = L'+'; // '+' used to check if the delay is too big in my_atoi\n }\n }\n else if (*ch == L'-')\n {\n sequence_array[sequence_position] = UINT_MAX; // used for saying reset should happen\n sequence_position += 1;\n break; // no point checking delay times beyond where reset happens\n }\n }\n while (*ch != WEOF && *ch != L'\\n') // finish reading line if it's not already read\n {\n *ch = fgetwc(my_file);\n }\n if (sequence_array[sequence_position - 1] != UINT_MAX) // numbers entered and not a reset-all-sequences file\n {\n for (unsigned int i = sequence_position - 1; i > 1 && sequence_array[i] == 0; i--) // don't copy pointless zeros\n {\n sequence_position -= 1;\n }\n }\n return sequence_position;\n}\n\nstatic unsigned char set_keys_and_values(rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map, FILE* my_file, size_t longest_name, size_t longest_sequence, unsigned char longest_delay, size_t line_count, unsigned int max_power_of_ten, unsigned char digits_in_uint)\n{\n wchar_t* name_array = (wchar_t*)malloc(longest_name * sizeof(wchar_t)); // array for filename text. Always greater than 0, shouldn't return NULL. Null character is accounted for.\n unsigned int* sequence_array = (unsigned int*)malloc(longest_sequence * sizeof(unsigned int)); // array for delay sequence. Always greater than 0, shouldn't return NULL.\n wchar_t* delay_array = (wchar_t*)malloc(longest_delay * sizeof(wchar_t)); // array for delay text. Always greater than 0, shouldn't return NULL.\n if (name_array == NULL || sequence_array == NULL || delay_array == NULL)\n {\n return 0;\n }\n my_rh_map.reserve(line_count);\n sequence_array[0] = 2; // first index stores length of array\n sequence_array[1] = 2; // second index stores what the next delay to use in the sequence is\n size_t chars_to_copy;\n unsigned int numbers_to_copy;\n wchar_t ch = L'\\0';\n while (ch != WEOF)\n {\n read_name(my_file, &ch, name_array); // puts characters in name_array\n if (ch != WEOF && ch != L'\\n') // checks if the line had a delay sequence. If it didn't, moves on to next line\n {\n numbers_to_copy = read_sequence(my_file, &ch, delay_array, sequence_array, max_power_of_ten, digits_in_uint);\n if (numbers_to_copy > 2) // read_sequence returns 2 if either the sequence was pointless or the user didn't enter anything for it\n {\n sequence_array[0] = numbers_to_copy;\n unsigned int* value_for_rh = (unsigned int*)malloc(numbers_to_copy * sizeof(unsigned int)); // always greater than 0, shouldn't return NULL\n if (value_for_rh == NULL)\n {\n return 0;\n }\n std::wstring key_for_rh(name_array); // null character added to name_array in read_name function\n for (unsigned int i = 0; i < numbers_to_copy; i++)\n {\n value_for_rh[i] = sequence_array[i];\n }\n my_rh_map[key_for_rh] = value_for_rh;\n }\n }\n sequence_array[0] = 2;\n sequence_array[1] = 2;\n }\n free((wchar_t*)name_array);\n name_array = NULL;\n free((unsigned int*)sequence_array);\n sequence_array = NULL;\n free((wchar_t*)delay_array);\n delay_array = NULL;\n return 1;\n}\n\nstatic unsigned char prepare_to_setup(rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map, FILE* my_file, size_t* longest_name, size_t* longest_sequence, unsigned char* longest_delay, size_t* line_count)\n{\n unsigned int max_power_of_ten = 1; // biggest power of 10 less than UINT_MAX, used in my_atoi\n unsigned char digits_in_uint = 1; // how many digits are in UINT_MAX, used for helping to see if a delay is too big\n for (; UINT_MAX / max_power_of_ten > 9; max_power_of_ten *= 10)\n {\n digits_in_uint += 1;\n }\n size_t map_max_size = my_rh_map.max_size();\n check_file(my_file, longest_name, longest_sequence, longest_delay, line_count, digits_in_uint, map_max_size);\n if (fseek(my_file, 0, SEEK_SET) != 0)\n {\n printf(\"fseek on files_and_delays.txt failed\\n\");\n return 0;\n }\n // longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints\n if (*line_count == SIZE_MAX) // check_file will return UINT_MAX if something is too big\n {\n printf(\"filename, delay, delay sequence, and/or number of files is too big\\n\");\n return 0;\n }\n unsigned char rh_succeeded = set_keys_and_values(my_rh_map, my_file, *longest_name, *longest_sequence, *longest_delay, *line_count, max_power_of_ten, digits_in_uint);\n if (rh_succeeded == 0) // set_keys_and_values returns 0 if malloc fails\n {\n printf(\"malloc failed in set_keys_and_values\\n\");\n return 0;\n }\n return 1;\n}\n```\n\n" |
This is a class representing an exponent. Its main purpose is to deal with logarithmic quantities.
template<std::floating_point Representation>
class Exponent
{
public:
using representation = Representation;
struct Literal{};
constexpr explicit Exponent(representation val, Literal):m_val{v... |
I wrote a desktop application in java (with JavaFX). Program first find given title in Imdb via: https://imdb-internet-movie-database-unofficial.p.rapidapi.com and then when user select a movie, search in the pirate bay site for magnets link, seeds and leechers.
Here is an example:
Here are two classes:
ImdbFinder
pac... |
update: a new version of this code is posted here
With this post, i would like to 1) ask for feedback on below code as it stands:
do i apply all best practices for c++20?
is it safe?
is my way to update a callback from inside a running callback sensible/best?
Based on code and design advice found on stackoverflow (e... |
This is a follow-up question for A recursive_copy_if Template Function Implementation in C++. Besides the recursive version std::ranges::copy_if, I am trying to implement a recursive version std::replace_copy_if.
The experimental implementation
The experimental implementation is as below.
// recursive_replace_copy_if ... |
Background
Given some random array of numbers like [3, 5, -4, 8, 11, 1, -1, 6] and a target value 10, find two numbers within the array that equal to the target value.
Code
def two_Number_Sum(array, target):
unique_number_set = set()
for num in array:
required_value = target - num
if required_va... |
Please consider evaluating the code below for best practices, efficiency, and mistakes. I got some of the code from W3 schools (I know, I know, but they've come a long way) and assimilated it to what I need. Particularly, the days = hours = minutes = seconds = 0; is likely going to cause people stress but after researc... |
I'm a new programmer and I'm periodically going into the Intro To Algorithms CLRS textbook and trying to translate pseudocode into Ruby for skill practice. This is my implementation/translation of insertion sort.
I'm looking for feedback on readability as well as efficiency.
Pseudocode is found on page 17 of Intro To A... |
$spotify_track = '1HbcclMpw0q2WDWpdGCKdS';
$client_id = '[my_id]';
$client_secret = '[my_secret]';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://accounts.spotify.com/api/token' );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_POST, ... |
I've written the following sample program as a way to help improve my understanding of passing pointers to a function, and it currently works:
#include "stdio.h"
typedef struct Car {
char* name;
unsigned int price;
} Car;
void print_cars(Car* cars[]) {
for (int i=0; cars[i] != NULL;i++) {
... |
I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve.
int firstNumber;
string sign;
int secondNumber;
int answer;
Console.WriteLine("Input Number:");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.Cle... |
There are 2 issues with my code:
a) If I put numbers in the following order (as my input) '1', '2', '3', '4',
'5', '6', '7' -- this where the game should end, because X (or O) would have
won now (because 3, 5, 7 are a diagonal win). But my program realizes this
after X (or again, O) plays their 4th turn (another turn i... |
I'm implementing a simple data reader to get image sequences from either a pre-recorded video file (In my case ROS bag file), or a camera device (In my case Intel Realsense). Basically I intend for users to use it in the following way:
When a non-empty file path is provided, the reader reads from the video file; other... |
I wanted to check and see if this was as efficient as can be. The goal is to get a user's data from a group of documents that contains references to users in Firestore.
ngOnInit
this.links = this.currentUserRef.collection('links', ref => ref.where('pendingRequest', '==', false)).get()
.pipe(map(querySnap =>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.