instruction
stringlengths
71
95.1k
I have written a Python function to solve the Dig Pow problem, where the goal is to find a number k such that the sum of each digit of n raised to a specific and increasing power equals n * k. Here is my current code: def dig_pow(n, p): if n != int(n): return -1 stockn = n tab = [] while n > 0:...
I have written a Python function called comp that checks whether two given arrays have the same elements, with the same multiplicities. The multiplicity of a member is the number of times it appears in the array. I would like to post my code here for review, so that I can optimize it and receive any advice on how to im...
I am creating a binary file format to store a series of vectors alongside some metadata. The vectors will be stored at the start of the file which will have a predetermined size, and the metadata alongside the size of each vector will go to the end. data = {{1, 2, 3}, {5, 6, 7}} metadata = {'1011', '1110'} file: --> 1...
I have a python script with different classes performing various tasks. There is one class that performs heavy computations that are needed by other classes. I am using multiprocessing in order to do these computations in parallel and providing them to the other classes when available. The Engine class is the process t...
I've been away from Programming and the Tech Industry for sometime. I thought I'd look at and try some of the older basic stuff. I bushed up to QuickSort and found most existing implementations of it, in Texts and on the web, to be a little convoluted. So I tried to simplify the implementation to be more in line with t...
I have my solution for the below usecase but I would like to know whether is any other effective solution for the same. My Data: const myArr = [{ data: { studyUId: 'abc', seriesData: [ { seriesUId: "123", modality: "VX"}, { seriesUId: "ef3", modality: "GX"} ] } }, { data: { studyUId: 'fgh', series...
I have written a Python script that turns a gigantic text file into a SQLite3 database. The text file is truly gigantic, it is 133MiB or 140,371,572 bytes in size, and contains 140,371,572 characters and 5,558,701 lines. The text file contains a list of all registered autonomous system numbers and their names, followed...
Here is my implementation of a lock free queue using CompareAndSwap operation. type LockFreeQueue struct { capacity int list []int top int32 numPopOps int32 } func (lfq *LockFreeQueue) Pop() (value int, empty bool) { for { top := atomic.LoadInt32(&lfq.top) if top == -1 ...
Overview HTML Editor is an online HTML editor with a minimalist approach. Edit your HTML, CSS, and JavaScript code and monitor the instant live preview. It can also create, open and edit other types of text files such as .txt, .css, .js, .svg, etc. Please review the source code and provide feedback. Source code var r...
I have a form type that I use several times throughout my project, and I've noticed that, rather than making the form replicable, I've just copied and pasted it a few times and made slight adjustments to it to fit each of my needs. Below is an example of what this form might look like: const initValues = { email: '',...
I've written a function that takes two arrays of integers as input and removes all the elements in the first array that are also present in the second array. I would like to share my code with you and kindly request your feedback for potential improvements. Please find my code implementation below, and any suggestions ...
Firstly the goal of this code is a little more complex than in this post and the other invoice questions are C# Is there anything that just pops out as immeadiately unpythonic/wrong ? I have a few questions that are written in the code in the comments pertaining to specific issues in the code. (Denoted by the '?' at th...
I have made a Movies App with Vue 3, TypeScript and The Movie Database (TMDB) API. For aesthetics, I rely on Bootstrap 5. In src\App.vue I have: <template> <TopBar /> <router-view /> <AppFooter /> </template> <script lang="ts"> import { defineComponent } from 'vue'; // Import components import TopBar fro...
I wanted to create a data class that is strongly typed, and behaves both like a namedtuple and dict. It should check the data types of the variables used to initialize it, and should support indexing in the style of sequences, therefore it should also be iterable and support type casting to list. It should also support...
My work has an isolated network that developers write applications to run inside of. These developers often write Python code. This Python code often requires modules from the Python Package Index (PyPi) to be downloaded using something like pip. In order to allow these developers to run their software on this isolated...
Since last month I have been practicing python, and yesterday I tried to make a simple app that reads a random list of players and based on that it makes a random fight between 2 random players. I dont know if there is something that I can change to make the program be better. Something I tried to do, was to make the p...
Sometimes I find I want to call a function passing each of a set of types as a template parameter, but without needing to construct an object of those types. I also may want to do this in multiple places, or have a class that holds a tuple of these types, but I want to have this type list defined in a single place, not...
I made a simple connect four terminal game in C and was wondering if I could get feedback on it. I mainly want to know where pointers could have optimised my code, and if there are any major redundancies. ( I know that the is_occupied function is one, but I added that for readability) Here is the code: /* simple conne...
The objective is simple: List all possible permutations for a given a String. I looked at some implementations from popular sources. I decided to build this to the flow: The Code for Review package com.progint; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.BufferedReader...
I am trying to detect the content/mime type of a given Buffer/string. In other words, I am trying to guess what on earth is a given string. My approach is somewhat brute-force: /** * Check if valid url encoded. * For now I set the value as true * @param {String} body * @returns {Boolean} */ const isValidFormUrlEn...
I've created Snake in Console. I've tried to make my code as good as I possibly could. (Code on github: https://github.com/bartex-bartex/SnakeCSharp) Question Is my coding style good enough, so I can move to creating another project while not repeating some blunders I've made here? Program.cs using SnakeGame; Game gam...
The task is writing a function, which checks if a string contains only unique characters. Means: is each character is included only one time. Here's the solution, I have developed: func areAllLettersUnique(_ str: String) -> Bool { let arr = str.split(separator: "") for (i, chr) in arr.enumerated() { if ...
I have this repository. The idea is that there is a file tags sitting in the users home directory, and which contains the tag declarations of the format <tag> <directory>. For example, the tags file may look like: home C:\Users\bob docs C:\Users\bob\Documents down C:\Users\bob\Downloads croot C:\ Now, when the user ty...
I'm new on C++ and OOP. I wrote the following QuadTree implementation (I didn't wrote the remove object part yet). please take a look on it and provide feedback, mainly about C++ OOP design, seperating my code to files, public vs. privte, shared_pt and etc... QuadTree.h: #pragma once #include <iostream> #include <utili...
I have created a SingleDivUI chart library with CSS. Here the idea is to create the UI components with a single div element by CSS. To explore the power of CSS and to bring some innovative thoughts I started to reserch on this, finally I can make the fully usable Chart component with a lot of customization. Here is the...
I've made a python game called 2d minecraft (guess where I got the idea) that has an infinite chunk system. I believe the idea I have is alright but my coding is bad and I have tried to improve it as much as I can before posting here. Here is the code: import pygame # set up variables title, size = "2d_MC", (1365, 705...
This is a follow-up question for A recursive_sum Template Function Implementation with Unwrap Level in C++ and A recursive_reduce_all Template Function Implementation in C++. Considering the answer provided by G. Sliepen: Make it more generic Summing is a very specific operation. What if you want to calculate the prod...
I have written a script for CVE-2023-24932 like below. But I want to improve my script. I am open to new ideas. Here is my script: $DBXUpdateSuccess = Get-EventLog -LogName System -Source "Microsoft-Windows-TPM-WMI" -InstanceId 1035 -ErrorAction SilentlyContinue if ($DBXUpdateSuccess){ Write-Host "Patch has been ...
After reviewing my previous question I came up with this pagination function. On my first approach I wrote a class thinking about IDE's code assist and the review wasn't positive. In this function I decided to return a stdClass object with necessary properties. I have my concerns about the output approach. I want one f...
I've written code for a program that reads a text file, checking if there's any capitalized parts of speech of specific types (noun, adj, verb, adv) in the text and replace them with the user's chosen word for that category. Below is an example of how it the result should be: Original: "The ADJECTIVE, ADJECTIVE, and A...
Recently I made a point dataclass and a point_calc class which performs various commonly used algorithms on a point. from dataclasses import dataclass import math EPS = 7./3 - 4./3 -1 #note 7./3 - 4./3 -1: https://stackoverflow.com/questions/19141432/python-numpy-machine-epsilon @dataclass class point: x: ...
My problem I am working with two objects, structured as follows: test <- structure(list(rs1_A = c(0.1, 3), rs2_B = c(0.2, 2), rs22_C = c(2, 1)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L)) > test # A tibble: 2 × 3 rs1_A rs2_B rs22_C <dbl> <dbl> <dbl> 1 0.1 0.2 2 2 3 2 1...
Problem description I'm trying to write a library for protecting variables from concurrent access using sync.RWMutex. The goal is to prevent accidental misuse and promote best practices and I didn't find a library which provided a simple and safe wrapper like this. Scenario: Web application which has a data structure (...
I wrote this function to flatten nested iterables (with arbitrary depth) but refrain from flattening excepted types (for instance, string or tuple): from typing import Iterable, Tuple, Type def flatten(item: Iterable, except_types: Type | Tuple[Type] | None = None): if except_types is not None and isinstance(item...
This outputs the report in HTML. This fetches all records for an entity and then lists them in the report. Wondering if this can be made generic, right now it is only one entity and 2 fields. Also thinking what if PDF is asked along with HTML @Service public class DialogReportServiceImpl implements DialogReportService ...
EDIT Updated code This is my first real project in Python, and also my first time using sql databases. The purpose was initially to provide a very simple interface to track my reading hours using logs, but became a bit more complex as I expanded on the idea. The app consists of 4 primary classes Printer, Logger (main),...
Working through the freeCodeCamp JavaScript curriculum and I found this RegExp task surprisingly tricky (maybe I just don't use RegExp very much). The parameters are: Usernames can only use alpha-numeric characters. The only numbers in the username have to be at the end. There can be zero or more of them at the end. U...
I wrote a simple multilayer perceptron in Julia, which seems to work fine on different datasets, e.g. the MNIST dataset with a success rate of about 90% after a few seconds of training. But I would like constructive criticism of the program and I'm very new to the Julia programming language, so feedback on the formatti...
I've been working on a simple form validation code in JavaScript coupled with an HTML form. The form asks for user's basic information, including name, email, country, gender, and skills. There's a form validation function that checks if all required fields are filled in before submission. While the current code works ...
I am posting a message here because I am new to assembly programming. My goal today was to re-code strdup in assembly, so to save my first parameter which is a string (const char*), I have doubts when handling RSP to reserve space for the string and how I reset it at the end. However I'm not sure I did well, and I woul...
I have a basic pygame program that I use at the start of every project that involves pygame. The idea is every time I start a project that involves pygame I can copy and past and I can immediately start on my project without changing anything. The reason I am posting this is because of another question I posted. The an...
I have written a python program for random password generation and as a newbie I would like my code to be reviewed by professionals and if they have any suggestions to improve it. import string import random letters = string.ascii_letters digits = string.digits special_chars = string.punctuation letters_list = list(le...
I have a Balancer Class in my project which should dynamically increases/decreases the amount of Worker Thread based on the current amount of Messages which are written to an output queue. For that i have created the following Classes: Message.h A message class thats deriving from the Poco::Notification Class because i...
I am trying to speed up the code of a R function that calculates a Moran's I autocorrelation coefficient from very large distance matrices between geographic points. So I am exploring approaches to boost my R code using C++. Unfortunately, I am not at all familiar with C++. I found a very interesting C++ code to comput...
I am using a R function to spatially filter location points. There are five steps in the function: 1) calculate the distance between all points, 2) for each point, define the number of neighboring points within a given distance, 3) define the points with the greatest number of neighboring points within the given distan...
Do you have any suggestions for improving the efficiency of the code below? I believe that better optimization can be implemented in the GPU function cuKer_sum, which is located in the np.cu file. In this code, I am performing a summation over different determinants that are independently computed for various combinati...
I have a couple of methods and I am wondering if I can write them better. I am in dilemma of choosing over keeping all the functionalities in one place used by one method and dividing into multiple functions. Can I make the code more readable and Pythonic? Here's the code: def validate_screenshot_image(component, filen...
My project penhand tries to visualize the process of writing with a pen. Part of the project is an engine that converts text entry into a sequence of glyphs that are then rendered as animation into a HTML <canvas>. The other part is a file format for fonts and the development of actual fonts. Writing in a handwritten s...
I've written a comparison function between two json values. I'd like to know if it can be improved at all in any way. Thanks again for the help. /* JSON will compare in the following order: - null - bool - number - string - array (on values, then on array length (shorter i...
I took my code from this answer by me, I found it useful, so I developed it further, and here is the result. This script generates cryptographically secure passwords. The characters used by the passwords are chosen from the 94 printable ASCII characters that aren't blank characters or control characters. The characters...
I am making a 2d minecraft clone for a hobby. Here is my code: 2D_MC.py: import pygame import world TITLE = "2d_MC" SIZE = (1365, 705) MOVEMENT_SPEED = 5 def handle_events(): for event in pygame.event.get(): if event.type == pygame.QUIT: return 1 keys = pygame.key.get_pressed() if k...
I have been developing control software for a three-phase induction motor. The main task of this C++ code is to control the torque of the motor. In one part of the algorithm (The control algorithm is executed with a period of 100 µs.), I need to calculate the arcsine function. Here is my implementation. I would apprec...
This is part of the code I wrote in Java yesterday. It is for sending a body request with some parameters as a pair of keys and values, in a sorted list. Also, this list must have a signature, or the proposal I sent to the API endpoints won;t receive a correct answer (just because the API will refuse it). The signature...
Please help me optimize this script. I'm running it in Google Colab GPU runtime. I've implemented many optimizations but they worsened it. I need serious help. I have to submit my project in 3 days!. Let me know if you need additional information. PS: I don't have a Colab subscription. The model is built using Keras. W...
I've been writing a small Rust module recently with the sole purpose of speeding up my Python program, which is a Conway's Game of Life simulation. The function written in Rust is called from Python using the maturin package and PyO3 crate (on Rust's side). I've come up with a working prototype, but there are still a f...
Following suggestions from answers from my previous question, I have completely rewrote my script, to make it more concise and Pythonic, truly cryptographically secure, and added more functionality. This program generates random passwords, each password has a minimum length of 8, will always contain UPPERCASE, lowercas...
The Problem: Given an N by M Matrix, Create an Anti-Clockwise Traversal Path that winds in all the way into the Matrix Example: The Matrix is 9 by 5 Output: | 1|| 24|| 23|| 22|| 21| | 2|| 25|| 40|| 39|| 20| | 3|| 26|| 41|| 38|| 19| | 4|| 27|| 42|| 37|| 18| | 5|| 28|| 43|| 36|| 17| | 6|| 29|| 44|| 35|| 16| | 7|| ...
I have written a code to calculate the MSD of some molecules. The code averages over multiple time origins (sliding time window) and over all the molecules. I have also made it do one extra thing: do a dot product of the displacement vector selected and the eigenvectors of the molecule. The code works but it is extreme...
This is my implementation of the FPGrowth algorithm where, as an optimisation, I avoid re-creating the tree at each extension of the prefix, while I use a view representation that I think would be more memory efficient. Please let me know if there are any other ways to improve the current code. Any feedback is apprecia...
Task is simply to write the classic isPalindrom-function. Here's my implementation: func isStringPalindrom(str: String) -> Bool { let lcStr = str.lowercased() var i = 0 let aChars = Array(lcStr) while i < (lcStr.count / 2) { if aChars[i] != aChars[aChars.count - (i + 1)] { retur...
Basically I'm working on an API that receives a POST method and then uses some data to create a json and send it. There are some constraints, for example the names that I have in my database are different of the names that need to be in the json, but the values need to be the same. So what I did was create a dictionary...
Here's a piece of code from codebase I maintain/contribute to. It is a Spring REST controller, which exposes an endpoint to create user question. The question consists of title, description and reference to the user who asked it. It feels it's a bit of problematic from the design standpoint. That said, the person who o...
In order to gain familiarity with Scala I am trying to solve the following problem https://leetcode.com/problems/evaluate-division/description/ You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]....
I am learning about ANN and tried it for the MINST data sets. Now I am supposted to create a neural network (ANN) with backpropagation. The structure for the neural network I have is this the input layer consists of 784 neurons followed by one hidden layer with 10 neurons and the output layer is 10. Data file Code: imp...
I am adapting the following existing python parser: def parse_hexchar(c): if (c >= '0') and (c <= '9'): return ord(c) - ord('0') elif (c >= 'a') and (c <= 'f'): return ord(c) - ord('a') + 10 elif (c >= 'A') and (c <= 'F'): return ord(c) - ord('A') + 10 else: return -1 d...
Task description: Write a function, which counts the letters, spaces, number and special characters in string. My implementation: fun getPartsCount(str: String): Array<Int> { val nums = "[0-9]".toRegex().findAll(str) val letters = "[a-zA-Z]".toRegex().findAll(str) val spaces = " ".toRegex().findAll(str) ...
From code review: OO simple network time server with changes from a previous code inspection and added Windows support I made many changes as per the review comments. The code has been significantly revamped and hopefully the code is clearer to read. A new feature is support for IPv4 or IPv6 in the udp_server class al...
As the title suggests, I'm learning rust. My go to starter project when learning a language is to write a calculator. It's relatively simple, but complex enough that you will need to utilize many features of a language. This particular implementation only covers the base PEMDAS as well as pseudo handling the unary nega...
I have a workbook that has a number of Pivot Tables spread across a number of worksheets. There's a bunch of slicers on one of the worksheets, and they're pretty slow-ish to load after changing filters/selections. All of my slicers are on the same worksheet (call it Sheet1), but only 4 out of 15 pivot tables are on tha...
The following code is meant to generate ranges from arbitrary integer sequences and print them in a bash-like syntax: main.rs use ranges::Ranges; use std::io::stdin; use std::ops::RangeInclusive; fn main() { println!( "{}", Ranges::from(read_integers()) .map(range_to_bash_literal) ...
After giving a couple of well-received answers to similar questions, I thought I'd try to come up with my own solution. I believe that a good password generator can and should be quite simple without sacrificing security or usability. Also, this is the first time I actually code a command-line utility (as a Windows use...
This is related to my previous question, this is the core logic of that script that I wanted you to review. Basically, I have two very large lists collectively containing literally over one million items, each item can be simplified to a triplet, in which the first and second element are integers, and the third element...
I am new to rust and come from a Java background. Currently I'm trying to imitate the java methodology of thread creation using Runnable interface in Rust. But I feel this design pattern isn't that flexible due to immutable self reference that the run method of StartThread trait requires. This is my current implementat...
I have this code, which works for the simple tasks I want. But I have questions. import colorama TXT = WTXT = RESET = colorama.Style.RESET_ALL WARN = WARNED = CAUTION = colorama.Fore.YELLOW FAIL = FAILED = ERROR = STOP = colorama.Fore.RED SUCCESS = SUCCEED = PASS = GO = colorama.Fore.GREEN def warn(*txt): a = lis...
I have developed a World Weather application using Tkinter in Python. The application retrieves current weather information and a 3-day weather forecast from the Weatherbit.io API based on user input. The application displays the weather data on a graphical user interface. I would like feedback on the following aspects...
ERROR: type should be string, got "https://github.com/speedrun-program/amnesia_load_screen_tool/blob/main/code_injection.cpp\nhttps://github.com/speedrun-program/amnesia_load_screen_tool/blob/main/file_helper.h\n#include <cstdio>\n#include <windows.h>\n#include <tlhelp32.h>\n#include <psapi.h>\n#include <cstdint>\n#include <string>\n#include <memory>\n#include <stdexcept>\n\n#include \"file_helper.h\"\n\ntypedef LONG(__stdcall* NTFUNCTION)(HANDLE);\n\nconst wchar_t steamName[] = L\"Amnesia.exe\";\nconst wchar_t nosteamName[] = L\"Amnesia_NoSteam.exe\";\nconst char flashbackNameFile[] = \"flashback_names.txt\";\nconst uint32_t flashbackSkipInstructionsSize = 128;\nconst uint32_t flashbackWaitInstructionsSize = 128;\n\nclass ProcessHelper\n{\npublic:\n std::unique_ptr<unsigned char[]> buffer;\n uint32_t memoryOffset = 0;\n uint32_t bytesLeft = 0;\n HANDLE amnesiaHandle = nullptr;\n uint32_t amnesiaMemoryLocation = (uint32_t)-1;\n DWORD pageSize = 0;\n int bufferPosition = 0;\n\n ProcessHelper(const ProcessHelper& fhelper) = delete;\n ProcessHelper& operator=(ProcessHelper other) = delete;\n ProcessHelper(ProcessHelper&&) = delete;\n ProcessHelper& operator=(ProcessHelper&&) = delete;\n\n ProcessHelper(DWORD pid)\n {\n amnesiaHandle = OpenProcess(\n PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_SUSPEND_RESUME,\n false,\n pid\n );\n\n SYSTEM_INFO sysInfo;\n GetSystemInfo(&sysInfo);\n pageSize = sysInfo.dwPageSize;\n buffer = std::make_unique<unsigned char[]>(pageSize);\n bufferPosition = pageSize; // this initial value lets the first read happen on the first call to getByte\n }\n\n ~ProcessHelper()\n {\n if (amnesiaHandle != nullptr)\n {\n CloseHandle(amnesiaHandle);\n }\n }\n\n bool checkIfPathIsToAmnesia(const std::wstring& filepathBuffer)\n {\n // if L'\\\\' isn't found, filenamePosition will increase from npos to 0\n size_t filenamePosition = filepathBuffer.find_last_of(L'\\\\') + 1;\n int filenameSize = wcslen(&filepathBuffer[filenamePosition]);\n\n if ((filenameSize != (sizeof(steamName) / sizeof(wchar_t)) - 1 && filenameSize != (sizeof(nosteamName) / sizeof(wchar_t)) - 1)\n || (wcscmp(&filepathBuffer[filenamePosition], steamName) != 0 && wcscmp(&filepathBuffer[filenamePosition], nosteamName) != 0))\n {\n return false;\n }\n\n return true;\n }\n\n bool checkIfProcessIsAmnesia()\n {\n std::wstring filepathBuffer(512 - 1, L'\\0'); // - 1 because a character is used for a null terminator on modern implementations\n\n DWORD queryFullProcessImageNameResult = 0;\n if (amnesiaHandle != nullptr) // this check gets rid of warning C6387\n {\n while (queryFullProcessImageNameResult == 0)\n {\n DWORD filepathBufferSize = filepathBuffer.size() - 1; // - 1 because writing to filepathBuffer.size() position is undefined\n queryFullProcessImageNameResult = QueryFullProcessImageName(amnesiaHandle, 0, &filepathBuffer[0], &filepathBufferSize);\n if (queryFullProcessImageNameResult == 0)\n {\n DWORD errorNumber = GetLastError();\n if (errorNumber == 122) // buffer too small error\n {\n filepathBuffer.clear();\n filepathBuffer.resize(((filepathBufferSize + 2) * 2) - 1, L'\\0'); // resizing to the next power of 2\n }\n else\n {\n printf(\"error when using GetModuleBaseName: %d\\n\", GetLastError());\n return false;\n }\n }\n\n if (filepathBufferSize >= 32767) // this should never happen\n {\n printf(\"ERROR: file path size from QueryFullProcessImageName somehow exceeded 32767 characters\\n\");\n return false;\n }\n }\n }\n\n // if L'\\\\' isn't found, filenamePosition will increase from npos to 0\n if (!checkIfPathIsToAmnesia(filepathBuffer))\n {\n printf(\"process name wasn't Amnesia.exe or Amnesia_NoSteam.exe when checking it using GetModuleBaseName: %ls\\n\", &filepathBuffer[0]);\n return false;\n }\n\n return true;\n }\n\n bool findExecutableMemoryLocation()\n {\n std::wstring filepathBuffer(512 - 1, L'\\0'); // - 1 because a character is used for a null terminator on modern implementations\n\n uint32_t queryAddress = 0;\n MEMORY_BASIC_INFORMATION mbi = {};\n if (VirtualQueryEx(amnesiaHandle, (LPCVOID)queryAddress, &mbi, sizeof(mbi)) == 0) // checking if VirtualQueryEx works\n {\n printf(\"error when using VirtualQueryEx: %d\\n\", GetLastError());\n return false;\n }\n\n // finding start of Amnesia.exe or Amnesia_NoSteam.exe memory\n DWORD filepathBufferSize = 0;\n DWORD charactersWritten = 0;\n size_t filepathLength = (size_t)-1;\n do\n {\n if (queryAddress != 0) // this check gets rid of warning C6387\n {\n do\n {\n filepathBufferSize = filepathBuffer.size() - 1; // - 1 because writing to filepathBuffer.size() position is undefined\n charactersWritten = GetMappedFileName(\n amnesiaHandle,\n (LPVOID)queryAddress,\n &filepathBuffer[0],\n filepathBufferSize\n );\n\n if (filepathBufferSize == charactersWritten)\n {\n if (filepathBufferSize >= 32767) // this should never happen\n {\n continue;\n }\n\n filepathBuffer.clear();\n filepathBuffer.resize(((filepathBufferSize + 2) * 2) - 1, L'\\0'); // resizing to the next power of 2\n }\n }\n while (filepathBufferSize == charactersWritten); // if this is true then filepathBuffer wasn't big enough\n }\n\n if (checkIfPathIsToAmnesia(filepathBuffer))\n {\n filepathLength = charactersWritten;\n break;\n }\n\n queryAddress += mbi.RegionSize;\n }\n while (VirtualQueryEx(amnesiaHandle, (LPCVOID)queryAddress, &mbi, sizeof(mbi)) != 0);\n\n if (filepathLength == (size_t)-1)\n {\n printf(\"couldn't find Amnesia.exe or Amnesia_NoSteam.exe memory location\\n\");\n return false;\n }\n\n // finding the .text area\n std::wstring filepathBufferCopy = filepathBuffer;\n\n do\n {\n if (mbi.Protect == PAGE_EXECUTE_READ)\n {\n amnesiaMemoryLocation = queryAddress;\n bytesLeft = mbi.RegionSize;\n memoryOffset = queryAddress - pageSize; // this will overflow to 0 on the first call to getByte\n return true;\n }\n\n if (queryAddress != 0) // this check gets rid of warning C6387\n {\n charactersWritten = GetMappedFileName(\n amnesiaHandle,\n (LPVOID)queryAddress,\n &filepathBuffer[0],\n filepathBufferSize\n );\n }\n\n if (charactersWritten != filepathLength || filepathBuffer != filepathBufferCopy) // no longer looking at exe memory\n {\n break;\n }\n\n queryAddress += mbi.RegionSize;\n }\n while (VirtualQueryEx(amnesiaHandle, (LPCVOID)queryAddress, &mbi, sizeof(mbi)) != 0);\n\n printf(\"couldn't find .text area in Amnesia.exe or Amnesia_NoSteam.exe memory\\n\");\n return false;\n }\n\n bool getByte(unsigned char& b)\n {\n if (bytesLeft == 0)\n {\n return false;\n }\n\n if (bufferPosition == pageSize)\n {\n bufferPosition = 0;\n memoryOffset += pageSize;\n bool readSucceeded = ReadProcessMemory(\n amnesiaHandle,\n (LPCVOID)memoryOffset,\n (LPVOID)buffer.get(),\n pageSize,\n nullptr\n );\n\n if (!readSucceeded)\n {\n printf(\"ProcessHelper ReadProcessMemory error in getByte: %d\\nat memory address: %u\\n\", GetLastError(), memoryOffset);\n return false;\n }\n }\n\n b = buffer[bufferPosition];\n bufferPosition++;\n bytesLeft--;\n\n return true;\n }\n};\n\nstruct SavedInstructions\n{\n unsigned char gettingSoundHandler[14]{};\n unsigned char beforeFadeOutAllBytes[7]{};\n unsigned char sleepCallBytes[6]{};\n unsigned char loadEndBytes[5]{};\n uint32_t stopFunctionLocation = 0;\n uint32_t isPlayingLocation = 0;\n uint32_t beforeFadeOutAllLocation = 0;\n uint32_t loadEndLocation = 0;\n bool isSteamVersion = false;\n};\n\nDWORD searchUsingSnapshotHandle(SavedInstructions& si, PROCESSENTRY32& processEntry, HANDLE snapshot)\n{\n if (!Process32First(snapshot, &processEntry))\n {\n printf(\"error when using Process32First: %d\\n\", GetLastError());\n return (DWORD)-1;\n }\n\n do\n {\n if ((si.isSteamVersion = (wcscmp(processEntry.szExeFile, steamName) == 0)) || wcscmp(processEntry.szExeFile, nosteamName) == 0)\n {\n return processEntry.th32ProcessID;\n }\n }\n while (Process32Next(snapshot, &processEntry));\n\n return (DWORD)-1;\n}\n\nDWORD findAmnesiaPid(SavedInstructions& si)\n{\n DWORD amnesiaPid = (DWORD)-1;\n\n PROCESSENTRY32 processEntry{};\n processEntry.dwSize = sizeof(PROCESSENTRY32);\n\n HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n if (snapshot == INVALID_HANDLE_VALUE)\n {\n printf(\"error when using CreateToolhelp32Snapshot: %d\\n\", GetLastError());\n return amnesiaPid;\n }\n amnesiaPid = searchUsingSnapshotHandle(si, processEntry, snapshot);\n CloseHandle(snapshot);\n\n if (amnesiaPid == (DWORD)-1)\n {\n printf(\"couldn't find amnesia process\\n\");\n }\n\n return amnesiaPid;\n}\n\nbool findNtFunctions(NTFUNCTION& NtSuspendProcess, NTFUNCTION& NtResumeProcess)\n{\n HMODULE ntdllHandle = GetModuleHandle(L\"ntdll.dll\");\n if (!ntdllHandle)\n {\n printf(\"WARNING: error using GetModuleHandle to find ntdll.dll: %d\\nAmnesia won't be suspended during code injection\\n\", GetLastError());\n return false;\n }\n\n NtSuspendProcess = (NTFUNCTION)GetProcAddress(ntdllHandle, \"NtSuspendProcess\");\n if (!NtSuspendProcess)\n {\n printf(\"WARNING: error using GetProcAddress to find NtSuspendProcess: %d\\nAmnesia won't be suspended during code injection\\n\", GetLastError());\n return false;\n }\n\n NtResumeProcess = (NTFUNCTION)GetProcAddress(ntdllHandle, \"NtResumeProcess\");\n if (!NtResumeProcess)\n {\n printf(\"WARNING: error using GetProcAddress to find NtResumeProcess: %d\\nAmnesia won't be suspended during code injection\\n\", GetLastError());\n return false;\n }\n\n return true;\n}\n\nvoid addNewValueToMemorySlice(unsigned char* memorySlice, size_t size, unsigned char newEndValue)\n{\n for (size_t i = 0; i < size - 1; i++)\n {\n memorySlice[i] = memorySlice[i + 1];\n }\n memorySlice[size - 1] = newEndValue;\n}\n\n// this is fast enough for the size of the game\n// if it needs to be faster, try making memorySlice a circular buffer\nbool findInstructions(SavedInstructions& si, ProcessHelper& ph)\n{\n unsigned char b = 0;\n unsigned char memorySlice[16]{}; // give this at least the size of the longest byte pattern\n\n for (int i = 1; i < sizeof(memorySlice); i++)\n {\n if (!ph.getByte(b))\n {\n return false;\n }\n memorySlice[i] = b;\n }\n\n int locationsFound = 0; // if this ends up being greater than 5, there were duplicate injection location patterns\n bool isv = si.isSteamVersion; // on the steam version, the first mov instruction is 6 bytes long instead of 5\n for (size_t i = 0; ph.getByte(b); i++)\n {\n addNewValueToMemorySlice(memorySlice, sizeof(memorySlice), b);\n\n if (memorySlice[0] == 0xf6 && memorySlice[1] == 0x74 && memorySlice[7] == 0x75 && memorySlice[9] == 0x80)\n {\n locationsFound++;\n si.stopFunctionLocation = ph.amnesiaMemoryLocation + i - 16;\n }\n else if (memorySlice[0] == 0x48 && memorySlice[8] == 0xd0 && memorySlice[9] == 0x5d)\n {\n locationsFound++;\n si.isPlayingLocation = ph.amnesiaMemoryLocation + i - 17;\n }\n else if (memorySlice[0] == 0x75 && memorySlice[2] == 0x56 && memorySlice[4] == 0x15 && memorySlice[9] == 0x8b)\n {\n locationsFound++;\n memcpy(si.sleepCallBytes, &memorySlice[3], sizeof(si.sleepCallBytes));\n }\n else if (\n (memorySlice[5] == 0xff && memorySlice[6] == 0x50 && memorySlice[8] == 0xe8 && memorySlice[13] == 0x2b)\n || (si.isSteamVersion && memorySlice[5] == 0xff && memorySlice[6] == 0xd0 && memorySlice[7] == 0xe8 && memorySlice[13] == 0x45))\n {\n locationsFound++;\n si.loadEndLocation = ph.amnesiaMemoryLocation + i;\n\n if (memorySlice[0] == 0xe9) // the jump instruction is already there, so amnesia must have already been injected\n {\n printf(\"amnesia is already injected\\n\");\n return false;\n }\n\n memcpy(si.loadEndBytes, memorySlice, sizeof(si.loadEndBytes));\n }\n else if (memorySlice[8 + isv] == 0x40 && memorySlice[10 + isv] == 0x8b && memorySlice[11 + isv] == 0x40 && memorySlice[14 + isv] == 0x01)\n {\n locationsFound++;\n memcpy(si.gettingSoundHandler, memorySlice, sizeof(si.gettingSoundHandler));\n\n i += 16 + isv;\n si.beforeFadeOutAllLocation = ph.amnesiaMemoryLocation + i;\n for (int n = 0; n < 16 + isv; n++)\n {\n ph.getByte(b);\n addNewValueToMemorySlice(memorySlice, sizeof(memorySlice), b);\n }\n\n if (memorySlice[0] == 0xe9) // the jump instruction is already there, so amnesia must have already been injected\n {\n printf(\"amnesia is already injected\\n\");\n return false;\n }\n\n memcpy(si.beforeFadeOutAllBytes, memorySlice, sizeof(si.beforeFadeOutAllBytes));\n }\n }\n\n bool allLocationsFound = (\n si.stopFunctionLocation != 0\n && si.isPlayingLocation != 0\n && si.beforeFadeOutAllLocation != 0\n && si.loadEndLocation != 0\n && si.sleepCallBytes[0] != 0\n );\n if (locationsFound > 5 || (locationsFound == 5 && !allLocationsFound))\n {\n printf(\"error: duplicate injection location patterns found\\n\");\n return false;\n }\n else if (allLocationsFound)\n {\n return true;\n }\n\n printf(\"couldn't find all instruction locations\\n\");\n return false;\n}\n\n// this needs to be done to find how much memory to allocate for the virtual pages\nvoid preprocessFlashbackNames(FileHelper<char>& fh, uint32_t& howManyNames, uint32_t& longestName)\n{\n char ch = '\\0';\n\n uint32_t currentNameLength = 0;\n\n while (fh.getCharacter(ch))\n {\n if (ch == '\\r') // windows puts this at the end of lines\n {\n continue;\n }\n else if (ch == '\\n')\n {\n if (currentNameLength > longestName)\n {\n longestName = currentNameLength;\n }\n howManyNames += currentNameLength > 0;\n currentNameLength = 0;\n }\n else\n {\n currentNameLength++;\n }\n }\n\n // last line\n if (currentNameLength > longestName)\n {\n longestName = currentNameLength;\n }\n howManyNames += currentNameLength > 0;\n\n fh.resetFile();\n}\n\nbool setFlashbackNames(unsigned char* forExtraMemory, FileHelper<char>& fh, uint32_t startOffset, uint32_t spacePerName, uint32_t extraMemorySize)\n{\n char ch = '\\0';\n uint32_t writeOffset = startOffset;\n uint32_t nameSize = 0;\n\n while (fh.getCharacter(ch))\n {\n if (ch == '\\r') // windows puts this at the end of lines\n {\n continue;\n }\n else if (ch == '\\n')\n {\n if (nameSize > 0)\n {\n memcpy(&forExtraMemory[writeOffset + spacePerName - 8], &nameSize, sizeof(nameSize));\n writeOffset += spacePerName;\n nameSize = 0;\n }\n }\n else\n {\n if (nameSize == spacePerName - 9) // this shouldn't ever happen, flashback line names shouldn't need to be long enough to cause this\n {\n printf(\"a flashback line name was longer than expected, possibly because of integer overflow\\n\");\n return false;\n }\n else if (writeOffset + nameSize >= extraMemorySize) // this also shouldn't ever happen, there shouldn't need to be enough to cause this\n {\n printf(\"there were more flashback line names than expected, possibly because of integer overflow\\n\");\n return false;\n }\n\n forExtraMemory[writeOffset + nameSize] = (unsigned int)ch;\n nameSize++;\n }\n }\n if (nameSize > 0)\n {\n memcpy(&forExtraMemory[writeOffset + spacePerName - 8], &nameSize, sizeof(nameSize));\n }\n\n return true;\n}\n\nbool injectSkipInstructions(\n unsigned char* forExtraMemory,\n SavedInstructions& si,\n ProcessHelper& ph,\n uint32_t howManyNames,\n uint32_t spacePerName,\n uint32_t extraMemoryLocation,\n uint32_t extraMemorySize)\n{\n // this is jumped to before a call instruction, so the caller-saved registers should already be saved\n unsigned char flashbackSkipInstructions[flashbackSkipInstructionsSize] = {\n // jmp destination from before calling cSoundHandler::FadeOutAll\n 0xd9, 0x1c, 0x24, // 0000 // fstp dword ptr [esp] // copied\n 0x6a, 0x01, // 0003 // push 0x01 // copied\n 0x8b, 0xc8, // 0005 // mov ecx, eax // copied\n 0x53, // 0007 // push ebx // stack depth +4\n 0x57, // 0008 // push edi // stack depth +8\n 0x51, // 0009 // push ecx // cSoundHandler object // stack depth +12\n 0xbb, 0x00, 0x00, 0x00, 0x00, // 0010 // mov ebx, start of first flashback name // check\n 0x90, // 0015 // nop so loop is aligned on byte 16\n // start of loop\n 0x89, 0x1d, 0x00, 0x00, 0x00, 0x00, // 0016 // mov [string object ptr location], ebx // ptr to characters // check\n 0x8b, 0xbb, 0x00, 0x00, 0x00, 0x00, // 0022 // mov edi, dword ptr [ebx + spacePerName - 8] // flashback name size\n 0x89, 0x3d, 0x00, 0x00, 0x00, 0x00, // 0028 // mov dword ptr [string object size location], edi // check\n 0x68, 0x00, 0x00, 0x00, 0x00, // 0034 // push string object ptr location // stack depth +16 // check\n 0xe8, 0x00, 0x00, 0x00, 0x00, // 0039 // call cSoundHandler::Stop // stack depth +12\n 0x8b, 0x0c, 0x24, // 0044 // mov ecx, dword ptr [esp] // cSoundHandler object\n 0x81, 0xc3, 0x00, 0x00, 0x00, 0x00, // 0047 // add ebx, spacePerName // start of next string data\n 0x81, 0xfb, 0x00, 0x00, 0x00, 0x00, // 0053 // cmp ebx, end of flashback names // check\n 0x75, 0xd3, // 0059 // jnz -45\n // end of loop\n\n 0x59, // 0061 // pop ecx // stack depth +8\n 0x5f, // 0062 // pop edi // stack depth +4\n 0x5b, // 0063 // pop ebx // stack depth +0\n 0xe9, 0x00, 0x00, 0x00, 0x00, // 0064 // jmp to before calling cSoundHandler::FadeOutAll, 0048baad\n 0x90, // 0069 // nop\n };\n\n unsigned char jmpInstruction[sizeof(si.beforeFadeOutAllBytes)] = {0xe9, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90};\n\n uint32_t stdStringCapacity = spacePerName - 1;\n memcpy(&forExtraMemory[sizeof(flashbackSkipInstructions) + 20], &stdStringCapacity, sizeof(uint32_t));\n\n uint32_t startOffset = sizeof(flashbackSkipInstructions) + 64; // 64 bytes used for std::string object + padding\n\n memcpy(&flashbackSkipInstructions[0], si.beforeFadeOutAllBytes, sizeof(si.beforeFadeOutAllBytes));\n\n uint32_t firstFlashbackNameLocation = extraMemoryLocation + startOffset;\n memcpy(&flashbackSkipInstructions[11], &firstFlashbackNameLocation, sizeof(uint32_t));\n\n uint32_t stringObjectPtrLocation = extraMemoryLocation + sizeof(flashbackSkipInstructions);\n memcpy(&flashbackSkipInstructions[18], &stringObjectPtrLocation, sizeof(uint32_t));\n memcpy(&flashbackSkipInstructions[35], &stringObjectPtrLocation, sizeof(uint32_t));\n\n uint32_t flashbackNameSizeOffset = spacePerName - 8;\n memcpy(&flashbackSkipInstructions[24], &flashbackNameSizeOffset, sizeof(uint32_t));\n\n uint32_t stringObjectSizeLocation = extraMemoryLocation + sizeof(flashbackSkipInstructions) + 16;\n memcpy(&flashbackSkipInstructions[30], &stringObjectSizeLocation, sizeof(uint32_t));\n\n uint32_t stopFunctionOffset = si.stopFunctionLocation - (extraMemoryLocation + 44);\n memcpy(&flashbackSkipInstructions[40], &stopFunctionOffset, sizeof(stopFunctionOffset));\n\n memcpy(&flashbackSkipInstructions[49], &spacePerName, sizeof(spacePerName));\n\n uint32_t endOfFlashbackNames = extraMemoryLocation + startOffset + (howManyNames * spacePerName);\n memcpy(&flashbackSkipInstructions[55], &endOfFlashbackNames, sizeof(uint32_t));\n\n uint32_t fadeOutAllOffset = (si.beforeFadeOutAllLocation + sizeof(si.beforeFadeOutAllBytes)) - (extraMemoryLocation + 69);\n memcpy(&flashbackSkipInstructions[65], &fadeOutAllOffset, sizeof(fadeOutAllOffset));\n\n memset(&flashbackSkipInstructions[70], 0xcc, sizeof(flashbackSkipInstructions) - 70); // int3\n\n memcpy(forExtraMemory, flashbackSkipInstructions, sizeof(flashbackSkipInstructions));\n\n SIZE_T bytesWritten = 0;\n bool wpmSucceeded = false;\n\n wpmSucceeded = WriteProcessMemory(\n ph.amnesiaHandle,\n (LPVOID)extraMemoryLocation,\n (LPCVOID)forExtraMemory,\n extraMemorySize,\n nullptr\n );\n\n if (!wpmSucceeded)\n {\n printf(\"error when calling WriteProcessMemory to write to allocated virtual page(s): %d\\nat memory address: %u\\n\", GetLastError(), extraMemoryLocation);\n return false;\n }\n\n uint32_t offsetFromCheckMapChange = (extraMemoryLocation + 0) - (si.beforeFadeOutAllLocation + 5);\n memcpy(&jmpInstruction[1], &offsetFromCheckMapChange, sizeof(offsetFromCheckMapChange));\n\n wpmSucceeded = WriteProcessMemory(\n ph.amnesiaHandle,\n (LPVOID)si.beforeFadeOutAllLocation,\n (LPCVOID)jmpInstruction,\n sizeof(si.beforeFadeOutAllBytes),\n &bytesWritten\n );\n\n if (bytesWritten < sizeof(si.beforeFadeOutAllBytes))\n {\n printf(\"JMP INSTRUCTION ONLY PARTIALLY WRITTEN IN CHECKMAPCHANGE\\nRESTART AMNESIA OR IT WILL CRASH ON MAP CHANGE\\nerror: %d\\n\", GetLastError());\n return false;\n }\n else if (!wpmSucceeded)\n {\n printf(\"error when calling WriteProcessMemory to write jmp instruction in CheckMapChange: %d\\nat memory address: %u\\n\", GetLastError(), si.beforeFadeOutAllLocation);\n return false;\n }\n\n return true;\n}\n\nbool injectWaitInstructions(\n unsigned char* forExtraMemory,\n SavedInstructions& si,\n ProcessHelper& ph,\n uint32_t howManyNames,\n uint32_t spacePerName,\n uint32_t extraMemoryLocation,\n uint32_t extraMemorySize)\n{\n // this is jumped to before a call instruction, so the caller-saved registers should already be saved\n unsigned char flashbackWaitInstructions[flashbackWaitInstructionsSize] = {\n 0x53, // 0000 // push ebx // stack depth +4\n 0x57, // 0001 // push edi // stack depth +8\n 0x56, // 0002 // push esi // stack depth +12\n 0x51, // 0003 // push ecx // steam version copied instructions need ecx // stack depth +16\n 0x51, // 0004 // push ecx // dummy push // stack depth +20\n 0x51, // 0005 // push ecx // dummy push // stack depth +24\n\n // jmp destination from near the end of the map load\n // starting with 13-14 bytes to get the cSoundHandler object in eax\n // the last byte is a nop instruction because the NoSteam version only uses 13 bytes to get the cSoundHandler object\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, // 0006 // getting cSoundHandler object\n\n 0x8b, 0xc8, // 0020 // mov ecx, eax // moving cSoundHandler object to ecx\n 0x51, // 0022 // push ecx // cSoundHandler object // stack depth +28\n 0xbb, 0x00, 0x00, 0x00, 0x00, // 0023 // mov ebx, start of first flashback name\n 0x31, 0xf6, // 0028 // xor esi, esi\n 0x90, 0x90, // 0030 // nops so loop is aligned on byte 32\n // start of loop\n 0x89, 0x1d, 0x00, 0x00, 0x00, 0x00, // 0032 // mov [string object ptr location], ebx // ptr to characters\n 0x8b, 0xbb, 0x00, 0x00, 0x00, 0x00, // 0038 // mov edi, dword ptr [ebx + spacePerName - 8] // flashback name size\n 0x89, 0x3d, 0x00, 0x00, 0x00, 0x00, // 0044 // mov dword ptr [string object size location], edi\n 0x8b, 0x0c, 0x24, // 0050 // mov ecx, dword ptr [esp] // cSoundHandler object\n 0x68, 0x00, 0x00, 0x00, 0x00, // 0053 // push string object ptr location // stack depth +32\n 0xe8, 0x00, 0x00, 0x00, 0x00, // 0058 // call cSoundHandler::IsPlaying // stack depth +28\n 0x09, 0xc6, // 0063 // or esi, eax\n 0x81, 0xc3, 0x00, 0x00, 0x00, 0x00, // 0065 // add ebx, spacePerName // start of next string data\n 0x81, 0xfb, 0x00, 0x00, 0x00, 0x00, // 0071 // cmp ebx, end of flashback names\n 0x75, 0xd1, // 0077 // jnz -47\n 0x83, 0xfe, 0x00, // 0079 // cmp esi, 0\n 0x74, 0x10, // 0082 // jz 16\n 0x56, // 0084 // push esi // stack depth +32 // esi should be 1 here\n 0xff, 0x15, 0x00, 0x00, 0x00, 0x00, // 0085 // call Sleep // stack depth +28\n 0xbb, 0x00, 0x00, 0x00, 0x00, // 0091 // mov ebx, start of first flashback name\n 0x31, 0xf6, // 0096 // xor esi, esi\n 0x74, 0xbc, // 0098 // jz -68\n // end of loop\n\n 0x83, 0xc4, 0x0c, // 0100 // add esp, 12 // stack depth +16\n 0x59, // 0103 // pop ecx // stack depth +12\n 0x5e, // 0104 // pop esi // stack depth +8\n 0x5f, // 0105 // pop edi // stack depth +4\n 0x5b, // 0106 // pop ebx // stack depth +0\n 0x00, 0x00, 0x00, 0x00, 0x00, // 0107 // copied instructions\n 0xe9, 0x00, 0x00, 0x00, 0x00, // 0112 // jmp to end of load\n 0x90, // 0117 // nop\n };\n\n unsigned char jmpInstruction[sizeof(si.beforeFadeOutAllBytes)] = {0xe9, 0x00, 0x00, 0x00, 0x00};\n\n uint32_t stdStringCapacity = spacePerName - 1;\n memcpy(&forExtraMemory[sizeof(flashbackWaitInstructions) + 20], &stdStringCapacity, sizeof(uint32_t));\n\n uint32_t startOffset = sizeof(flashbackWaitInstructions) + 64; // 64 bytes used for std::string object + padding\n\n memcpy(&flashbackWaitInstructions[6], si.gettingSoundHandler, sizeof(si.gettingSoundHandler) - !(si.isSteamVersion));\n\n uint32_t firstFlashbackNameLocation = extraMemoryLocation + startOffset;\n memcpy(&flashbackWaitInstructions[24], &firstFlashbackNameLocation, sizeof(uint32_t));\n memcpy(&flashbackWaitInstructions[92], &firstFlashbackNameLocation, sizeof(uint32_t));\n\n uint32_t stringObjectPtrLocation = extraMemoryLocation + sizeof(flashbackWaitInstructions);\n memcpy(&flashbackWaitInstructions[34], &stringObjectPtrLocation, sizeof(uint32_t));\n memcpy(&flashbackWaitInstructions[54], &stringObjectPtrLocation, sizeof(uint32_t));\n\n uint32_t flashbackNameSizeOffset = spacePerName - 8;\n memcpy(&flashbackWaitInstructions[40], &flashbackNameSizeOffset, sizeof(uint32_t));\n\n uint32_t stringObjectSizeLocation = extraMemoryLocation + sizeof(flashbackWaitInstructions) + 16;\n memcpy(&flashbackWaitInstructions[46], &stringObjectSizeLocation, sizeof(uint32_t));\n\n uint32_t isPlayingOffset = si.isPlayingLocation - (extraMemoryLocation + 63);\n memcpy(&flashbackWaitInstructions[59], &isPlayingOffset, sizeof(isPlayingOffset));\n\n memcpy(&flashbackWaitInstructions[67], &spacePerName, sizeof(spacePerName));\n\n uint32_t endOfFlashbackNames = extraMemoryLocation + startOffset + (howManyNames * spacePerName);\n memcpy(&flashbackWaitInstructions[73], &endOfFlashbackNames, sizeof(uint32_t));\n\n memcpy(&flashbackWaitInstructions[85], si.sleepCallBytes, sizeof(si.sleepCallBytes));\n\n memcpy(&flashbackWaitInstructions[107], si.loadEndBytes, sizeof(si.loadEndBytes));\n\n uint32_t loadEndOffset = (si.loadEndLocation + sizeof(si.loadEndBytes)) - (extraMemoryLocation + 117);\n memcpy(&flashbackWaitInstructions[113], &loadEndOffset, sizeof(loadEndOffset));\n\n memset(&flashbackWaitInstructions[118], 0xcc, sizeof(flashbackWaitInstructions) - 118); // int3\n\n memcpy(forExtraMemory, flashbackWaitInstructions, sizeof(flashbackWaitInstructions));\n\n SIZE_T bytesWritten = 0;\n bool wpmSucceeded = false;\n\n wpmSucceeded = WriteProcessMemory(\n ph.amnesiaHandle,\n (LPVOID)extraMemoryLocation,\n (LPCVOID)forExtraMemory,\n extraMemorySize,\n nullptr\n );\n\n if (!wpmSucceeded)\n {\n printf(\"error when calling WriteProcessMemory to write to allocated virtual page(s): %d\\nat memory address: %u\\n\", GetLastError(), extraMemoryLocation);\n return false;\n }\n\n uint32_t offsetFromCheckMapChange = (extraMemoryLocation + 0) - (si.loadEndLocation + 5);\n memcpy(&jmpInstruction[1], &offsetFromCheckMapChange, sizeof(offsetFromCheckMapChange));\n\n wpmSucceeded = WriteProcessMemory(\n ph.amnesiaHandle,\n (LPVOID)si.loadEndLocation,\n (LPCVOID)jmpInstruction,\n sizeof(si.loadEndBytes),\n &bytesWritten\n );\n\n if (bytesWritten < sizeof(si.loadEndBytes))\n {\n printf(\"JMP INSTRUCTION ONLY PARTIALLY WRITTEN IN CHECKMAPCHANGE\\nRESTART AMNESIA OR IT WILL CRASH ON MAP CHANGE\\nerror: %d\\n\", GetLastError());\n return false;\n }\n else if (!wpmSucceeded)\n {\n printf(\"error when calling WriteProcessMemory to write jmp instruction in CheckMapChange: %d\\nat memory address: %u\\n\", GetLastError(), si.loadEndLocation);\n return false;\n }\n\n return true;\n}\n\nbool injectWhileSuspended(ProcessHelper& ph, SavedInstructions& si, LPVOID& extraMemoryLocation, bool skipFlashbacks)\n{\n if (!ph.findExecutableMemoryLocation())\n {\n return false;\n }\n size_t executableRegionSize = ph.bytesLeft;\n\n if (!findInstructions(si, ph))\n {\n return false;\n }\n\n uint32_t howManyNames = 0;\n uint32_t longestName = 0;\n uint32_t spacePerName = 0;\n uint32_t nameAreaOffset = 0;\n uint32_t extraMemorySize = 0;\n std::unique_ptr<unsigned char[]> forExtraMemory;\n\n // FileHelper<char> object is only used in this area, so this scope is used so it doesn't stay allocated longer than it's needed\n {\n FileHelper<char> fh(flashbackNameFile);\n preprocessFlashbackNames(fh, howManyNames, longestName);\n\n if (howManyNames == 0)\n {\n printf(\"no flashback line names found in %s\\n\", flashbackNameFile);\n return false;\n }\n\n spacePerName = (((longestName + 9) / 64) + (((longestName + 9) % 64) != 0)) * 64; // 8 bytes to store name size, 1 byte for null character\n nameAreaOffset = (skipFlashbacks ? flashbackSkipInstructionsSize : flashbackWaitInstructionsSize) + 64; // 64 bytes to store string object plus padding\n extraMemorySize = nameAreaOffset + (spacePerName * howManyNames);\n\n forExtraMemory = std::make_unique<unsigned char[]>(extraMemorySize);\n\n if (!setFlashbackNames(forExtraMemory.get(), fh, nameAreaOffset, spacePerName, extraMemorySize))\n {\n return false;\n }\n }\n\n extraMemoryLocation = VirtualAllocEx(\n ph.amnesiaHandle,\n nullptr,\n extraMemorySize,\n MEM_COMMIT | MEM_RESERVE,\n PAGE_EXECUTE_READWRITE\n );\n if (extraMemoryLocation == nullptr)\n {\n printf(\"error when using VirtualAllocEx: %d\\n\", GetLastError());\n return false;\n }\n\n bool injectionSucceeded = false;\n if (skipFlashbacks)\n {\n injectionSucceeded = injectSkipInstructions(forExtraMemory.get(), si, ph, howManyNames, spacePerName, (uint32_t)extraMemoryLocation, extraMemorySize);\n }\n else\n {\n injectionSucceeded = injectWaitInstructions(forExtraMemory.get(), si, ph, howManyNames, spacePerName, (uint32_t)extraMemoryLocation, extraMemorySize);\n }\n\n if (!injectionSucceeded)\n {\n bool extraMemoryFreed = VirtualFreeEx(\n ph.amnesiaHandle,\n extraMemoryLocation,\n 0,\n MEM_RELEASE\n );\n extraMemoryLocation = nullptr;\n if (!extraMemoryFreed)\n {\n printf(\"WARNING: error when using VirtualFreeEx: %d\\ncouldn't release VirtualAllocEx memory\\n\", GetLastError());\n }\n\n return false;\n }\n\n printf(\"amnesia has been injected\\n\");\n return true;\n}\n\nDWORD codeInjectionMain(bool skipFlashbacks)\n{\n LPVOID extraMemoryLocation = nullptr; // this is here so the virtual pages can be released in the catch block if an unexpected error happens\n HANDLE amnesiaHandle = nullptr; // needed when catching exception\n\n try\n {\n // LiveSplit uses these functions, so they're probably safe to use even though they're undocumented\n NTFUNCTION NtSuspendProcess = nullptr;\n NTFUNCTION NtResumeProcess = nullptr;\n\n SavedInstructions si;\n\n DWORD amnesiaPid = findAmnesiaPid(si);\n\n if (amnesiaPid == (DWORD)-1)\n {\n printf(\"you can now close this window\\n\");\n return (DWORD)-1;\n }\n\n ProcessHelper ph(amnesiaPid);\n\n if (!ph.checkIfProcessIsAmnesia())\n {\n printf(\"you can now close this window\\n\");\n return (DWORD)-1;\n }\n\n amnesiaHandle = ph.amnesiaHandle;\n\n bool ntFunctionsFound = findNtFunctions(NtSuspendProcess, NtResumeProcess);\n\n if (ntFunctionsFound)\n {\n NtSuspendProcess(ph.amnesiaHandle);\n }\n\n bool injectionSucceeded = injectWhileSuspended(ph, si, extraMemoryLocation, skipFlashbacks);\n\n if (ntFunctionsFound)\n {\n NtResumeProcess(ph.amnesiaHandle);\n }\n\n return injectionSucceeded ? amnesiaPid : (DWORD)-1;\n }\n catch (const std::runtime_error& e)\n {\n char const* fixC4101Warning = e.what();\n printf(\"unexpected error: %s\\n\", fixC4101Warning);\n\n if (extraMemoryLocation)\n {\n bool extraMemoryFreed = VirtualFreeEx(\n amnesiaHandle,\n extraMemoryLocation,\n 0,\n MEM_RELEASE\n );\n extraMemoryLocation = nullptr;\n if (!extraMemoryFreed)\n {\n printf(\"WARNING: error when using VirtualFreeEx: %d\\ncouldn't release VirtualAllocEx memory\\n\", GetLastError());\n }\n }\n }\n\n return (DWORD)-1;\n}\n\n#include <cstdio>\n#include <memory>\n#include <stdexcept>\n\nconst size_t fhelperBufferSize = 8192;\n\ntemplate <typename T>\nclass FileHelper\n{\npublic:\n FileHelper(const FileHelper& fhelper) = delete;\n FileHelper& operator=(FileHelper other) = delete;\n FileHelper(FileHelper&&) = delete;\n FileHelper& operator=(FileHelper&&) = delete;\n\n explicit FileHelper(const wchar_t* filename) // there isn't wfopen on linux\n {\n#ifndef _WIN32\n throw std::runtime_error(\"FileHelper wchar_t* constructor only works on Windows\");\n#endif\n if (_wfopen_s(&_f, filename, L\"rb\") != 0 || !_f)\n {\n printf(\"FileHelper couldn't open %ls\\n\", filename);\n throw std::runtime_error(\"FileHelper fopen failure in const wchar_t* constructor\");\n }\n }\n\n explicit FileHelper(const char* filename)\n {\n#ifdef _WIN32\n if (fopen_s(&_f, filename, \"rb\") != 0 || !_f)\n#else\n if (!(_f = fopen(filename, \"rb\")))\n#endif\n {\n printf(\"FileHelper couldn't open %s\\n\", filename);\n throw std::runtime_error(\"FileHelper fopen failure in const char* constructor\");\n }\n }\n\n ~FileHelper()\n {\n if (_f)\n {\n fclose(_f);\n }\n }\n\n bool getCharacter(T& ch)\n {\n if (_bufferPosition == _charactersRead)\n {\n _bufferPosition = 0;\n _charactersRead = (int)fread(_buffer.get(), sizeof(T), fhelperBufferSize / sizeof(T), _f);\n\n if (!_charactersRead)\n {\n return false;\n }\n }\n\n ch = _buffer[_bufferPosition];\n _bufferPosition++;\n\n return true;\n }\n\n void resetFile()\n {\n if (fseek(_f, 0, SEEK_SET) != 0)\n {\n throw std::runtime_error(\"FileHelper fseek failure in resetFile\");\n }\n\n _bufferPosition = 0;\n _charactersRead = 0;\n }\n\nprivate:\n FILE* _f = nullptr;\n std::unique_ptr<T[]> _buffer = std::make_unique<T[]>(fhelperBufferSize / sizeof(T));\n int _bufferPosition = 0;\n int _charactersRead = 0;\n};\n\nThis is code for a mod for the open source game Amnesia: The Dark Descent which injects it to make it either skip or wait through dialogue during load screens.\nexample: https://youtu.be/mMikDj3KSGg\nIf it's skipping the dialogue, it injects here: https://github.com/FrictionalGames/AmnesiaTheDarkDescent/blob/acc95cdedd6c94db89dc924eb9afa23185df562f/amnesia/src/game/LuxMapHandler.cpp#L633\nAnd then it skips by calling this function for each possible dialogue: https://github.com/FrictionalGames/AmnesiaTheDarkDescent/blob/acc95cdedd6c94db89dc924eb9afa23185df562f/HPL2/core/sources/sound/SoundHandler.cpp#L709\nIf it's waiting through the dialogue, it injects here: https://github.com/FrictionalGames/AmnesiaTheDarkDescent/blob/acc95cdedd6c94db89dc924eb9afa23185df562f/amnesia/src/game/LuxMapHandler.cpp#L685\nAnd then it checks if any of the dialogues are playing by calling this function for each possible dialogue: https://github.com/FrictionalGames/AmnesiaTheDarkDescent/blob/acc95cdedd6c94db89dc924eb9afa23185df562f/HPL2/core/sources/sound/SoundHandler.cpp#L797\n"
I started studying web development a few months ago and to practice my skills I decided to do the game of rock, paper, scissors. Here are some questions for review: Is the use of HTML semantics correct and how could I improve it? How could I improve the CSS and JavaScript code in terms of readability, optimization and...
I wrote a simple script to set permissions for a file or folder for some embedded Linux devices as part of a larger setup script. This method would be called on less than 20 files and folders. It seems to work correctly. For the Linux OS, the stat command is not available. Please let me know if anyone notices any issu...
I have a site that I made to parse parts of Wikipedia articles for me. Part of this is removing parentheticals and citations. I came up with the following implementation: export default function removeBracketsAndContents( input: string, openingBracket: string, closingBracket: string ) { let remainingInput = inp...
Per feed back for this question, I have written an unsigned 128 bit integer for Windows. The class first determines if it is in a 64 bit environment. It only creates the class if it is in a Windows 64 bit environment that supports MS intrinsic functions. Else it falls back to 32 bit mode. It also checks if either G...
I have written a command-line tool to switch between different java versions, and as this is my first larger PowerShell script, I would like to get some feedback on the code. The powershell file expects to find a list of directories containing JDKs in the directory of the script, lists them, and prompts the user to cho...
here is the second game I have made. its not easy and I was hoping someone could test it and bring some improvements to the table. fun project for learning. import random class Ship: def __init__(self, name, symbol, position): self.name = name self.symbol = symbol self.health = 100 self.crew = 100 ...
#include "gmpxx.h" #include <thread> #include <string> using namespace std; // g++ -o a2.out testing.cpp -lgmp -lgmpxx -lpthread -O3 // time ./a2.out int doer(int num) { mpz_class data_x; mpz_class data_y; if (num == 61) { data_x = "7291606492164737008501663535535623193849905819354390...
Below is a function template that tokenizes a given std::basic_string_view using a given delimiter and assigns the tokens to a buffer (via a std::span). Its main advantage is that it doesn't construct a vector<string_view> and return it. Instead, it assigns each found token to an element of the span parameter. And the ...
I'm writing a small utility operator which applies two functions to an argument pair and strands the results. The pair can either be given as two arguments or as a single argument with two elements. Either way, the left operand is applied to the left value and the right operand to the right value: _n_←{⍺←⊢ ⋄ (a b)←⍺ ⍵ ...
I have a Python function that will terminate when some condition is fulfilled.That could happen after the first (easy) step. But more steps (of increasing complexity) may follow. Below is the simplified example function find_slugs. For each person in database it finds a slug, which is unique and as short as possible. T...
I have written a code to stitch 2 images using SIFT keypoint descriptor and homography matrix for perspective transform. Are there any areas where code an be improved or optimized? #include <opencv2/opencv.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/xfeatures2d.hpp> #include <op...
function factorial(nb) { let tab = []; if (nb > 0) { tab.push(nb); tab = tab.concat(factorial(nb - 1)); } return tab; } // Calculate factorial for number 3 const array = factorial(3); // Calculate the final factorial value by reducing the array const factorialValue = array.reduce((accumulator, cur...
Background I was working on a coding challenge as part of an interview process. I had to create a REST API where the user can report sensor data and query derived metrics based on several filter criteria. Ingest In the sensor data ingest handler I could simply annotate the expected request body entity with validation r...
Context I am making a system, where different clients issue queries A query is resolved by issuing a set of subqueries I have an invalidation-worker, which gets notified when subqueries go stale Goal When a subquery goes stale, I want to notify the clients which have made this subquery Solution To do this, I am thi...
I want to write on failure to either STDOUT or STDERR a clean, simple error message for the user, without the (verbose) backtrace, and then exit with a failed status. I am currently using raise to raise exceptions in various parts of the code that I call. I am using begin ... rescue block and abort that wraps the entir...
After my previous question I made several changes and came up with this. Remember: I wrote this for PHP 7.0.33. I'm aware I should upgrade, save the advice :) class Table { private $orientation = "hz"; // "vt" not implemented yet private $table_title = ""; private $headers = array(); private $data = ar...
In my answer to string_view tokenizer function template I suggested that a flexible tokeniser would yield a Range that could be iterated over. This is my implementation of such a tokeniser. #include <concepts> #include <cstddef> #include <functional> #include <iterator> #include <ranges> #include <string_view> #includ...
I have made a basic neural network in python. The idea is the neural network can have any structure you want, not just the standard layers where every neuron is connected to every neuron in the next layer. from numpy import exp class Feed_forward_network: """ Feed_forward_network inputs: the number of inpu...
I made a function that prompts me for values of variables (formatted %^{var1}) it found in a string and fills in said values. (defun fill-var-in-string (STRING) "Find variables in a string, prompt for a value and fill in STRING." (let ((filled STRING)) (while (string-match "%^{\\([^}]*\\)}" STRING (match-end 0)...
Say I have a framework, which should catch any exceptions raised from user code, and actually do something with it, such as converting it to a return value namespace framework { template<class Handler> status do_stuff(Handler handler) { try { return handler(); } c...
This is an exercise I solved in the PPP book in C++. If there's a better way I could have done something, please tell me. (No main() and Date (just year)) Thank you! For context here is the exercise: This exercise and the next few require you to design and implement a Book class, such as you can imagine as part of so...
I am working on one of my assignments (Hash Tables) for my Data Structures class(1st year), the assignment focuses on OOP and understanding of Hash Tables. Restrictions: Usage of raw pointers C++11 standard Have to use vectors for my HashTable (can't use std::map) The goal of this assignment is to make a Covid-19 tab...
I have this code for a factory design pattern that will take into account any number of arguments in the constructor. Through a static boolean in the class a certain constructor is registered in the factory. However it requires reinterpret_cast to run. Also the boolean strategy is not very elegant (it works, but If I h...
A school's task: There are two sequences n_tab and m_tab. For every element m in m_tab display how many n_tab elements are lesser than m_tab[i] up to the first n_tab element greater than m_tab[i]. Value limits: 1 <= n_tab.size(), m_tab.size() <= 500000 All elements of n_tab and m_tab are >= 1 and <= 10^9 Example: Inpu...