text stringlengths 1 2.12k | source dict |
|---|---|
c++, windows, assembly
if (charactersWritten != filepathLength || filepathBuffer != filepathBufferCopy) // no longer looking at exe memory
{
break;
}
queryAddress += mbi.RegionSize;
}
while (VirtualQueryEx(amnesiaHandle, (LPCVOID)queryAddress, &mbi, sizeof(mbi)) != 0);
printf("couldn't find .text area in Amnesia.exe or Amnesia_NoSteam.exe memory\n");
return false;
}
bool getByte(unsigned char& b)
{
if (bytesLeft == 0)
{
return false;
}
if (bufferPosition == pageSize)
{
bufferPosition = 0;
memoryOffset += pageSize;
bool readSucceeded = ReadProcessMemory(
amnesiaHandle,
(LPCVOID)memoryOffset,
(LPVOID)buffer.get(),
pageSize,
nullptr
);
if (!readSucceeded)
{
printf("ProcessHelper ReadProcessMemory error in getByte: %d\nat memory address: %u\n", GetLastError(), memoryOffset);
return false;
}
}
b = buffer[bufferPosition];
bufferPosition++;
bytesLeft--;
return true;
}
};
struct SavedInstructions
{
unsigned char gettingSoundHandler[14]{};
unsigned char beforeFadeOutAllBytes[7]{};
unsigned char sleepCallBytes[6]{};
unsigned char loadEndBytes[5]{};
uint32_t stopFunctionLocation = 0;
uint32_t isPlayingLocation = 0;
uint32_t beforeFadeOutAllLocation = 0;
uint32_t loadEndLocation = 0;
bool isSteamVersion = false;
};
DWORD searchUsingSnapshotHandle(SavedInstructions& si, PROCESSENTRY32& processEntry, HANDLE snapshot)
{
if (!Process32First(snapshot, &processEntry))
{
printf("error when using Process32First: %d\n", GetLastError());
return (DWORD)-1;
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
do
{
if ((si.isSteamVersion = (wcscmp(processEntry.szExeFile, steamName) == 0)) || wcscmp(processEntry.szExeFile, nosteamName) == 0)
{
return processEntry.th32ProcessID;
}
}
while (Process32Next(snapshot, &processEntry));
return (DWORD)-1;
}
DWORD findAmnesiaPid(SavedInstructions& si)
{
DWORD amnesiaPid = (DWORD)-1;
PROCESSENTRY32 processEntry{};
processEntry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
{
printf("error when using CreateToolhelp32Snapshot: %d\n", GetLastError());
return amnesiaPid;
}
amnesiaPid = searchUsingSnapshotHandle(si, processEntry, snapshot);
CloseHandle(snapshot);
if (amnesiaPid == (DWORD)-1)
{
printf("couldn't find amnesia process\n");
}
return amnesiaPid;
}
bool findNtFunctions(NTFUNCTION& NtSuspendProcess, NTFUNCTION& NtResumeProcess)
{
HMODULE ntdllHandle = GetModuleHandle(L"ntdll.dll");
if (!ntdllHandle)
{
printf("WARNING: error using GetModuleHandle to find ntdll.dll: %d\nAmnesia won't be suspended during code injection\n", GetLastError());
return false;
}
NtSuspendProcess = (NTFUNCTION)GetProcAddress(ntdllHandle, "NtSuspendProcess");
if (!NtSuspendProcess)
{
printf("WARNING: error using GetProcAddress to find NtSuspendProcess: %d\nAmnesia won't be suspended during code injection\n", GetLastError());
return false;
}
NtResumeProcess = (NTFUNCTION)GetProcAddress(ntdllHandle, "NtResumeProcess");
if (!NtResumeProcess)
{
printf("WARNING: error using GetProcAddress to find NtResumeProcess: %d\nAmnesia won't be suspended during code injection\n", GetLastError());
return false;
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
return true;
}
void addNewValueToMemorySlice(unsigned char* memorySlice, size_t size, unsigned char newEndValue)
{
for (size_t i = 0; i < size - 1; i++)
{
memorySlice[i] = memorySlice[i + 1];
}
memorySlice[size - 1] = newEndValue;
}
// this is fast enough for the size of the game
// if it needs to be faster, try making memorySlice a circular buffer
bool findInstructions(SavedInstructions& si, ProcessHelper& ph)
{
unsigned char b = 0;
unsigned char memorySlice[16]{}; // give this at least the size of the longest byte pattern
for (int i = 1; i < sizeof(memorySlice); i++)
{
if (!ph.getByte(b))
{
return false;
}
memorySlice[i] = b;
}
int locationsFound = 0; // if this ends up being greater than 5, there were duplicate injection location patterns
bool isv = si.isSteamVersion; // on the steam version, the first mov instruction is 6 bytes long instead of 5
for (size_t i = 0; ph.getByte(b); i++)
{
addNewValueToMemorySlice(memorySlice, sizeof(memorySlice), b); | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
if (memorySlice[0] == 0xf6 && memorySlice[1] == 0x74 && memorySlice[7] == 0x75 && memorySlice[9] == 0x80)
{
locationsFound++;
si.stopFunctionLocation = ph.amnesiaMemoryLocation + i - 16;
}
else if (memorySlice[0] == 0x48 && memorySlice[8] == 0xd0 && memorySlice[9] == 0x5d)
{
locationsFound++;
si.isPlayingLocation = ph.amnesiaMemoryLocation + i - 17;
}
else if (memorySlice[0] == 0x75 && memorySlice[2] == 0x56 && memorySlice[4] == 0x15 && memorySlice[9] == 0x8b)
{
locationsFound++;
memcpy(si.sleepCallBytes, &memorySlice[3], sizeof(si.sleepCallBytes));
}
else if (
(memorySlice[5] == 0xff && memorySlice[6] == 0x50 && memorySlice[8] == 0xe8 && memorySlice[13] == 0x2b)
|| (si.isSteamVersion && memorySlice[5] == 0xff && memorySlice[6] == 0xd0 && memorySlice[7] == 0xe8 && memorySlice[13] == 0x45))
{
locationsFound++;
si.loadEndLocation = ph.amnesiaMemoryLocation + i;
if (memorySlice[0] == 0xe9) // the jump instruction is already there, so amnesia must have already been injected
{
printf("amnesia is already injected\n");
return false;
}
memcpy(si.loadEndBytes, memorySlice, sizeof(si.loadEndBytes));
}
else if (memorySlice[8 + isv] == 0x40 && memorySlice[10 + isv] == 0x8b && memorySlice[11 + isv] == 0x40 && memorySlice[14 + isv] == 0x01)
{
locationsFound++;
memcpy(si.gettingSoundHandler, memorySlice, sizeof(si.gettingSoundHandler));
i += 16 + isv;
si.beforeFadeOutAllLocation = ph.amnesiaMemoryLocation + i;
for (int n = 0; n < 16 + isv; n++)
{
ph.getByte(b);
addNewValueToMemorySlice(memorySlice, sizeof(memorySlice), b);
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
if (memorySlice[0] == 0xe9) // the jump instruction is already there, so amnesia must have already been injected
{
printf("amnesia is already injected\n");
return false;
}
memcpy(si.beforeFadeOutAllBytes, memorySlice, sizeof(si.beforeFadeOutAllBytes));
}
}
bool allLocationsFound = (
si.stopFunctionLocation != 0
&& si.isPlayingLocation != 0
&& si.beforeFadeOutAllLocation != 0
&& si.loadEndLocation != 0
&& si.sleepCallBytes[0] != 0
);
if (locationsFound > 5 || (locationsFound == 5 && !allLocationsFound))
{
printf("error: duplicate injection location patterns found\n");
return false;
}
else if (allLocationsFound)
{
return true;
}
printf("couldn't find all instruction locations\n");
return false;
}
// this needs to be done to find how much memory to allocate for the virtual pages
void preprocessFlashbackNames(FileHelper<char>& fh, uint32_t& howManyNames, uint32_t& longestName)
{
char ch = '\0';
uint32_t currentNameLength = 0;
while (fh.getCharacter(ch))
{
if (ch == '\r') // windows puts this at the end of lines
{
continue;
}
else if (ch == '\n')
{
if (currentNameLength > longestName)
{
longestName = currentNameLength;
}
howManyNames += currentNameLength > 0;
currentNameLength = 0;
}
else
{
currentNameLength++;
}
}
// last line
if (currentNameLength > longestName)
{
longestName = currentNameLength;
}
howManyNames += currentNameLength > 0;
fh.resetFile();
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
fh.resetFile();
}
bool setFlashbackNames(unsigned char* forExtraMemory, FileHelper<char>& fh, uint32_t startOffset, uint32_t spacePerName, uint32_t extraMemorySize)
{
char ch = '\0';
uint32_t writeOffset = startOffset;
uint32_t nameSize = 0;
while (fh.getCharacter(ch))
{
if (ch == '\r') // windows puts this at the end of lines
{
continue;
}
else if (ch == '\n')
{
if (nameSize > 0)
{
memcpy(&forExtraMemory[writeOffset + spacePerName - 8], &nameSize, sizeof(nameSize));
writeOffset += spacePerName;
nameSize = 0;
}
}
else
{
if (nameSize == spacePerName - 9) // this shouldn't ever happen, flashback line names shouldn't need to be long enough to cause this
{
printf("a flashback line name was longer than expected, possibly because of integer overflow\n");
return false;
}
else if (writeOffset + nameSize >= extraMemorySize) // this also shouldn't ever happen, there shouldn't need to be enough to cause this
{
printf("there were more flashback line names than expected, possibly because of integer overflow\n");
return false;
}
forExtraMemory[writeOffset + nameSize] = (unsigned int)ch;
nameSize++;
}
}
if (nameSize > 0)
{
memcpy(&forExtraMemory[writeOffset + spacePerName - 8], &nameSize, sizeof(nameSize));
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
bool injectSkipInstructions(
unsigned char* forExtraMemory,
SavedInstructions& si,
ProcessHelper& ph,
uint32_t howManyNames,
uint32_t spacePerName,
uint32_t extraMemoryLocation,
uint32_t extraMemorySize)
{
// this is jumped to before a call instruction, so the caller-saved registers should already be saved
unsigned char flashbackSkipInstructions[flashbackSkipInstructionsSize] = {
// jmp destination from before calling cSoundHandler::FadeOutAll
0xd9, 0x1c, 0x24, // 0000 // fstp dword ptr [esp] // copied
0x6a, 0x01, // 0003 // push 0x01 // copied
0x8b, 0xc8, // 0005 // mov ecx, eax // copied
0x53, // 0007 // push ebx // stack depth +4
0x57, // 0008 // push edi // stack depth +8
0x51, // 0009 // push ecx // cSoundHandler object // stack depth +12
0xbb, 0x00, 0x00, 0x00, 0x00, // 0010 // mov ebx, start of first flashback name // check
0x90, // 0015 // nop so loop is aligned on byte 16
// start of loop
0x89, 0x1d, 0x00, 0x00, 0x00, 0x00, // 0016 // mov [string object ptr location], ebx // ptr to characters // check
0x8b, 0xbb, 0x00, 0x00, 0x00, 0x00, // 0022 // mov edi, dword ptr [ebx + spacePerName - 8] // flashback name size
0x89, 0x3d, 0x00, 0x00, 0x00, 0x00, // 0028 // mov dword ptr [string object size location], edi // check
0x68, 0x00, 0x00, 0x00, 0x00, // 0034 // push string object ptr location // stack depth +16 // check
0xe8, 0x00, 0x00, 0x00, 0x00, // 0039 // call cSoundHandler::Stop // stack depth +12
0x8b, 0x0c, 0x24, // 0044 // mov ecx, dword ptr [esp] // cSoundHandler object | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
0x81, 0xc3, 0x00, 0x00, 0x00, 0x00, // 0047 // add ebx, spacePerName // start of next string data
0x81, 0xfb, 0x00, 0x00, 0x00, 0x00, // 0053 // cmp ebx, end of flashback names // check
0x75, 0xd3, // 0059 // jnz -45
// end of loop | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
0x59, // 0061 // pop ecx // stack depth +8
0x5f, // 0062 // pop edi // stack depth +4
0x5b, // 0063 // pop ebx // stack depth +0
0xe9, 0x00, 0x00, 0x00, 0x00, // 0064 // jmp to before calling cSoundHandler::FadeOutAll, 0048baad
0x90, // 0069 // nop
};
unsigned char jmpInstruction[sizeof(si.beforeFadeOutAllBytes)] = {0xe9, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90};
uint32_t stdStringCapacity = spacePerName - 1;
memcpy(&forExtraMemory[sizeof(flashbackSkipInstructions) + 20], &stdStringCapacity, sizeof(uint32_t));
uint32_t startOffset = sizeof(flashbackSkipInstructions) + 64; // 64 bytes used for std::string object + padding
memcpy(&flashbackSkipInstructions[0], si.beforeFadeOutAllBytes, sizeof(si.beforeFadeOutAllBytes));
uint32_t firstFlashbackNameLocation = extraMemoryLocation + startOffset;
memcpy(&flashbackSkipInstructions[11], &firstFlashbackNameLocation, sizeof(uint32_t));
uint32_t stringObjectPtrLocation = extraMemoryLocation + sizeof(flashbackSkipInstructions);
memcpy(&flashbackSkipInstructions[18], &stringObjectPtrLocation, sizeof(uint32_t));
memcpy(&flashbackSkipInstructions[35], &stringObjectPtrLocation, sizeof(uint32_t));
uint32_t flashbackNameSizeOffset = spacePerName - 8;
memcpy(&flashbackSkipInstructions[24], &flashbackNameSizeOffset, sizeof(uint32_t));
uint32_t stringObjectSizeLocation = extraMemoryLocation + sizeof(flashbackSkipInstructions) + 16;
memcpy(&flashbackSkipInstructions[30], &stringObjectSizeLocation, sizeof(uint32_t));
uint32_t stopFunctionOffset = si.stopFunctionLocation - (extraMemoryLocation + 44);
memcpy(&flashbackSkipInstructions[40], &stopFunctionOffset, sizeof(stopFunctionOffset));
memcpy(&flashbackSkipInstructions[49], &spacePerName, sizeof(spacePerName)); | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
memcpy(&flashbackSkipInstructions[49], &spacePerName, sizeof(spacePerName));
uint32_t endOfFlashbackNames = extraMemoryLocation + startOffset + (howManyNames * spacePerName);
memcpy(&flashbackSkipInstructions[55], &endOfFlashbackNames, sizeof(uint32_t));
uint32_t fadeOutAllOffset = (si.beforeFadeOutAllLocation + sizeof(si.beforeFadeOutAllBytes)) - (extraMemoryLocation + 69);
memcpy(&flashbackSkipInstructions[65], &fadeOutAllOffset, sizeof(fadeOutAllOffset));
memset(&flashbackSkipInstructions[70], 0xcc, sizeof(flashbackSkipInstructions) - 70); // int3
memcpy(forExtraMemory, flashbackSkipInstructions, sizeof(flashbackSkipInstructions));
SIZE_T bytesWritten = 0;
bool wpmSucceeded = false;
wpmSucceeded = WriteProcessMemory(
ph.amnesiaHandle,
(LPVOID)extraMemoryLocation,
(LPCVOID)forExtraMemory,
extraMemorySize,
nullptr
);
if (!wpmSucceeded)
{
printf("error when calling WriteProcessMemory to write to allocated virtual page(s): %d\nat memory address: %u\n", GetLastError(), extraMemoryLocation);
return false;
}
uint32_t offsetFromCheckMapChange = (extraMemoryLocation + 0) - (si.beforeFadeOutAllLocation + 5);
memcpy(&jmpInstruction[1], &offsetFromCheckMapChange, sizeof(offsetFromCheckMapChange));
wpmSucceeded = WriteProcessMemory(
ph.amnesiaHandle,
(LPVOID)si.beforeFadeOutAllLocation,
(LPCVOID)jmpInstruction,
sizeof(si.beforeFadeOutAllBytes),
&bytesWritten
); | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
if (bytesWritten < sizeof(si.beforeFadeOutAllBytes))
{
printf("JMP INSTRUCTION ONLY PARTIALLY WRITTEN IN CHECKMAPCHANGE\nRESTART AMNESIA OR IT WILL CRASH ON MAP CHANGE\nerror: %d\n", GetLastError());
return false;
}
else if (!wpmSucceeded)
{
printf("error when calling WriteProcessMemory to write jmp instruction in CheckMapChange: %d\nat memory address: %u\n", GetLastError(), si.beforeFadeOutAllLocation);
return false;
}
return true;
}
bool injectWaitInstructions(
unsigned char* forExtraMemory,
SavedInstructions& si,
ProcessHelper& ph,
uint32_t howManyNames,
uint32_t spacePerName,
uint32_t extraMemoryLocation,
uint32_t extraMemorySize)
{
// this is jumped to before a call instruction, so the caller-saved registers should already be saved
unsigned char flashbackWaitInstructions[flashbackWaitInstructionsSize] = {
0x53, // 0000 // push ebx // stack depth +4
0x57, // 0001 // push edi // stack depth +8
0x56, // 0002 // push esi // stack depth +12
0x51, // 0003 // push ecx // steam version copied instructions need ecx // stack depth +16
0x51, // 0004 // push ecx // dummy push // stack depth +20
0x51, // 0005 // push ecx // dummy push // stack depth +24
// jmp destination from near the end of the map load
// starting with 13-14 bytes to get the cSoundHandler object in eax
// the last byte is a nop instruction because the NoSteam version only uses 13 bytes to get the cSoundHandler object
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, // 0006 // getting cSoundHandler object | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
0x8b, 0xc8, // 0020 // mov ecx, eax // moving cSoundHandler object to ecx
0x51, // 0022 // push ecx // cSoundHandler object // stack depth +28
0xbb, 0x00, 0x00, 0x00, 0x00, // 0023 // mov ebx, start of first flashback name
0x31, 0xf6, // 0028 // xor esi, esi
0x90, 0x90, // 0030 // nops so loop is aligned on byte 32
// start of loop
0x89, 0x1d, 0x00, 0x00, 0x00, 0x00, // 0032 // mov [string object ptr location], ebx // ptr to characters
0x8b, 0xbb, 0x00, 0x00, 0x00, 0x00, // 0038 // mov edi, dword ptr [ebx + spacePerName - 8] // flashback name size
0x89, 0x3d, 0x00, 0x00, 0x00, 0x00, // 0044 // mov dword ptr [string object size location], edi
0x8b, 0x0c, 0x24, // 0050 // mov ecx, dword ptr [esp] // cSoundHandler object
0x68, 0x00, 0x00, 0x00, 0x00, // 0053 // push string object ptr location // stack depth +32
0xe8, 0x00, 0x00, 0x00, 0x00, // 0058 // call cSoundHandler::IsPlaying // stack depth +28
0x09, 0xc6, // 0063 // or esi, eax
0x81, 0xc3, 0x00, 0x00, 0x00, 0x00, // 0065 // add ebx, spacePerName // start of next string data
0x81, 0xfb, 0x00, 0x00, 0x00, 0x00, // 0071 // cmp ebx, end of flashback names
0x75, 0xd1, // 0077 // jnz -47
0x83, 0xfe, 0x00, // 0079 // cmp esi, 0
0x74, 0x10, // 0082 // jz 16
0x56, // 0084 // push esi // stack depth +32 // esi should be 1 here
0xff, 0x15, 0x00, 0x00, 0x00, 0x00, // 0085 // call Sleep // stack depth +28
0xbb, 0x00, 0x00, 0x00, 0x00, // 0091 // mov ebx, start of first flashback name | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
0xbb, 0x00, 0x00, 0x00, 0x00, // 0091 // mov ebx, start of first flashback name
0x31, 0xf6, // 0096 // xor esi, esi
0x74, 0xbc, // 0098 // jz -68
// end of loop | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
0x83, 0xc4, 0x0c, // 0100 // add esp, 12 // stack depth +16
0x59, // 0103 // pop ecx // stack depth +12
0x5e, // 0104 // pop esi // stack depth +8
0x5f, // 0105 // pop edi // stack depth +4
0x5b, // 0106 // pop ebx // stack depth +0
0x00, 0x00, 0x00, 0x00, 0x00, // 0107 // copied instructions
0xe9, 0x00, 0x00, 0x00, 0x00, // 0112 // jmp to end of load
0x90, // 0117 // nop
};
unsigned char jmpInstruction[sizeof(si.beforeFadeOutAllBytes)] = {0xe9, 0x00, 0x00, 0x00, 0x00};
uint32_t stdStringCapacity = spacePerName - 1;
memcpy(&forExtraMemory[sizeof(flashbackWaitInstructions) + 20], &stdStringCapacity, sizeof(uint32_t));
uint32_t startOffset = sizeof(flashbackWaitInstructions) + 64; // 64 bytes used for std::string object + padding
memcpy(&flashbackWaitInstructions[6], si.gettingSoundHandler, sizeof(si.gettingSoundHandler) - !(si.isSteamVersion));
uint32_t firstFlashbackNameLocation = extraMemoryLocation + startOffset;
memcpy(&flashbackWaitInstructions[24], &firstFlashbackNameLocation, sizeof(uint32_t));
memcpy(&flashbackWaitInstructions[92], &firstFlashbackNameLocation, sizeof(uint32_t));
uint32_t stringObjectPtrLocation = extraMemoryLocation + sizeof(flashbackWaitInstructions);
memcpy(&flashbackWaitInstructions[34], &stringObjectPtrLocation, sizeof(uint32_t));
memcpy(&flashbackWaitInstructions[54], &stringObjectPtrLocation, sizeof(uint32_t));
uint32_t flashbackNameSizeOffset = spacePerName - 8;
memcpy(&flashbackWaitInstructions[40], &flashbackNameSizeOffset, sizeof(uint32_t)); | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
uint32_t stringObjectSizeLocation = extraMemoryLocation + sizeof(flashbackWaitInstructions) + 16;
memcpy(&flashbackWaitInstructions[46], &stringObjectSizeLocation, sizeof(uint32_t));
uint32_t isPlayingOffset = si.isPlayingLocation - (extraMemoryLocation + 63);
memcpy(&flashbackWaitInstructions[59], &isPlayingOffset, sizeof(isPlayingOffset));
memcpy(&flashbackWaitInstructions[67], &spacePerName, sizeof(spacePerName));
uint32_t endOfFlashbackNames = extraMemoryLocation + startOffset + (howManyNames * spacePerName);
memcpy(&flashbackWaitInstructions[73], &endOfFlashbackNames, sizeof(uint32_t));
memcpy(&flashbackWaitInstructions[85], si.sleepCallBytes, sizeof(si.sleepCallBytes));
memcpy(&flashbackWaitInstructions[107], si.loadEndBytes, sizeof(si.loadEndBytes));
uint32_t loadEndOffset = (si.loadEndLocation + sizeof(si.loadEndBytes)) - (extraMemoryLocation + 117);
memcpy(&flashbackWaitInstructions[113], &loadEndOffset, sizeof(loadEndOffset));
memset(&flashbackWaitInstructions[118], 0xcc, sizeof(flashbackWaitInstructions) - 118); // int3
memcpy(forExtraMemory, flashbackWaitInstructions, sizeof(flashbackWaitInstructions));
SIZE_T bytesWritten = 0;
bool wpmSucceeded = false;
wpmSucceeded = WriteProcessMemory(
ph.amnesiaHandle,
(LPVOID)extraMemoryLocation,
(LPCVOID)forExtraMemory,
extraMemorySize,
nullptr
);
if (!wpmSucceeded)
{
printf("error when calling WriteProcessMemory to write to allocated virtual page(s): %d\nat memory address: %u\n", GetLastError(), extraMemoryLocation);
return false;
}
uint32_t offsetFromCheckMapChange = (extraMemoryLocation + 0) - (si.loadEndLocation + 5);
memcpy(&jmpInstruction[1], &offsetFromCheckMapChange, sizeof(offsetFromCheckMapChange)); | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
wpmSucceeded = WriteProcessMemory(
ph.amnesiaHandle,
(LPVOID)si.loadEndLocation,
(LPCVOID)jmpInstruction,
sizeof(si.loadEndBytes),
&bytesWritten
);
if (bytesWritten < sizeof(si.loadEndBytes))
{
printf("JMP INSTRUCTION ONLY PARTIALLY WRITTEN IN CHECKMAPCHANGE\nRESTART AMNESIA OR IT WILL CRASH ON MAP CHANGE\nerror: %d\n", GetLastError());
return false;
}
else if (!wpmSucceeded)
{
printf("error when calling WriteProcessMemory to write jmp instruction in CheckMapChange: %d\nat memory address: %u\n", GetLastError(), si.loadEndLocation);
return false;
}
return true;
}
bool injectWhileSuspended(ProcessHelper& ph, SavedInstructions& si, LPVOID& extraMemoryLocation, bool skipFlashbacks)
{
if (!ph.findExecutableMemoryLocation())
{
return false;
}
size_t executableRegionSize = ph.bytesLeft;
if (!findInstructions(si, ph))
{
return false;
}
uint32_t howManyNames = 0;
uint32_t longestName = 0;
uint32_t spacePerName = 0;
uint32_t nameAreaOffset = 0;
uint32_t extraMemorySize = 0;
std::unique_ptr<unsigned char[]> forExtraMemory;
// 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
{
FileHelper<char> fh(flashbackNameFile);
preprocessFlashbackNames(fh, howManyNames, longestName);
if (howManyNames == 0)
{
printf("no flashback line names found in %s\n", flashbackNameFile);
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
spacePerName = (((longestName + 9) / 64) + (((longestName + 9) % 64) != 0)) * 64; // 8 bytes to store name size, 1 byte for null character
nameAreaOffset = (skipFlashbacks ? flashbackSkipInstructionsSize : flashbackWaitInstructionsSize) + 64; // 64 bytes to store string object plus padding
extraMemorySize = nameAreaOffset + (spacePerName * howManyNames);
forExtraMemory = std::make_unique<unsigned char[]>(extraMemorySize);
if (!setFlashbackNames(forExtraMemory.get(), fh, nameAreaOffset, spacePerName, extraMemorySize))
{
return false;
}
}
extraMemoryLocation = VirtualAllocEx(
ph.amnesiaHandle,
nullptr,
extraMemorySize,
MEM_COMMIT | MEM_RESERVE,
PAGE_EXECUTE_READWRITE
);
if (extraMemoryLocation == nullptr)
{
printf("error when using VirtualAllocEx: %d\n", GetLastError());
return false;
}
bool injectionSucceeded = false;
if (skipFlashbacks)
{
injectionSucceeded = injectSkipInstructions(forExtraMemory.get(), si, ph, howManyNames, spacePerName, (uint32_t)extraMemoryLocation, extraMemorySize);
}
else
{
injectionSucceeded = injectWaitInstructions(forExtraMemory.get(), si, ph, howManyNames, spacePerName, (uint32_t)extraMemoryLocation, extraMemorySize);
}
if (!injectionSucceeded)
{
bool extraMemoryFreed = VirtualFreeEx(
ph.amnesiaHandle,
extraMemoryLocation,
0,
MEM_RELEASE
);
extraMemoryLocation = nullptr;
if (!extraMemoryFreed)
{
printf("WARNING: error when using VirtualFreeEx: %d\ncouldn't release VirtualAllocEx memory\n", GetLastError());
}
return false;
}
printf("amnesia has been injected\n");
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
return false;
}
printf("amnesia has been injected\n");
return true;
}
DWORD codeInjectionMain(bool skipFlashbacks)
{
LPVOID extraMemoryLocation = nullptr; // this is here so the virtual pages can be released in the catch block if an unexpected error happens
HANDLE amnesiaHandle = nullptr; // needed when catching exception
try
{
// LiveSplit uses these functions, so they're probably safe to use even though they're undocumented
NTFUNCTION NtSuspendProcess = nullptr;
NTFUNCTION NtResumeProcess = nullptr;
SavedInstructions si;
DWORD amnesiaPid = findAmnesiaPid(si);
if (amnesiaPid == (DWORD)-1)
{
printf("you can now close this window\n");
return (DWORD)-1;
}
ProcessHelper ph(amnesiaPid);
if (!ph.checkIfProcessIsAmnesia())
{
printf("you can now close this window\n");
return (DWORD)-1;
}
amnesiaHandle = ph.amnesiaHandle;
bool ntFunctionsFound = findNtFunctions(NtSuspendProcess, NtResumeProcess);
if (ntFunctionsFound)
{
NtSuspendProcess(ph.amnesiaHandle);
}
bool injectionSucceeded = injectWhileSuspended(ph, si, extraMemoryLocation, skipFlashbacks);
if (ntFunctionsFound)
{
NtResumeProcess(ph.amnesiaHandle);
}
return injectionSucceeded ? amnesiaPid : (DWORD)-1;
}
catch (const std::runtime_error& e)
{
char const* fixC4101Warning = e.what();
printf("unexpected error: %s\n", fixC4101Warning); | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
if (extraMemoryLocation)
{
bool extraMemoryFreed = VirtualFreeEx(
amnesiaHandle,
extraMemoryLocation,
0,
MEM_RELEASE
);
extraMemoryLocation = nullptr;
if (!extraMemoryFreed)
{
printf("WARNING: error when using VirtualFreeEx: %d\ncouldn't release VirtualAllocEx memory\n", GetLastError());
}
}
}
return (DWORD)-1;
}
#include <cstdio>
#include <memory>
#include <stdexcept>
const size_t fhelperBufferSize = 8192;
template <typename T>
class FileHelper
{
public:
FileHelper(const FileHelper& fhelper) = delete;
FileHelper& operator=(FileHelper other) = delete;
FileHelper(FileHelper&&) = delete;
FileHelper& operator=(FileHelper&&) = delete;
explicit FileHelper(const wchar_t* filename) // there isn't wfopen on linux
{
#ifndef _WIN32
throw std::runtime_error("FileHelper wchar_t* constructor only works on Windows");
#endif
if (_wfopen_s(&_f, filename, L"rb") != 0 || !_f)
{
printf("FileHelper couldn't open %ls\n", filename);
throw std::runtime_error("FileHelper fopen failure in const wchar_t* constructor");
}
}
explicit FileHelper(const char* filename)
{
#ifdef _WIN32
if (fopen_s(&_f, filename, "rb") != 0 || !_f)
#else
if (!(_f = fopen(filename, "rb")))
#endif
{
printf("FileHelper couldn't open %s\n", filename);
throw std::runtime_error("FileHelper fopen failure in const char* constructor");
}
}
~FileHelper()
{
if (_f)
{
fclose(_f);
}
}
bool getCharacter(T& ch)
{
if (_bufferPosition == _charactersRead)
{
_bufferPosition = 0;
_charactersRead = (int)fread(_buffer.get(), sizeof(T), fhelperBufferSize / sizeof(T), _f); | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
if (!_charactersRead)
{
return false;
}
}
ch = _buffer[_bufferPosition];
_bufferPosition++;
return true;
}
void resetFile()
{
if (fseek(_f, 0, SEEK_SET) != 0)
{
throw std::runtime_error("FileHelper fseek failure in resetFile");
}
_bufferPosition = 0;
_charactersRead = 0;
}
private:
FILE* _f = nullptr;
std::unique_ptr<T[]> _buffer = std::make_unique<T[]>(fhelperBufferSize / sizeof(T));
int _bufferPosition = 0;
int _charactersRead = 0;
};
This 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.
example: https://youtu.be/mMikDj3KSGg
If it's skipping the dialogue, it injects here: https://github.com/FrictionalGames/AmnesiaTheDarkDescent/blob/acc95cdedd6c94db89dc924eb9afa23185df562f/amnesia/src/game/LuxMapHandler.cpp#L633
And 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
If it's waiting through the dialogue, it injects here: https://github.com/FrictionalGames/AmnesiaTheDarkDescent/blob/acc95cdedd6c94db89dc924eb9afa23185df562f/amnesia/src/game/LuxMapHandler.cpp#L685
And 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 | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
Answer: It isn't clear why file_helper.h makes an attempt to be portable since code_injection.cpp is not portable. If you want most of the code to be portable, break the code into more files and limit the code that requires WIN32 code - such as the process ID code - to a particular file.
Since this is C++ rather than C, it isn't clear why the code is using C input and output. Specifically, why is the code using printf() rather than std::cout?
All error messages are going to stdout, rather than stderr. If the code continues to use C rather than C++ input and output report errors using fprintf(stderr, ERROR MESSAGE);.
It is not clear why the code is using low-level C file functions such as fopen() and fclose(). Streams would be a better way in C++.
Allow the compiler to point out possible issues by increasing the warning levels. I am compiling using Visual Studio 2022 and I am getting the following warning messages: | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
code_injection.cpp(63,1): warning C4267: 'initializing': conversion from 'size_t' to 'int', possible loss of data
code_injection.cpp(83,1): warning C4267: 'initializing': conversion from 'size_t' to 'DWORD', possible loss of data
code_injection.cpp(124,1): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPCVOID' of greater size
code_injection.cpp(140,1): warning C4267: '=': conversion from 'size_t' to 'DWORD', possible loss of data
code_injection.cpp(143,1): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPVOID' of greater size
code_injection.cpp(167,32): warning C4244: '+=': conversion from 'SIZE_T' to 'uint32_t', possible loss of data
code_injection.cpp(168,1): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPCVOID' of greater size
code_injection.cpp(184,32): warning C4244: '=': conversion from 'SIZE_T' to 'uint32_t', possible loss of data
code_injection.cpp(193,1): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPVOID' of greater size
code_injection.cpp(204,32): warning C4244: '+=': conversion from 'SIZE_T' to 'uint32_t', possible loss of data
code_injection.cpp(205,1): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPCVOID' of greater size
code_injection.cpp(224,1): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPCVOID' of greater size
code_injection.cpp(361,72): warning C4267: '=': conversion from 'size_t' to 'uint32_t', possible loss of data
code_injection.cpp(366,69): warning C4267: '=': conversion from 'size_t' to 'uint32_t', possible loss of data
code_injection.cpp(378,62): warning C4267: '=': conversion from 'size_t' to 'uint32_t', possible loss of data
code_injection.cpp(394,71): warning C4267: '=': conversion from 'size_t' to 'uint32_t', possible loss of data
code_injection.cpp(597,36): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPVOID' of greater size
code_injection.cpp(614,44): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPVOID' of greater size | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
code_injection.cpp(739,36): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPVOID' of greater size
code_injection.cpp(756,35): warning C4312: 'type cast': conversion from 'uint32_t' to 'LPVOID' of greater size
code_injection.cpp(835,140): warning C4311: 'type cast': pointer truncation from 'LPVOID' to 'uint32_t'
code_injection.cpp(835,140): warning C4302: 'type cast': truncation from 'LPVOID' to 'uint32_t'
code_injection.cpp(839,140): warning C4311: 'type cast': pointer truncation from 'LPVOID' to 'uint32_t'
code_injection.cpp(839,140): warning C4302: 'type cast': truncation from 'LPVOID' to 'uint32_t' | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
Based on the above warning messages it isn't clear why the code is using std::uint32_t rather than just unsigned int or std::size_t. In some cases I might suggest a bool variable rather than an integer.
It isn't clear why the following code is using arrays of characters rather than C++ strings, although if the code continues to use C input and output functions that might be necessary.
const wchar_t steamName[] = L"Amnesia.exe";
const wchar_t nosteamName[] = L"Amnesia_NoSteam.exe";
const char flashbackNameFile[] = "flashback_names.txt";
The if statements in the following code are too complex and should be simplified. The code is also less clear because the comparisons are using raw numbers (Magic numbers) rather than symbolic constants.
if (memorySlice[0] == 0xf6 && memorySlice[1] == 0x74 && memorySlice[7] == 0x75 && memorySlice[9] == 0x80)
{
locationsFound++;
si.stopFunctionLocation = ph.amnesiaMemoryLocation + i - 16;
}
else if (memorySlice[0] == 0x48 && memorySlice[8] == 0xd0 && memorySlice[9] == 0x5d)
{
locationsFound++;
si.isPlayingLocation = ph.amnesiaMemoryLocation + i - 17;
}
else if (memorySlice[0] == 0x75 && memorySlice[2] == 0x56 && memorySlice[4] == 0x15 && memorySlice[9] == 0x8b)
{
locationsFound++;
memcpy(si.sleepCallBytes, &memorySlice[3], sizeof(si.sleepCallBytes));
}
else if (
(memorySlice[5] == 0xff && memorySlice[6] == 0x50 && memorySlice[8] == 0xe8 && memorySlice[13] == 0x2b)
|| (si.isSteamVersion && memorySlice[5] == 0xff && memorySlice[6] == 0xd0 && memorySlice[7] == 0xe8 && memorySlice[13] ==
0x45))
{ | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
c++, windows, assembly
The class ProcessHelper should be in its own header file (ProcessHelper.h) and the functions should be in ProcessHelper.cpp; this might make some portion of the code more portable.
It isn't clear why you want to embed assembly code rather than implement the functions in C++ which would make it easier to debug and maintain. | {
"domain": "codereview.stackexchange",
"id": 44742,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, windows, assembly",
"url": null
} |
beginner, rust
Title: Learning rust by writing a calculator
Question: 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 negative operator. Functions, Variables, and Unary operators are not implemented.
I have implemented a shunting yard algorithm for parsing the input into a vector of tokens. Then process the tokens left to right, updating the vector to to store intermediate results until the vector has a length of one and return an Option as the result. Returning None if any step of parsing and/or evaluating the expression fails.
Questions:
With this written as a library module, does it make sense to return an Option, or is it better to use a Result? Is there a rule of thumb of when to use one over the other?
I said I pseudo handle the unary negative operator. As it is implemented differently than the other operators. How could I better implement this operator?
Subjective Questions/Advice
Did I fall victim to any common mistakes made by people learning this language?
I am looking to generally improve the level at which I program. Is there any general suggestions on other ways I improve my code quality?
Trivial main.rs
use std::{io::{self}, process::exit};
use calculator;
fn main() {
loop {
let mut user_input = String::new();
io::stdin().read_line(&mut user_input).expect("Unable to read stdin");
if user_input.trim().eq_ignore_ascii_case("quit") || user_input.trim().eq_ignore_ascii_case("q"){
break;
}
//intentionally pass ownership of user_input since we don't want to use the raw input
if let Some(result) = calculator::to_result(user_input) {
println!("{:?}", result);
}
}
exit(0);
} | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
lib.rs
#[derive(Debug)]
enum Token<T> {
Number(T),
Operator(OP),
}
#[derive(Debug,PartialEq)]
enum OpAssocation {
LEFT,
RIGHT,
}
#[derive(Debug,PartialEq)]
enum OPSymbol {
ADD,
SUB,
MUL,
DIV,
EXP,
LeftParen,
RightParen,
}
impl OPSymbol {
//Convert char to OP
fn value(c: char) -> Option<OP> {
match c {
'+' => Some(OP { op_symbol: OPSymbol::ADD, precedence: 2, op_association: OpAssocation::LEFT }),
'-' => Some(OP { op_symbol: OPSymbol::SUB, precedence: 2, op_association: OpAssocation::LEFT }),
'*' => Some(OP { op_symbol: OPSymbol::MUL, precedence: 3, op_association: OpAssocation::LEFT }),
'/' => Some(OP { op_symbol: OPSymbol::DIV, precedence: 3, op_association: OpAssocation::LEFT }),
'^' => Some(OP { op_symbol: OPSymbol::EXP, precedence: 4, op_association: OpAssocation::RIGHT }),
'(' => Some(OP { op_symbol: OPSymbol::LeftParen, precedence: 0, op_association: OpAssocation::RIGHT }),
')' => Some(OP { op_symbol: OPSymbol::RightParen, precedence: 0, op_association: OpAssocation::RIGHT }),
_ => None
}
}
//evaluate OpSymbol and perform operation
fn eval(i1:f64, i2:f64, op: &OPSymbol) -> Option<f64> {
match op {
OPSymbol::ADD => Some(i1+i2),
OPSymbol::SUB => Some(i1-i2),
OPSymbol::MUL => Some(i1*i2),
OPSymbol::DIV => {
if i2 == 0.0 {
println!("Can't divide by 0!");
return None
}else {
Some(i1/i2)
}
},
OPSymbol::EXP => Some(i1.powf(i2)),
_ => {
println!("Can't evaluate invalid symbol");
None
}
}
}
}
#[derive(Debug)]
struct OP {
op_symbol: OPSymbol,
precedence: u8,
op_association: OpAssocation,
} | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
/// Parses a given expression string and returns a result as an f64
/// If any parsing/calculation errors occur returns None
/// Uses the shunting yard algorithm to parse the inputs into reverse polish notation
/// Handles basic Addition, Subtraction, Multiplication, Division, Exponents, the unary - operator
/// ```
/// let result = match calculator::to_result(String::from("2+2")) {
/// Some(x) => x,
/// None => panic!("Test Failed")
/// };
/// assert_eq!(result, 4.0);
///
/// let result = match calculator::to_result(String::from("2*(1+3)^2")) {
/// Some(x) => x,
/// None => panic!("Test Failed")
/// };
/// assert_eq!(result, 32.0);
/// ```
pub fn to_result(input: String) -> Option<f64> {
//immedieatly die if we find alpha characters
if input.contains(|c: char| { c.is_ascii_alphabetic() }){
println!("Found Invalid Input!");
return None
}
//get rid of spaces
//use map() and closure to combine steps?
let mut trimmed_input = String::new();
for s in input.split_whitespace() {
trimmed_input.push_str(s);
}
//convert to iterator since String and &str can't be iterated on
let char_iter = trimmed_input.chars().into_iter();
//manage index and offset of &str
let mut index = 0;
let mut offset = 0;
let mut prev_val = '`';
//token vector that will be passed to obtain final f64 result
let mut tokens: Vec<Token<f64>> = Vec::new();
let mut op_stack: Vec<OP> = Vec::new(); | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
for c in char_iter {
//handle unary negative operator
//Better way to hanlde this?
if (c.is_ascii_digit() || c == '.') || (index == 0 && c == '-') || (c == '-' && !prev_val.is_ascii_digit() && prev_val != '`') {
index+=1;
continue;
} else {
//found number boundry
if offset != index {
tokens.push(Token::Number(match trimmed_input[offset..index].parse() {
Ok(x) => x,
Err(_) => {
println!("Found Symbol, Expected Number");
return None
}
}));
}
//convert char to OpSymbol
let op1 = match OPSymbol::value(c) {
Some(x) => x,
None => {
println!("Found invalid symbol");
return None
}
};
//process logic for for op token
//unconditionally add ( to the opstack
if op1.op_symbol == OPSymbol::LeftParen {
op_stack.push(op1);
//hanlde )
} else if op1.op_symbol == OPSymbol::RightParen && op_stack.len() > 0 {
//pop opstack until ( is found
while op_stack.len() > 0 {
let op2 = &op_stack[op_stack.len()-1];
if op2.op_symbol != OPSymbol::LeftParen {
tokens.push(Token::Operator(match op_stack.pop() {
Some(x) => x,
None => {
println!("Found invalider OP token");
return None
}
} ));
} else {
//pop the ( and leave the loop
op_stack.pop();
break;
} | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
op_stack.pop();
break;
}
//found a ) but no matching (
if op_stack.len() == 0 {
println!("Found mismatched ()");
return None
}
}
//handle other operators
} else {
//if op stack is empty just add op
if op_stack.len() == 0 {
op_stack.push(op1);
}else {
while op_stack.len() > 0 {
let op2 = &op_stack[op_stack.len()-1];
if op2.op_symbol != OPSymbol::LeftParen && (op2.precedence > op1.precedence ||(op1.precedence == op2.precedence && op1.op_association == OpAssocation::LEFT)){
tokens.push(Token::Operator(match op_stack.pop() {
Some(x) => x,
None => {
println!("Failed to push operator to token output");
return None
}
} ));
}else {
break;
}
}
op_stack.push(op1);
}
}
}
prev_val = c;
index+=1;
offset = index;
}
//if end of input was not a ) or some other symbol offset to end of input must be a number. Push this number to output vector
if offset < trimmed_input.len() {
tokens.push(Token::Number(match trimmed_input[offset..].parse() {
Ok(x) => x,
Err(_) => {
println!("Found Symbol, Expected Number");
return None
} | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
}));
}
//finsished iterating over string push remaining op symbols on to output
if op_stack.len() > 0 {
while op_stack.len() > 0 {
tokens.push(Token::Operator(match op_stack.pop() {
Some(x) => {
if x.op_symbol == OPSymbol::LeftParen {
println!("Found unclosed (");
return None
}else {
x
}
},
None => continue
} ));
}
}
//missing symbol
//probably breaks if unary symbols are ever implemented like !5
if tokens.len() % 2 == 0 {
println!("Invalid Expression");
return None
}
get_result(tokens)
} | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
/// Convert vector of Tokens to a final result as a f64 number
fn get_result(mut tokens: Vec<Token<f64>>) -> Option<f64> {
let mut index = 0;
while tokens.len() > 1 {
//temp result
let mut r: Token<f64>= Token::Number(0.0) ;
for t in &tokens {
match t {
Token::Number(_x) => {
index+=1;
continue;
},
Token::Operator(x) => {
let i1 = match tokens[index-2] {
Token::Number(n) => n,
_ => {
println!("Found OPSymbol, expected Number");
return None;
}
};
let i2 = match tokens[index-1] {
Token::Number(n) => n,
_ => {
println!("Found OpSymbol, expected Number");
return None;
}
};
r = Token::Number(match OPSymbol::eval(i1, i2, &x.op_symbol) {
Some(x) => x,
_ => return None
});
break;
}
}
}//end for
//can't borrow immutable and mutable in same scope so need to update tokens outside for loop
//update tokens
tokens.remove(index);
tokens.remove(index -1);
tokens.remove(index - 2);
tokens.insert(index -2, r);
//reset for next loop
index =0;
}//end while
match tokens[0] {
Token::Number(x) => Some(x),
_ => {
println!("Expected Number, found Symbol");
return None
}
}
}
Link to github if it helps: https://github.com/ruinedme/rust-calculator/tree/main | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
Link to github if it helps: https://github.com/ruinedme/rust-calculator/tree/main
Answer: Looks nice! Since you asked for advice on Option versus Result, let’s start there.
Use Result to Pass Back Information about Recoverable Errors
You check for errors consistently. Right now, the error checks look like this:
if i2 == 0.0 {
println!("Can't divide by 0!");
return None
}else {
Some(i1/i2)
}
We see that, in this implementation, all errors print a string constant to standard output and short-circuit. This isn’t ideal, for a few reasons:
The functions have visible side-effects, which means you can’t perform optimizations like common-subexpression elimination or lazy evaluation without changing the program output.
The error messages are logged to standard output rather than standard error, making this unsuitable for shell scripts. To write to standard error, use eprintln!, ot to abort with a panic message, you can use panic!, expect! or unexpected!, depending on what kind of expression the type system needs.
The code to print the error message and exit is repeated unnecessarily.
Most importantly, we lose information about our errors! If there’s any kind of failure anywhere in the program, on any input, all we know is that the operation failed. Somewhere. We could easily have lost the information on the stack trace, too. If you ever have to debug a None that shouldn’t be there, you’ll curse yourself for not failing fast. | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
So, let’s see how this looks if we change to a Result type, whose Err value is a &'static str. The OPSymbol::eval function becomes:
fn eval(i1: f64, i2: f64, op: &OPSymbol) -> Result<f64, &'static str> {
match op {
OPSymbol::ADD => Ok(i1 + i2),
OPSymbol::SUB => Ok(i1 - i2),
OPSymbol::MUL => Ok(i1 * i2),
OPSymbol::DIV => {
if i2 == 0.0 {
Err("Can't divide by 0!")
} else {
Ok(i1 / i2)
}
}
OPSymbol::EXP => Ok(i1.powf(i2)),
_ => Err("Can't evaluate invalid symbol"),
}
} | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
This is a great use case to return an Err string, because a syntax error in a line of input is recoverable. The program prints the error message and then gives the user a chance to retype the line in the Read-Evaluate-Print-Loop.
This requires a cascade of changes to the program, but it enables the program to see a syntax error, print a message about what the error was, and read a new value instead of aborting.
On an Unrecoverable Error, Fail Fast
And be sure to do it from someplace where the stack trace will tell you enough about what went wrong. The worst thing you can do is throw away all the information you need to debug the problem and crash somewhere far away later.
Generally, None values should be for valid results that the caller handles. If you ever find yourself writing a return from an Err(_) or .is_err() block, or passing around an Err type of (), that’s a major code smell. If you’re not even looking at any of the information you had about the error, what was the point of using a Result type?
Depending on the context, you can make an error fail fast with a panic! or expect message. Sometimes, when the compiler makes you write exhaustive branches with the same type, you want to declare some unreachable!.
Avoid process::exit
You have many calls to this, and none of them are necessary.
If you need to print a message to standard error and abort the program, use panic!, or a more sugary synonym like unreachable! or .expect. However, nearly all of these should return a Result of Err, not halt the program.
If you want to return successfully from main, just return, or reach its closing brace.
Prefer &str to String Function Parameters
Sometimes, you really do want to consume a String object and re-use its memory. Maybe you call .into_bytes() on it, for example. | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
But if all you need is a view of something stringy, you should take a &str. This works on slices (like the one you get from .trim() in main), leaves the object usable and often saves you the overhead of cloning.
Here, you leave a comment saying that you are taking ownership because your main function of this one program doesn’t happen to need the input line after the call. But that’s not a good way to design an API. It results in an API that needs to change in many other programs (like one that trims whitespace from all lines, not just the commands q or quit).
Use More-Informative Names
Quick, without looking: what’s the difference between to_result and get_result? Does either produce a Result?
Run rustfmt
I don’t like all of its conventions, but it’s pretty standard for Rust, and would catch a few typos.
I also recommend against /// for comments.
Refactor get_result
The first change I’d make is to change the return type to a Result, so that all the branches that check for errors can become an if/else if block whose branches each return Err or Ok.
I’d also make the loop into a loop and check for the terminating conditions, which might be errors or a single Number value. What would really enhance the maintainability a lot, though, is if you pattern-match on slices of your Vec. Here’s one possible start:
// Convert vector of Tokens to a final result as a f64 number
fn get_result(mut tokens: Vec<Token<f64>>) -> Result<f64, &'static str> {
use Token::{Number, Operator}; | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
loop {
let n = tokens.len();
if n == 0 {
return Err(""); // Print a blank line in response.
} else if let [Number(a)] = tokens[..] {
return Ok(a);
} else if n < 3 {
return Err("Syntax error.");
} else if let [Operator(op), Number(a), Number(b)] = tokens[n - 3..n] {
match OPSymbol::eval(a, b, op.op_symbol) {
Ok(c) => {
tokens[n-3] = Number(c);
tokens.truncate(n-2);
}
err => {
return err;
}
}
} else {
return Err("Logic error: Parsed to invalid tree!");
}
} // end loop
} | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
Note that, for this pattern-match to compile, you need to derive both Clone and Copy for Token and all of its components. Otherwise, you would need to borrow a slice of the Vec, preventing you from borrowing it mutably to resize it. From the comments, you had the same problem, and solved it another way. In this case, though, the elements are so small that copying is a zero-cost abstraction.
I also changed the definition of OpSymbol::eval to return the same Result type, and remove the borrow.
Also note that this approach does not work with your current implementation of the shunting-yard algorithm, since yours evaluates from left to right.
Parse into Reverse Polish Notation
That is, push the operator first, then the operands. This allows you to evaluate the stack from the top down, and push intermediate results back onto the same stack. This is much more efficient than removing and inserting elements in the middle of a Vec, which shifts the array multiple times.
If you really, truly need to burn a vector from both ends, use a VecDequeue.
There are various other ways to optimize the parser, but you don’t want to write parsers by hand as anything but a learning exercise anyway.
Store Only the Necessary Information in Each Instance
Currently, you store not only the identifier of each operator, but a copy of its precedence and left-or-right association. But these are always the same for each operation! There’s no such thing as a multiply token that has lower precedence than an addition. You should store only the type of operation on the stack.
Make Main a Read-Evaluate-Print Loop that Reports Errors
If you change the type of get_result to
fn get_result(mut tokens: Vec<Token<f64>>) -> Result<f64, &'static str>
(or Result<f64, String> if you want to be able to return a dynamic error message) and make all the cascading changes that requires, you can rewrite main along the lines of,
use std::io; | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
pub fn main() {
for input in io::stdin().lines().map(Result::unwrap) {
let trimmed_input = input.trim();
if trimmed_input == "quit" || trimmed_input == "q" {
return;
}
match to_result(trimmed_input) {
Ok(result) => {
println!("{:?}", result);
}
Err(msg) => {
println!("{}", msg);
}
}
} // end for
}
This accepts the input
18/0
18/9
and produces the output
Can't divide by 0!
2.0 | {
"domain": "codereview.stackexchange",
"id": 44743,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
python, python-3.x
Title: Python program that deals with overlapping intervals
Question: 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 is some arbitrary data.
In each triplet the second integer is always no less than the first integer, the two integers represent integer ranges that includes both ends. Basically I have two extremely big lists containing integer ranges with some data associated with each range.
And here is the problem I wanted to address: the ranges often overlap, and sub-ranges can also have sub-ranges. So I intended to split the overlapping ranges into discrete ranges.
And there are two kinds of problematic situations:
1, the sub-ranges can have the same data as their parent ranges, this causes unnecessary nesting so I wanted the sub-ranges to be ignored and only the parent ranges need to be processed in this situation.
2, if the start of a range is the end of the previous range plus one, they sometimes have the same data, in this situation they need to be merged.
I intend to split the ranges into discrete ranges, so that any gap is filled with data from the immediate parent range, and no adjacent ranges share the same data.
My previous post didn't get reviewed, the code was too long and more importantly the solution was very inefficient.
I had spent many hours today trying to find a better solution, and I have found it, I have achieved doing everything I mentioned in one for loop, so that the code is much more efficient. But the code is ugly so I wanted it to be reviewed. | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
Code
class Merging_List:
def __init__(self):
self.rows = []
self.last = [False]*3
def append(self, row):
if row[0] != self.last[1] + 1 or row[2] != self.last[2]:
self.rows.append(row)
self.last = row
else:
self.last[1] = row[1]
def process(rows):
last = rows[0]
pos = last[0]
stack = [last]
processed = Merging_List()
for row in rows[1:]:
if stack and row[2] == stack[-1][2]:
continue
if last[0] > pos and stack:
processed.append([pos, last[0] - 1, stack[-1][2]])
if row[0] > last[1]:
processed.append(last)
pos = last[1] + 1
elif last not in stack:
stack.append(last)
if stack and row[0] > stack[-1][1]:
if pos < stack[-1][1]:
processed.append([pos, stack[-1][1], stack[-1][2]])
pos = stack[-1][1] + 1
stack.pop(-1)
if row[0] >= last[1] or row[2] != last[2]:
last = row
if stack and last[2] != stack[-1][2]:
if last[0] > pos:
processed.append([pos, last[0] - 1, stack[-1][2]])
processed.append(last)
pos = last[1] + 1
while stack:
row = stack.pop(-1)
if pos < row[1]:
processed.append([pos, row[1], row[2]])
pos = row[1] + 1
return processed.rows | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
return processed.rows
I haven't tested it on the full dataset, so I am not sure if it is completely working, but from what I have tested so far the code seems to be working perfectly.
The ranges are always sorted in such a way that ranges with lower indexes have smaller starts, and if two adjacent ranges share the same start, the range with larger end is ordered first. And I have verified that if two ranges overlap, then the smaller range is always completely contained within the larger range, with no exceptions, in other words if the start of range A is no greater than range B, the end of range A will never be greater than range B.
So for two adjacent ranges A and B, B comes after A, if the start of B is larger than the end of A, it is guaranteed that they don't overlap, else B must be a sub-range of A. | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
Test data
rows = [
[16777216, 33554431, 0], [16777216, 16777471, 1], [16777472, 16777727, 2], [16777728, 16778239, 2],
[16778240, 16779263, 3], [16778496, 16778751, 3], [16779264, 16781311, 2], [16781312, 16785407, 4],
[16781312, 16781567, 5], [16785408, 16793599, 2], [16785408, 16785663, 6], [16793600, 16809983, 7],
[16809984, 16842751, 8], [16809984, 16826367, 8], [16809984, 16818175, 8], [16809984, 16810239, 8],
[16810240, 16810495, 8], [16810496, 16811007, 8], [16811008, 16811263, 8], [16811264, 16811519, 8],
[16812032, 16812287, 8], [16812288, 16812543, 8], [16812544, 16812799, 8], [16812800, 16813055, 8],
[16813312, 16813567, 8], [16814080, 16818175, 8], [16818176, 16826367, 8], [16818176, 16819199, 8],
[16819200, 16819455, 8], [16819456, 16819711, 8], [16819712, 16819967, 8], [16819968, 16820223, 8],
[16820224, 16820479, 8], [16820480, 16820735, 8], [16820736, 16820991, 8], [16820992, 16821247, 8],
[16821248, 16822271, 8], [16822272, 16822527, 8], [16822528, 16822783, 8], [16822784, 16823039, 8],
[16823040, 16823295, 8], [16823808, 16824063, 8], [16825600, 16825855, 8], [16825856, 16826111, 8],
[16826112, 16826367, 8], [16826368, 16842751, 8], [16826368, 16834559, 8], [16826368, 16826623, 8],
[16826624, 16826879, 8], [16826880, 16827135, 8], [16827136, 16827391, 8], [16827392, 16827647, 8],
[16827648, 16827903, 8], [16827904, 16828159, 8], [16828160, 16828415, 8], [16828416, 16828671, 8],
[16828672, 16828927, 8], [16828928, 16829439, 8], [16829440, 16829695, 8], [16829696, 16829951, 8],
[16829952, 16830207, 8], [16830208, 16830463, 8], [16830464, 16830975, 8], [16830976, 16831487, 8]
]
Test result
[[16777216, 16777471, 1],
[16777472, 16778239, 2],
[16778240, 16779263, 3],
[16779264, 16781311, 2],
[16781312, 16781567, 5],
[16781568, 16785407, 4],
[16785408, 16785663, 6],
[16785664, 16793599, 2],
[16793600, 16809983, 7],
[16809984, 16842751, 8],
[16842752, 33554431, 0]] | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
I have verified the result to be indeed correct.
I know my code is ugly and this is exactly why I want it to be reviewed, it is just prototype code. The function is way too long and not elegant, but it does get the job done. I want the function to be split into smaller functions, but I don't know where to start, I need everything to be done in exactly one loop, because I literally have millions of rows to process.
So what is a better method to achieve exactly the same thing I have done, but with smaller function size, more concise and elegant code?
Update
I couldn't respond to the comments and update the question in time, because my ISP cut off my network connection, so it took me some time to fix it and change modem settings.
That said I spent sometime to make some really crude graphics to illustrate the point better.
The input:
The output:
Obviously the images are not to scale, because the numbers are so large it is impossible to draw them to scale. The first image captures the nesting structure of the networks. The rectangles each represent a network, the color represent the data of the network, and if a rectangle is within another, then the network it represents is the subnet of the network represented by the larger rectangle, and vice versa.
The larger the rectangle is, the more subnets the corresponding network has.
The criteria to merge ranges is really simple:
1, if two networks overlap, say they are network A and network B, it always will be the case that one network is fully contained in another. Say network A is larger, then the data is (start_A, end_A, attribute_A), (start_B, end_B, attribute_B), and this will always hold: start_A <= start_B <= end_B <= end_A. The networks need to be merged if and only if the share the same data, here it means if attribute_B == attribute_A. If that is the case, network B needs to be ignored. | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
2, if two networks don't overlap, but they are adjacent to each other, again, say they are networks A and B, network B comes after A, they are adjacent if and only if the start of B comes immediately after the end of A, or in code: start_B == end_A + 1, and they need to be merged if and only if they share the same attribute, the merged result would be: (start_A, end_B, attribute_A).
I hope the output graphics is self-explanatory enough, I don't need to clarify anything further.
I didn't claim my code to be completely working, but from what I have tested, in my use case, it is working. And it is prototype code. And since there is already an answer I am not allowed to edit the code.
Update 2
No, that is not a bug, that is exactly the intended behavior.
Like I already wrote, I want to split the overlapping ranges into discrete non-overlapping ranges. If two ranges overlap, then one range is completely inside the other.
Again, say they are range A and B, B comes after A, in all cases B is a su-brange of A. And if B and A have different data, they need to be split into discrete ranges, this means the portion of A that is B will be deleted so that the numbers inside range B will only have data from B.
I did write they are number ranges, right? The rule is very simple, each range assigns its attribute to all numbers within the corresponding range, and like Python assignment, later assignment should always overwrite everything assigned before. This means the sub-range always wins and the for each number there will only be one value to it.
Here is a simple example to show what I mean.
Data:
[(0, 10, 'A'), (0, 1, 'B'), (2, 5, 'C'), (3, 4, 'C'), (6, 7, 'C'), (8, 8, 'D')]
What the data actually means:
[
{0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A', 6: 'A', 7: 'A', 8: 'A', 9: 'A', 10: 'A'},
{0: 'B', 1: 'B'},
{2: 'C', 3: 'C', 4: 'C', 5: 'C'},
{3: 'C', 4: 'C'},
{6: 'C', 7: 'C'},
{8: 'D'}
] | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
My intended process is equivalent to simply processing them in order and update the dictionary according to the current item one by one.
Processed data:
{0: 'B', 1: 'B', 2: 'C', 3: 'C', 4: 'C', 5: 'C', 6: 'C', 7: 'C', 8: 'D', 9: 'A', 10: 'A'}
Output:
[(0, 1, 'B'), (2, 7, 'C'), (8, 8, 'D'), (9, 10, 'A')]
And I know I can just expand all the ranges and merge them one by one, and that is fool-proof and guaranteed to work, but that is incredibly stupid and terribly inefficient, as you can see the numbers in the data are so big and there are millions of rows I really have no idea how long it will take.
I wrote the completely working first version, the first smart approach I came up with, it was really completely working and included in the question I linked.
But it was still inefficient. This is my second attempt at a smart solution. This does everything in one for loop, in one go, therefore extremely efficient. But it isn't completely working and ugly.
However the output of this algorithm on any subset of the gigantic dataset I have is correct. I always started with the first item though.
Update 3.0
I have updated my code yet again and this time it seems to be working correctly, at least it gives correct output for all the three examples given so far: the original example included in the question, [[10, 15, 9], [16, 20, 9]] from a comment, and my second example [[0, 10, 'A'], [0, 1, 'B'], [2, 5, 'C'], [3, 4, 'C'], [6, 7, 'C'],[8, 8, 'D']]. | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
As you can see the code is of poor quality, it needs to be split into smaller methods.
Before you ask why did I share code as a screenshot, first see if there is existing answer to the question. As there is already an answer posted, I don't know if I am allowed to edit the code, lest it be rolled back.
The changes I made were quite simple, first I duplicated the last element in the data by appending the last element to the list.
This is to ensure every row will be processed, because my code works by comparing the current element to the last element, and only the last element will be appended to the result.
Second I got rid of last element assignment, or assigning the current element to last at the end of the loop to memorize what was the last element, by simply zipping the data starting at the zeroth index with the data starting at the first index, so I have two variables that keep track of what comes before the latter.
Third I eliminated the first and last if checks inside the for loop.
Finally and most importantly, this is what made it work for all inputs (that I have tested anyway, again there might still be edge cases), the trick is extremely simple, I changed the two conditions that look like this: if pos < number: to this: if pos <= number:.
That is right, I merely changed less than operator to less than or equal to operator and it made a huge difference. | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
Answer: Start with a clearer understanding of the current code's drawbacks. You
described your current implementation as prototype code. While criticizing it,
you expressed a desire for an implementation "with smaller function size, more
concise and elegant code" and conveyed the idea that "it needs to be split into
smaller methods". Perhaps those things are true. But I would suggest something
different. The current code is plenty concise. Its primary drawback is its
algorithmic complexity and its lack of any mechanisms to help the reader
understand what's going on. There are no code comments, for example, to guide
the reader. The logic rests substantially on opaque list indexes, which carry
no meaningful information. To illustrate the last point with one line of code,
consider what something as simple as a few constants could do to enhance
readability:
# Current code: making the reader work hard.
if row[0] >= last[1] or row[2] != last[2]:
...
# Add a few constants to give meaning to those indexes.
BEGIN, END, DATA = (0, 1, 2)
...
if row[BEGIN] >= last[END] or row[DATA] != last[DATA]:
...
Smarter data, simpler code. As with your password program, you are
under-investing in data and over-investing in algorithm. As Fred Brooks, Rob
Pike, and other computing
giants have emphasized, the key to programming is data. If you select the right
data structures, and create the right data objects, algorithms tend to simplify
and code tends to become more readable. Your current data structures are bare
bones (a list of triples) -- hence the need to rely on numeric indexes rather
than meaningful and self-documenting attributes. One good move would be to
define a simple data object to represent one of those intervals/ranges/triples.
from dataclasses import dataclass
@dataclass(order = True)
class Interval:
begin: int
end: int
data: object | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
@dataclass(order = True)
class Interval:
begin: int
end: int
data: object
Speaking of data structures, consider using an interval
tree. This problem seems
well-suited for a data structure specialized to answer questions about
overlapping intervals. The
intervaltree library seems to be
active and reasonably maintained. Here's an illustration of how you might use
it. Compared to your current implementation, the code is a little bit shorter
and, much more important, a lot more readable (even without the comments). But
notice the role that the comments play in providing a narrative to guide the
reader through the process, clarifying intent, and explaining anything that
might not be directly evident from the code.
from intervaltree import IntervalTree, Interval as TreeInterval
def merge_rows(rows):
# Convert the row data to an IntervalTree.
t = IntervalTree()
for begin, end, data in rows:
# Add the row to the tree.
iv = TreeInterval(begin, end + 1, data)
t.add(iv)
# Slice all intervals in the tree at the current interval's endpoints.
t.slice(iv.begin)
t.slice(iv.end)
# After those slices, intervals in the tree that overlap the current
# interval can be replaced by new intervals holding the current data.
for ov in t.overlap(iv):
new = TreeInterval(ov.begin, ov.end, iv.data)
t.remove(ov)
t.add(new)
# Merge abutting intervals having the same data value.
# Because TreeInterval instances are immutable, we will
# convert them to our own Interval instances.
ivs = []
prev = None
for iv in sorted(Interval(*iv) for iv in t):
if prev and iv.data == prev.data and prev.end == iv.begin:
prev.end = iv.end
else:
ivs.append(iv)
prev = iv | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x
# Convert back to the "row" data format that we started with.
# Or not: perhaps the rest of your program would benefit from
# using Interval instances rather than raw triples.
return [
[iv.begin, iv.end - 1, iv.data]
for iv in ivs
] | {
"domain": "codereview.stackexchange",
"id": 44744,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x",
"url": null
} |
python, python-3.x, game, console
Title: Text based naval game
Question: 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
self.position = position
self.cannonballs = 100
self.morale = 100
self.morale_boost_wait_turns = 0
self.enemy = None
def move(self, distance):
new_position = self.position + distance
if 0 <= new_position <= 6 and new_position != self.enemy.position:
self.position = new_position
print(f"{self.name} moved to position {new_position}.")
else:
print("Invalid move!")
def crew_attack(self, enemy_ship):
if abs(self.position - enemy_ship.position) in range(1, 3):
damage = random.randint(5, 10)
enemy_ship.health -= damage
self.crew -= random.randint(5, 10)
print(f"{self.name} executed a crew attack! {damage} damage dealt to {enemy_ship.name}.")
else:
print("Crew attack is not possible at this distance!")
def cannon_attack(self, enemy_ship):
if abs(self.position - enemy_ship.position) in range(3, 5):
damage = random.randint(10, 20)
enemy_ship.health -= damage
self.cannonballs -= random.randint(10, 20)
print(f"{self.name} executed a cannon attack! {damage} damage dealt to {enemy_ship.name}.")
else:
print("Cannon attack is not possible at this distance!") | {
"domain": "codereview.stackexchange",
"id": 44745,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, console",
"url": null
} |
python, python-3.x, game, console
def ram_attack(self, enemy_ship):
if abs(self.position - enemy_ship.position) >= 5:
damage = random.randint(20, 30)
enemy_ship.health -= damage
if self.position < enemy_ship.position:
self.position = min(enemy_ship.position - 1, 6)
else:
self.position = max(enemy_ship.position + 1, 0)
print(f"{self.name} executed a ram attack! {damage} damage dealt to {enemy_ship.name}.")
print(f"{self.name} moved to position {self.position}.")
else:
print("Ram attack is not possible at this distance!")
def repair(self):
if self.crew >= 10:
restored_health = random.randint(10, 20)
self.health += restored_health
self.crew -= 10
print(f"{self.name} repaired their ship. Health restored by {restored_health}.")
else:
print("Insufficient crew members for repair.")
def steal_crew_members(self):
if abs(self.position - self.enemy.position) == 1:
stolen_crew = random.randint(5, 10)
self.crew += stolen_crew
self.enemy.crew -= stolen_crew
print(f"{self.name} stole {stolen_crew} crew members from {self.enemy.name}!")
def morale_booster(self):
if self.crew >= 20:
if self.morale_boost_wait_turns == 0:
morale_boost_amount = random.randint(15, 20) * (self.crew // 10)
self.morale += morale_boost_amount
self.crew -= 20
self.morale_boost_wait_turns = 3 # Crew members need to wait 3 turns before using morale booster again
print(f"{self.name} used a morale booster. Morale boosted by {morale_boost_amount}.")
else:
print("Crew members need to wait before using the morale booster again.")
else:
print("Insufficient crew members for morale booster.")
def update_morale_boost_wait_turns(self):
if self.morale_boost_wait_turns > 0:
self.morale_boost_wait_turns -= 1 | {
"domain": "codereview.stackexchange",
"id": 44745,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, console",
"url": null
} |
python, python-3.x, game, console
def is_alive(self):
return self.health > 0 and self.crew > 0
def display_distance_bar(player1, player2):
bar = [" "] * 7 # Initialize the bar with 7 empty slots
bar[player1.position] = player1.symbol
bar[player2.position] = player2.symbol
# Adjust positions if they overlap or go beyond the valid range
if player1.position == player2.position:
bar[player1.position] = "X" # Mark overlapping position with "X"
elif player1.position > player2.position:
bar[player1.position] = ">" # Mark player1's position with ">"
bar[player2.position] = "<" # Mark player2's position with "<"
distance_bar = "|".join(bar)
print(f"Distance Bar: {distance_bar}")
def display_stats(player):
print(f"{player.name}'s Stats:")
print(f"Health: {player.health}")
print(f"Crew: {player.crew}")
print(f"Position: {player.position}")
print(f"Cannonballs: {player.cannonballs}")
print(f"Morale: {player.morale}")
print(f"Morale Boost Turns Remaining: {player.morale_boost_wait_turns}")
def main():
print("==== Welcome to Jolley Roger ====")
player1_name = input("Player 1, enter your name: ")
player2_name = input("Player 2, enter your name: ")
player1 = Ship(player1_name, player1_name[0], 0)
player2 = Ship(player2_name, player2_name[0], 6)
player1.enemy = player2
player2.enemy = player1
while player1.is_alive() and player2.is_alive():
print("\nPlayer 1's Turn:")
display_stats(player1)
display_distance_bar(player1, player2)
steps = int(input("Enter the number of steps to move (0-3): "))
if steps != 0:
direction = input("Enter the direction to move (left or right): ")
if direction == "left":
steps *= -1
player1.move(steps) | {
"domain": "codereview.stackexchange",
"id": 44745,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, console",
"url": null
} |
python, python-3.x, game, console
print("\nPlayer 1's Turn - Action Menu:")
display_stats(player1)
display_distance_bar(player1, player2)
print("Choose an action:")
print("1. Crew Attack (1-2 distance)")
print("2. Cannon Attack (3-4 distance)")
print("3. Ram Attack (5+ distance)")
print("4. Repair")
print("5. Steal Crew Members")
print("6. Morale Booster")
choice = int(input())
if choice == 1:
player1.crew_attack(player2)
elif choice == 2:
player1.cannon_attack(player2)
elif choice == 3:
player1.ram_attack(player2)
elif choice == 4:
player1.repair()
elif choice == 5:
player1.steal_crew_members()
elif choice == 6:
player1.morale_booster()
player1.update_morale_boost_wait_turns()
print("\nPlayer 2's Turn:")
display_stats(player2)
display_distance_bar(player1, player2)
steps = int(input("Enter the number of steps to move (0-3): "))
if steps != 0:
direction = input("Enter the direction to move (left or right): ")
if direction == "left":
steps *= -1
player2.move(steps)
print("\nPlayer 2's Turn - Action Menu:")
display_stats(player2)
display_distance_bar(player1, player2)
print("Choose an action:")
print("1. Crew Attack (1-2 distance)")
print("2. Cannon Attack (3-4 distance)")
print("3. Ram Attack (5+ distance)")
print("4. Repair")
print("5. Steal Crew Members")
print("6. Morale Booster")
choice = int(input())
if choice == 1:
player2.crew_attack(player1)
elif choice == 2:
player2.cannon_attack(player1)
elif choice == 3:
player2.ram_attack(player1)
elif choice == 4:
player2.repair()
elif choice == 5:
player2.steal_crew_members()
elif choice == 6:
player2.morale_booster()
player2.update_morale_boost_wait_turns() | {
"domain": "codereview.stackexchange",
"id": 44745,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, console",
"url": null
} |
python, python-3.x, game, console
player2.update_morale_boost_wait_turns()
if player1.is_alive():
print(f"\n{player1.name} won the battle!")
elif player2.is_alive():
print(f"\n{player2.name} won the battle!")
else:
print("\nIt's a draw!")
print("==== Game Over ====")
if __name__ == "__main__":
main()
Answer: Your code is good, but there are a few improvements to be made.
First, the repeated code. You repeat the same code for player1 and player2, when you could just use a method:
# inside the Ship class
def turn(self):
print(f"\n{self.name}'s Turn:")
display_stats(self)
display_distance_bar(self, self.enemy)
steps = int(input("Enter the number of steps to move (0-3): "))
if steps != 0:
direction = input("Enter the direction to move (left or right): ")
if direction == "left":
steps *= -1
player1.move(steps)
print("\nPlayer 1's Turn - Action Menu:")
display_stats(self)
display_distance_bar(self, self.enemy)
print("Choose an action:")
print("1. Crew Attack (1-2 distance)")
print("2. Cannon Attack (3-4 distance)")
print("3. Ram Attack (5+ distance)")
print("4. Repair")
print("5. Steal Crew Members")
print("6. Morale Booster")
choice = int(input())
if choice == 1:
self.crew_attack(self.enemy)
elif choice == 2:
self.cannon_attack(self.enemy)
elif choice == 3:
self.ram_attack(self.enemy)
elif choice == 4:
self.repair()
elif choice == 5:
self.steal_crew_members()
elif choice == 6:
self.morale_booster()
self.update_morale_boost_wait_turns()
I would also advise you to use a match-case statement:
def turn(self):
...
choice = int(input())
match choice:
case 1:
self.crew_attack(self.enemy)
case 2:
self.cannon_attack(self.enemy)
...
You could also make some of your existing functions into methods, for example display_distance_bar():
# inside Ship class | {
"domain": "codereview.stackexchange",
"id": 44745,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, console",
"url": null
} |
python, python-3.x, game, console
def display_distance_bar(self):
bar = [" "] * 7 # Initialize the bar with 7 empty slots
bar[self.position] = self.symbol
bar[self.enemy.position] = self.enemy.symbol
# Adjust positions if they overlap or go beyond the valid range
if self.position == self.enemy.position:
bar[self.position] = "X" # Mark overlapping position with "X"
elif self.position > self.enemy.position:
bar[self.position] = ">" # Mark player1's position with ">"
bar[self.enemy.position] = "<" # Mark player2's position with "<"
distance_bar = "|".join(bar)
print(f"Distance Bar: {distance_bar}")
This would also work for display_stats().
The game loop would now look something like:
def main():
print("==== Welcome to Jolley Roger ====")
player1_name = input("Player 1, enter your name: ")
player2_name = input("Player 2, enter your name: ")
player1 = Ship(player1_name, player1_name[0], 0)
player2 = Ship(player2_name, player2_name[0], 6)
player1.enemy = player2
player2.enemy = player1
while player1.is_alive() and player2.is_alive():
player1.turn()
player2.turn()
if player1.is_alive():
print(f"\n{player1.name} won the battle!")
elif player2.is_alive():
print(f"\n{player2.name} won the battle!")
else:
print("\nIt's a draw!")
print("==== Game Over ====")
N.B.
Your indentation is also wrong but I assume that's from incorrect copy and pasting.
Overall, a very engaging text-based game. | {
"domain": "codereview.stackexchange",
"id": 44745,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, game, console",
"url": null
} |
java, beginner, hibernate
Title: A vanilla Hibernate app (no Spring)
Question: I finished my web project a while ago and decided to revisit one my first Java projects – the first project that had anything to do with databases. It looked pretty messy to my more experienced eye. For example, I created a new SessionFactory at each method call. I decided to refactor it a bit. I'm still more or less a beginner so it may still have lots of room for improvement. What would you suggest?
For example, I suspect catching all Exceptions is bad practice (as opposed to catching specific exceptions). I'm just not sure it's worth the time and the effort to write all those log statements
Using wrapper classes may also be unnecessary
It uses Hibernate's classes and interfaces on purpose (as opposed to JPA's)!
@Entity
@Table(name="users")
@Getter
@Setter
@NoArgsConstructor // yes, I'm too lazy to write a no-args constructor by myself
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Long id;
@Column
private String name;
@Column(name = "last_name")
private String lastName;
@Column
private Byte age;
public User(String name, String lastName, Byte age) {
this.name = name;
this.lastName = lastName;
this.age = age;
}
public User (Long id, String name, String lastName, Byte age) {
this.id = id;
this.name = name;
this.lastName = lastName;
this.age = age;
}
@Override
public String toString() {
return "User{" + "id=" + id +
", name='" + name + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
'}';
} | {
"domain": "codereview.stackexchange",
"id": 44746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, hibernate",
"url": null
} |
java, beginner, hibernate
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id.equals(user.id) && name.equals(user.name) && lastName.equals(user.lastName) && age.equals(user.age);
}
@Override
public int hashCode() {
return Objects.hash(id, name, lastName, age);
}
}
public class UtilHibernate {
private static final String SCHEMA_NAME = "users_db";
private static final SessionFactory sessionFactory;
static {
Properties properties = new Properties();
String[][] propertiesArray = {
{"hibernate.connection.url", "jdbc:mysql://localhost:3306/users_db"},
{"dialect", "org.hibernate.dialect.MySQLDialect"},
{"hibernate.connection.username", "pp_user"},
{"hibernate.connection.password", "pp_user"},
{"hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver"},
{"hibernate.current_session_context_class", "thread"}
};
for (String[] property : propertiesArray) {
properties.setProperty(property[0], property[1]);
}
sessionFactory = new Configuration()
.setProperties(properties)
.addAnnotatedClass(User.class)
.buildSessionFactory();
}
public static String getSchemaName() {
return SCHEMA_NAME;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
sessionFactory.close();
}
}
public class UserDaoHibernateImpl implements UserDao {
private final String schemaName = UtilHibernate.getSchemaName();
private final Session session =
UtilHibernate.getSessionFactory().getCurrentSession(); | {
"domain": "codereview.stackexchange",
"id": 44746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, hibernate",
"url": null
} |
java, beginner, hibernate
@Override
public void createUsersTable() {
try {
session.beginTransaction();
session.createSQLQuery("""
CREATE TABLE IF NOT EXISTS :sn.users (
id int NOT NULL AUTO_INCREMENT,
name varchar(15),
last_name varchar(25),
age tinyint,
PRIMARY KEY (id)
);""")
.setParameter("sn", schemaName)
.executeUpdate();
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
}
}
@Override
public void dropUsersTable() {
try {
session.beginTransaction();
session.createSQLQuery("DROP TABLE IF EXISTS :sn.users;")
.setParameter("sn", schemaName)
.executeUpdate();
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
}
}
@Override
public void save(User... users) {
try {
session.beginTransaction();
for (User user : users) {
session.save(user);
}
int length = users.length;
if (length == 0) {
System.out.println("No User instances are provided, no inserting was performed");
} else {
System.out.printf("%d records were successfully inserted into the database", length);
}
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
}
} | {
"domain": "codereview.stackexchange",
"id": 44746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, hibernate",
"url": null
} |
java, beginner, hibernate
@Override
public void removeUserById(long id) {
try {
session.beginTransaction();
int rowsAffected = session.createQuery("DELETE FROM User u WHERE u.id = :id;")
.setParameter("id", id)
.executeUpdate();
session.getTransaction().commit();
if (rowsAffected < 1) {
System.out.printf("No user with id %d exists in the database, " +
"its removal is not possible", id);
}
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
}
}
@Override
public User getUserById(long id) {
User user = null;
try {
session.beginTransaction();
user = session.get(User.class, id);
if (user == null) {
System.out.printf("No user with id %d exists in the database, " +
"its retrieval is not possible", id);
}
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
}
return user;
}
@Override
public List<User> getAllUsers() {
List<User> userList = new ArrayList<>();
try {
session.beginTransaction();
userList = session.createQuery("SELECT u FROM User u", User.class).list();
session.getTransaction().commit();
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
}
return userList;
} | {
"domain": "codereview.stackexchange",
"id": 44746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, hibernate",
"url": null
} |
java, beginner, hibernate
@Override
public void clearUsersTable() {
try {
session.beginTransaction();
int rowsAffected = session.createSQLQuery("TRUNCATE :sn.users")
.setParameter("sn", schemaName)
.executeUpdate();
session.getTransaction().commit();
System.out.printf("The Users table was cleared, %d rows were removed", rowsAffected);
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
}
}
}
public class UserServiceHibernateImpl implements UserService {
private final UserDao userDaoHibernate = new UserDaoHibernateImpl();
@Override
public void createUsersTable() {
userDaoHibernate.createUsersTable();
}
@Override
public void dropUsersTable() {
userDaoHibernate.dropUsersTable();
}
// you get the idea
public class Main {
public static void main(String[] args) {
UserService userService = new UserServiceHibernateImpl();
User user = userService.getUserById(1); // or something else
System.out.println(user);
UtilHibernate.shutdown();
}
Answer:
I suspect catching all Exceptions is bad practice (as opposed to catching specific exceptions). | {
"domain": "codereview.stackexchange",
"id": 44746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, hibernate",
"url": null
} |
java, beginner, hibernate
It depends...
As long as you have the same reaction to all kinds of possible exceptions (just logging in your case) there is nothing wrong with this catch all approach.
Duplicated constructor
Your user class has two constructors doing merely the the same. You could call the one having more parameters from the other. This would allow to declare the properties final. which in turn prevents problems in multithreaded environments.
Hard coded configurations
You have all configurations hard coded. This way you have to recompile your Program if any of that configuration changes. Concider the use of the Properties class to read configurations from the hard drive.
Session handling / code duplication
You have quite some methods where you commit the changes in the database on success but no rollback occurs in the event of an exception. That may lead to unexpected consistency problems.
Also you end each and every database action with a commit, including those that only read from the database and do no DML.
On one hand this looks a bit smelly to me. On the other hand it allows for reducing code duplication like this:
interface DbAction{
<T> T executeIn(Session session) throws Exception;
}
public class DbActionWrapper {
private final Session session;
public DbActionWrapper (Session session) {this.session = Ssession;}
public <T> Optional<T> execute(DbAction dbAction){
try {
session.beginTransaction();
return Optional.ofNullable(dbAction.executeIn(session));
} catch (Exception e) {
System.err.println("An exception was thrown: " + e.getMessage());
return Optional.empty();
session.getTransaction().rollback();
} finally {
session.getTransaction().commit();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, hibernate",
"url": null
} |
java, beginner, hibernate
And your code in UserDaoHibernateImpl would change to:
public static final User NOT_FOUND = new User(-1,"John", "Doe", -1);
private final DbActionWrapper dbAction;
public UserDaoHibernateImpl(DbActionWrapper dbAction) {
this.dbAction = dbAction;
}
@Override
public void removeUserById(long id) {
dbAction.execute(session-> {
int rowsAffected = session.createQuery("DELETE FROM User u WHERE u.id = :id;")
.setParameter("id", id)
.executeUpdate();
if (rowsAffected < 1) {
System.out.printf("No user with id %d exists in the database, " +
"its removal is not possible", id);
}
return null; // return value is ignored
});
}
@Override
public User getUserById(long id) {
dbAction.execute(session-> {
Optional<User> user = Optional.ofNullable(session.get(User.class, id));
if (!user.isPresent()) {
System.out.printf("No user with id %d exists in the database, " +
"its retrieval is not possible", id);
}
// You really should not return a literal null since it aims for NullPointerExceptions on the callers side.
// better solution would be to (re) raise an exception.
return user.orElse(NOT_FOUND);
});
}
// ...
Unnecessary indirection
Your class UserServiceHibernateImpl is pure boilerplate code. It has no logic of its own and only delegates to the same one and only dependency (at least as fahr as you showed it...).
So the question is, why not having UserDaoHibernateImpl implementing the UserService directly and removing UserServiceHibernateImpl completely? | {
"domain": "codereview.stackexchange",
"id": 44746,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, beginner, hibernate",
"url": null
} |
python, console, io
Title: Python code using *args to print warnings in color
Question: 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 = list(txt)
a[0] = WARN + a[0]
a[-1] += WTXT
print(*a)
def fail(*txt):
a = list(txt)
a[0] = FAIL + a[0]
a[-1] += WTXT
print(*a)
def okay(*txt): # shouldn't be named "pass" since that's a reserved word
a = list(txt)
a[0] = PASS + a[0]
a[-1] += WTXT
print(*a)
warn("Unfragmented text")
warn("Fragmented", "text")
fail("Unfragmented text")
fail("Fragmented", "text")
okay("Unfragmented text")
okay("Fragmented", "text")
Above, I can print code in yellow, red or green, which isn't a super powerful stub, but it saves time and energy. Even typing print(FAIL + "..." + WTXT) is a nuisance, as I forget the closing WTXT.
My questions are:
Am I horribly misusing *arg? I've never used it before, and so often stuff that just works can backfire in unexpected ways once I try to get it to do more.
I clearly have code that duplicates itself. Ideally I'd like a def colorize(*txt) the three other functions call, but I'd also like a "color=PASS" default parameter. I have a feeling I'm just being scared by a new concept, so I am missing an easy refactoring.
Is it okay to use PASS as a variable, as lower-case pass is a reserved word?
Of course, there may be more I'm overlooking, and I'd love to know that, too. Thanks!
Answer: The globals aren't doing much for you, so get rid of them.
Your code will not do the right thing if an argument fails to print: the colour will not be reset. Add a finally to handle this case.
You're too aggressive with your style reset. Just reset the fore colour and nothing else.
Add type hints.
am I horribly misusing *arg? | {
"domain": "codereview.stackexchange",
"id": 44747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, io",
"url": null
} |
python, console, io
am I horribly misusing *arg?
No, it's fine.
is it okay to use PASS as a variable, as lower-case pass is a reserved word?
Not really. The convention to get around keywords is an underscore suffix, as in pass_.
from typing import Any
import colorama
def print_colour(fore_colour: str, *text: Any) -> None:
print(fore_colour, end='')
try:
print(*text, end='')
finally:
print(colorama.Fore.RESET)
def okay(*text: Any) -> None:
print_colour(colorama.Fore.GREEN, *text)
def warn(*text: Any) -> None:
print_colour(colorama.Fore.YELLOW, *text)
def fail(*text: Any) -> None:
print_colour(colorama.Fore.RED, *text)
def test() -> None:
class BadClass:
def __str__(self):
raise ValueError()
try:
fail(BadClass())
except ValueError:
pass
print('Should be in default colour')
warn("Unfragmented text")
warn("Fragmented", "text")
fail("Unfragmented text")
fail("Fragmented", "text")
okay("Unfragmented text")
okay("Fragmented", "text")
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 44747,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, io",
"url": null
} |
c++, performance, strings, library, c++23
Title: string_view tokenizer function template
Question: 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 client needs to tell the function how many tokens they expect to get by passing a span object of that exact size (say I expect 5 tokens to be found, I need to pass a span with size 5). This also ensures that the function does not overrun the underlying buffer by assigning an excess number of tokens to the elements passed the end (which is UB).
This obviously has some niche use cases.
Here (live):
#include <string_view>
#include <span>
#include <limits>
#include <cstddef>
#include <fmt/core.h>
#define METHOD 1
using std::size_t;
template < typename CharT,
class Traits = std::char_traits<CharT> >
[[ nodiscard ]] size_t constexpr
tokenize( const std::basic_string_view<CharT, Traits> str,
const std::basic_string_view<CharT, Traits> delimiter,
const std::span< std::basic_string_view<CharT, Traits> > found_tokens_OUT ) noexcept
{
auto found_tokens_count { 0uz };
size_t start { str.find_first_not_of( delimiter ) };
size_t end { };
#if METHOD == 1
for ( auto idx { 0uz };
start != std::string_view::npos && idx < std::size( found_tokens_OUT ); ++idx )
{
end = str.find_first_of( delimiter, start );
found_tokens_OUT[ idx ] = str.substr( start, end - start );
++found_tokens_count;
start = str.find_first_not_of( delimiter, end );
}
#else
for ( auto&& token : found_tokens_OUT )
{
if ( start == std::basic_string_view<CharT, Traits>::npos ) break; | {
"domain": "codereview.stackexchange",
"id": 44748,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, library, c++23",
"url": null
} |
c++, performance, strings, library, c++23
end = str.find_first_of( delimiter, start );
token = str.substr( start, end - start );
++found_tokens_count;
start = str.find_first_not_of( delimiter, end );
}
#endif
if ( start == std::basic_string_view<CharT, Traits>::npos )
return found_tokens_count;
else
return found_tokens_count = std::numeric_limits<size_t>::max( );
}
int main( )
{
using std::string_view_literals::operator""sv;
const auto str { "1 % "sv };
constexpr auto delimiter { " \t"sv };
std::array<std::string_view, 5> tokens;
const auto token_count { tokenize( str, delimiter, { std::begin( tokens ), 2 } ) };
if ( token_count != std::numeric_limits<size_t>::max( ) )
{
for ( auto idx { 0uz }; idx < token_count; ++idx )
{
fmt::print( "{} ", tokens[ idx ] );
}
}
fmt::print( "\nCount: {}\n", token_count );
}
Questions about API design:
Is this function easy to use and hard to misuse? For example, the user has to construct and pass the 3rd argument (the span) by paying attention to its size because the function will expect to find span.size() number of tokens.
In case the function finds out that there is at least one more token than the user expected (the size of the span), then it stops the tokenization process and returns a sentinel value (i.e. MAX of size_t).
Questions about implementation:
Inside the body, I have written two different loops that do exactly the same thing. Which one is better? I find the second one (i.e. METHOD 2) more readable.
Can any of the loops be simplified even more?
And finally what else could be improved?
Answer: The span for output is somewhat inflexible:
it requires the caller to anticipate the number of results, and
it requires contiguous storage, restricting the implementation. | {
"domain": "codereview.stackexchange",
"id": 44748,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, library, c++23",
"url": null
} |
c++, performance, strings, library, c++23
It's probably better to make the function return an Input Range, enabling more flexible calling (e.g. I can then create a linked list of the results without overhead by using std::ranges::copy(tokenize(…), std::back_inserter(my_list));, or I could use a View to filter the results).
An alternative that's more like the current approach would be to accept an Output Range - possibly an infinite range such as a stream output range or a collection inserter.
Without that change, I think it would be more useful to operate like std::snprintf() by returning the number of tokens that would have been produced if the output range was large enough. That allows callers to call again with a resized buffer if they need to.
I prefer the version with the range-based for, but that's probably irrelevant given that changes to the interface could well make that look completely different.
A minor observation: this assignment is pointless, since found_tokens_count is going out of scope anyway:
return found_tokens_count = std::numeric_limits<size_t>::max( );
That can be replaced with simply
return std::numeric_limits<size_t>::max(); | {
"domain": "codereview.stackexchange",
"id": 44748,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, library, c++23",
"url": null
} |
python, python-3.x, console, security
Title: Python command line password generator
Question: 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 user, command-line tools aren't part of my usual work-flow).
I'm interested in any remark about my code, especially regarding security and features.
'''
Command-line utility program for generating passwords
'''
from argparse import ArgumentParser, RawTextHelpFormatter
import secrets
from string import ascii_lowercase, ascii_uppercase, digits, punctuation
ESCAPES = { r'\l' : ascii_lowercase,
r'\u' : ascii_uppercase,
r'\d' : digits,
r'\s' : punctuation }
def generate_password(length, alphabet):
return ''.join(secrets.choice(alphabet) for _ in range(length))
def _parse_alphabet(specifiers):
ranges = []
for escape, characters in ESCAPES.items():
if escape in specifiers:
ranges.append(characters)
specifiers = specifiers.replace(escape, '')
ranges.append(specifiers)
return ''.join(set(''.join(ranges))) | {
"domain": "codereview.stackexchange",
"id": 44749,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, security",
"url": null
} |
python, python-3.x, console, security
if __name__ == '__main__':
parser = ArgumentParser(
prog='Password generator',
formatter_class=RawTextHelpFormatter)
parser.add_argument(
'-l', '--length',
default=32,
type=int,
help='length of password to be generated')
parser.add_argument(
'-a', '--alphabet',
default=r'\l\u\d\s',
help=r'''alphabet to use for password generation. The following escape sequences are supported:
* \u: uppercase ASCII letters.
* \l: lowercase ASCII letters.
* \d: digits.
* \s: other printable ASCII characters.
Any other specified character will also be included.''')
args = parser.parse_args()
print(generate_password(args.length, _parse_alphabet(args.alphabet)))
Example uses:
# show help
(base) [...]>python password.py -h
usage: Password generator [-h] [-l LENGTH] [-a ALPHABET]
optional arguments:
-h, --help show this help message and exit
-l LENGTH, --length LENGTH
length of password to be generated
-a ALPHABET, --alphabet ALPHABET
alphabet to use for password generation. The following escape sequences are supported:
* \u: uppercase ASCII letters.
* \l: lowercase ASCII letters.
* \d: digits.
* \s: other printable ASCII characters.
Any other specified character will also be included.
# generate a password with default settings:
(base) [...]>python password.py
y3S%iR!O=zNhcWYf-f9@87m_FC'WGr+^
# generate a 6-digit PIN (eg. for phone unlocking):
(base) [...]>python password.py -l 6 -a \d
310696
# generate a password with smaller length and only some special chars (eg. for website compatibility):
(base) [...]>python password.py -l 16 -a "\u\l\d_-&@!?"
bP7L?_uuGbdHFww@ | {
"domain": "codereview.stackexchange",
"id": 44749,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, security",
"url": null
} |
python, python-3.x, console, security
# generate a long password:
(base) [...]>python password.py -l 250
FO_Hy1O,7#z}M'5K/,=:Al"dK-w{VIC:G$[Xqm|GRw8Uou@d^peD1vk$:76)n#28f112w"vz<F+-c\it$7@fb9Xq@3\[)7+*R7PTa(gdMb&\,?n6GRT93jD'L!6Ww)u:-}rWyXq&?V!pw>9<&.Nt4S!+a9X6f~z+?DZeB:);`-!{K;ftB(/;"TEeKi%yV,-,H3{2!x2Y"]'?[3$/'QM=K5mSo[!D~#;!iuY]=BF3=LLkGK92Nm4kttc\*S
# generate a password with non-ASCII characters:
(base) [...]>python password.py -a µùûÜ
ùùùÜùùµÜܵµµÜùûÜûµÜÜÜûûÜûûùùùûܵ
Answer: Configuring argparse is real code: put it in a function. There is nothing
trivial about configuring argparse. Put the code in a proper function -- for
maintainability, flexibility, testability, etc.
Pass the args explicitly to argparse. Don't rely on its default use
of sys.argv. This is another testability consideration.
When feasible, avoid RawTextHelpFormatter. It causes your program's help
text to ignore things like dynamic terminal widths. In this case, a little
wordsmithing can work around the perceived need for it. With program help text
(especially for arguments and options), brevity is crucial. When facing
complexities needing further elaboration, keep the argument help texts brief
and rely on an argparse epilog for further explanation.
Speaking of brevity, consider using argparse metavar. It can reduce the
visual weight/clutter of the generated help text.
List the long options first. It enhances help text readability.
Define constants for the default alphabet and length. You need to use each in two places.
A simpler alternative for _parse_alphabet(). Perhaps I overlooked
something, but I think you can start with the user-supplied alphabet and just
replace all of the escapes. In the illustration below, sorted() is neither
necessary nor harmful for the password algorithm, but it is helpful for any
debugging/testing you might want to perform.
import sys
import secrets
from argparse import ArgumentParser
from string import ascii_lowercase, ascii_uppercase, digits, punctuation | {
"domain": "codereview.stackexchange",
"id": 44749,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, security",
"url": null
} |
python, python-3.x, console, security
ESCAPES = {
r'\l': ascii_lowercase,
r'\u': ascii_uppercase,
r'\d': digits,
r'\s': punctuation,
}
DEFAULT_ALPHABET = ''.join(ESCAPES.keys())
DEFAULT_LENTH = 32
def main(args):
opts = parse_args(args)
alpha = _parse_alphabet(opts.alphabet)
p = generate_password(opts.length, alpha)
print(p)
def parse_args(args):
p = ArgumentParser(prog = 'Password generator')
p.add_argument(
'--length', '-l',
default = DEFAULT_LENTH,
type = int,
metavar = 'N',
help = f'password length [default: {DEFAULT_LENTH}]',
)
p.add_argument(
'--alphabet', '-a',
default = DEFAULT_ALPHABET,
metavar = 'A',
help = (
r'password alphabet. Supported escapes: '
r'\u upper ASCII, \l lower ASCII, \d digits, '
rf'\s other printable ASCII [default: "{DEFAULT_ALPHABET}"]'
),
)
return p.parse_args(args)
def _parse_alphabet(alpha):
for e, chars in ESCAPES.items():
alpha = alpha.replace(e, chars)
return ''.join(sorted(set(alpha)))
def generate_password(length, alphabet):
return ''.join(secrets.choice(alphabet) for _ in range(length))
if __name__ == '__main__':
main(sys.argv[1:]) | {
"domain": "codereview.stackexchange",
"id": 44749,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, console, security",
"url": null
} |
python, performance, game, pygame, minecraft
Title: 2D Minecraft - infinite chunk system
Question: 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 keys[pygame.K_UP]:
overworld.change_pos(pygame.Vector2(0, -MOVEMENT_SPEED))
if keys[pygame.K_DOWN]:
overworld.change_pos(pygame.Vector2(0, MOVEMENT_SPEED))
if keys[pygame.K_LEFT]:
overworld.change_pos(pygame.Vector2(-MOVEMENT_SPEED, 0))
if keys[pygame.K_RIGHT]:
overworld.change_pos(pygame.Vector2(MOVEMENT_SPEED, 0))
return 0
def draw():
screen.fill((255, 255, 255))
overworld.render(screen, True, other_offset=window_rect.center)
def game_logic():
overworld.handle_chunk_loader()
def run_game():
while True:
if handle_events():
break
game_logic()
draw()
pygame.display.update(window_rect)
clock.tick()
print(clock.get_fps())
pygame.quit()
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(SIZE)
window_rect = pygame.Rect((0, 0), SIZE)
clock = pygame.time.Clock()
pygame.display.set_caption(TITLE)
pygame.event.set_allowed([pygame.KEYDOWN, pygame.QUIT])
overworld = world.World(pygame.Vector2(0, 0), 2, 8)
run_game()
world.py:
import pygame | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
overworld = world.World(pygame.Vector2(0, 0), 2, 8)
run_game()
world.py:
import pygame
BLOCK_SIZE = 64
BLOCK_TEXTURE_NAMES = ["textures/void.png",
"textures/air.png",
"textures/grass_block.png",
"textures/dirt.png",
"textures/stone.png",
"textures/sandstone.png",
"textures/sand.png",
"textures/bedrock.png",
"textures/oak_log.png",
"textures/oak_leaves.png",
"textures/cobblestone.png"]
def block_texture(texture):
return pygame.transform.scale(pygame.image.load(texture), (BLOCK_SIZE, BLOCK_SIZE)).convert_alpha()
def convert(pos, convert_value_x, convert_value_y):
"""Converts coordinate systems."""
nx, rx = divmod(pos.x, convert_value_x)
ny, ry = divmod(pos.y, convert_value_y)
return ((nx, ny), (rx, ry))
class Chunk:
def __init__(self, pos, size):
self.size = size
self.actual_size = size*BLOCK_SIZE
self.block_textures = [block_texture(texture) for texture in BLOCK_TEXTURE_NAMES]
self.backround_texture = block_texture("textures/backround.png")
self.pos = pos
self.actual_pos = pos*BLOCK_SIZE
self.surface = pygame.Surface((self.actual_size, self.actual_size))
self.x_range = range(0, self.size)
self.y_range = range(0, self.size)
self.blocks = {} | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def update(self, block_pos, new_block=None):
if new_block == None:
self.surface.blit(self.backround_texture, pygame.Vector2(block_pos)*BLOCK_SIZE)
self.surface.blit(self.block_textures[self.blocks[block_pos]], pygame.Vector2(block_pos)*BLOCK_SIZE)
else:
self.blocks[block_pos] = new_block
self.surface.blit(self.backround_texture, pygame.Vector2(block_pos)*BLOCK_SIZE)
self.surface.blit(self.block_textures[new_block], pygame.Vector2(block_pos)*BLOCK_SIZE)
def generate(self):
for x in self.x_range:
for y in self.y_range:
x_pos, y_pos = int(self.pos.x)+x, int(self.pos.y)+y
surface = 0
bedrock = 16
soil_amount = 3
if y_pos == surface:
block = 2
elif y_pos > surface and y_pos <= surface + soil_amount:
block = 3
elif y_pos > surface + soil_amount and y_pos < bedrock:
block = 4
elif y_pos == bedrock:
block = 7
elif y_pos > bedrock:
block = 0
else:
block = 1
self.update((x, y), block)
def set_blocks(self, blocks):
self.blocks = blocks
for x in self.x_range:
for y in self.y_range:
self.update((x, y))
def __str__(self):
return str([self.blocks[(x, y)] for x in self.x_range for y in self.y_range]) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
class World():
def __init__(self, loader_pos, loader_distance, chunk_size):
self.chunk_size = chunk_size
self.actual_chunk_size = chunk_size*BLOCK_SIZE
self.loaded_chunks = {}
self.loader_pos = loader_pos
self.loader_chunk_pos = pygame.Vector2(convert(loader_pos, self.actual_chunk_size, self.actual_chunk_size)[0])
self.loader_distance = loader_distance
self.rendered = pygame.Surface((1, 1)).convert_alpha()
self.innactive_block_data = {}
def handle_chunk_loader(self):
chunks_needed = [chunk_pos for chunk_pos in self.chunks_to_load(self.loader_chunk_pos)]
chunks_currently_loaded = [chunk_pos for chunk_pos in self.loaded_chunks]
self.load_chunks([chunk_pos for chunk_pos in chunks_needed if chunk_pos not in chunks_currently_loaded])
self.unload_chunks([chunk_pos for chunk_pos in chunks_currently_loaded if chunk_pos not in chunks_needed])
def load_chunks(self, chunks_pos):
for pos in chunks_pos:
chunk_pos = (pos.x, pos.y)
block_data = self.innactive_block_data.get(chunk_pos, False)
self.loaded_chunks[chunk_pos] = Chunk(pos, self.chunk_size)
if block_data:
self.loaded_chunks[chunk_pos].set_blocks(block_data)
else:
self.loaded_chunks[chunk_pos].generate()
def unload_chunks(self, chunks_pos):
for chunk_pos in chunks_pos:
chunk = self.loaded_chunks.pop(chunk_pos)
if not self.innactive_block_data.get(chunk_pos, False) == chunk.blocks:
self.innactive_block_data[chunk_pos] = chunk.blocks
def get_block(self, pos):
chunk_pos, block_pos = convert(pos, self.chunk_size, self.chunk_size)
try:
return self.loaded_chunks[chunk_pos].blocks[block_pos]
except IndexError as e:
return 0 | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def chunks_to_load(self, loader_pos):
return [pygame.Vector2(chunk_pos_x*self.chunk_size, chunk_pos_y*self.chunk_size)
for chunk_pos_x in range(int(loader_pos.x)-self.loader_distance, int(loader_pos.x)+self.loader_distance+1)
for chunk_pos_y in range(int(loader_pos.y)-self.loader_distance, int(loader_pos.y)+self.loader_distance+1)]
def change_pos(self, pos):
self.loader_pos += pos
self.loader_chunk_pos = pygame.Vector2(convert(self.loader_pos, self.actual_chunk_size, self.actual_chunk_size)[0])
def set_pos(self, pos):
self.loader_pos = pos
self.loader_chunk_pos = pygame.Vector2(convert(pos, self.actual_chunk_size, self.actual_chunk_size)[0])
def render(self, screen, use_pos, other_offset=0):
for ch in self.loaded_chunks.values():
chunk_screen_pos = ch.actual_pos
screen.blit(ch.surface, (chunk_screen_pos - self.loader_pos*int(use_pos))+other_offset)
Is there any redundancy? Can performance be improved? Is the code hard to read?
Answer: Screen resolution
SIZE = (1365, 705) is plainly bad, users have different screen resolutions, setting a default resolution doesn't make sense at all, because on larger screens (i.e. 3840x2160) the window looks tiny, and users will want games to be full-screen. So it is better to get the user's screen resolution.
On Windows, use the following to get screen resolution:
from win32api import GetSystemMetrics
RESOLUTION = tuple(map(GetSystemMetrics, (0, 1))) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
RESOLUTION = tuple(map(GetSystemMetrics, (0, 1)))
Note this doesn't work on Linux, most users will probably be on Windows anyway, but if a user is using Linux and runs the program, it will raise exceptions. But of course, the Linux user can most probably fix the issue if you haven't fixed it.
Repetition elif ladder
Your code has a lot of repetition, a lot of redundancy, you used the same expressions multiple times, have multiple if statements with similar conditions, et cetera, you should follow Don't Repeat Yourself principle and clean those up.
if keys[pygame.K_UP]:
overworld.change_pos(pygame.Vector2(0, -MOVEMENT_SPEED))
if keys[pygame.K_DOWN]:
overworld.change_pos(pygame.Vector2(0, MOVEMENT_SPEED))
if keys[pygame.K_LEFT]:
overworld.change_pos(pygame.Vector2(-MOVEMENT_SPEED, 0))
if keys[pygame.K_RIGHT]:
overworld.change_pos(pygame.Vector2(MOVEMENT_SPEED, 0))
In the above code, each if statement is checking if a key is pressed and the action is extremely similar.
This is a perfect candidate to refactor to a for loop, you just need to store the keys in a sequence, and loop through that sequence to check if the key is pressed and do the action associated with the key. In this way, you only need to write one if statement.
You can get the keys by doing this:
def get_key(key): return getattr(pygame, f"K_{key}")
KEYS = list(map(get_key, ("UP", "DOWN", "LEFT", "RIGHT")))
The keys all have a prefix 'K_', the second line loops through the key names and adds the prefix, then gets the value of the key name by getting the value of the attribute of pygame with the key as name by using getattr, and then assigns the result to the KEYS list.
Your movement vectors follow a clear pattern. They are of the form (0, n). The sign of n is dependent on the direction of movement, and the order of the two numbers is dependent on the axis of movement. So you can just write a function to get the vectors.
from itertools import product
MOVEMENT_SPEED = 5 | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def get_vector(bools):
vertical, positive = bools
a, b = MOVEMENT_SPEED * (-1, 1)[positive], 0
if vertical:
a, b = b, a
return pygame.Vector2(a, b)
VECTORS = dict(zip(KEYS, map(get_vector, product((1, 0), (0, 1)))))
product((1, 0), (0, 1)) gives [(1, 0), (1, 1), (0, 0), (0, 1)] which is then passed to get_vector, the arguments are the four tuples and they are unpacked, then the sign of the vector is set according to positive flag using indexing, and the order of the two numbers is swapped if vertical flag is set, finally the pygame.Vector2 object is created and returned.
And then your code allows pressing opposite arrow keys at the same time. If both up and down or both left and right keys are pressed, the player is moved then moved back to the original position. This shouldn't be allowed and the second move should be invalidated.
Observe that opposite keys have indices in KEYS with opposite oddness, so we can detect if opposite keys are pressed by detecting if both odd index and even index is present.
def handle_events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
keys = pygame.key.get_pressed()
exclusive = [False, False]
for i, key in enumerate(KEYS):
if keys[key]:
exclusive[i % 2] = True
if all(exclusive):
break
overworld.change_pos(VECTORS[key])
return False
while condition
def run_game():
while True:
if handle_events():
break
...
Don't do the above. while True is used to start infinite loops with no single predicate exit condition, and while it has legitimate uses, here it is not the case. You have one specific exit condition that breaks the loop, you should use that condition for the while condition, in this way the code is more concise and it is clearer when the loop should exit.
def run_game():
while not handle_events():
... | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
Making ranges
self.x_range = range(0, self.size)
Don't do range(0, n), just write range(n), if you pass a single number as argument, Python knows that is the end of the range, and the start is by default 0 unless explicitly stated otherwise. It is more concise not to pass it and everyone knows what it means.
Repetition yet again
def update(self, block_pos, new_block=None):
if new_block == None:
self.surface.blit(self.backround_texture, pygame.Vector2(block_pos)*BLOCK_SIZE)
self.surface.blit(self.block_textures[self.blocks[block_pos]], pygame.Vector2(block_pos)*BLOCK_SIZE)
else:
self.blocks[block_pos] = new_block
self.surface.blit(self.backround_texture, pygame.Vector2(block_pos)*BLOCK_SIZE)
self.surface.blit(self.block_textures[new_block], pygame.Vector2(block_pos)*BLOCK_SIZE)
In the above code you used pygame.Vector2(block_pos)*BLOCK_SIZE four times, and self.surface.blit(self.backround_texture, pygame.Vector2(block_pos)*BLOCK_SIZE) twice, without the regard to the if statement.
pygame.Vector2(block_pos)*BLOCK_SIZE should be a named variable so that you don't have to recalculate it when you need to use it again, and self.surface.blit(self.backround_texture, pygame.Vector2(block_pos)*BLOCK_SIZE) should be moved outside of if else statements so that it will automatically executed without regard to the condition and you don't have to write it twice.
Then your second commands are very similar, the only difference is the key will be the default value if new_block is None, else the key will be new_block and the corresponding value will be updated.
You can just check the emptiness of the variable and assign it if non-empty in one-line by leveraging the or operator.
def update(self, block_pos, new_block=None):
vector = pygame.Vector2(block_pos) * BLOCK_SIZE
self.surface.blit(self.backround_texture, vector)
self.blocks[block_pos] = block = new_block or self.blocks[block_pos]
self.surface.blit(block, vector) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
Repetition yet another elif ladder
def generate(self):
for x in self.x_range:
for y in self.y_range:
x_pos, y_pos = int(self.pos.x)+x, int(self.pos.y)+y
surface = 0
bedrock = 16
soil_amount = 3
if y_pos == surface:
block = 2
elif y_pos > surface and y_pos <= surface + soil_amount:
block = 3
elif y_pos > surface + soil_amount and y_pos < bedrock:
block = 4
elif y_pos == bedrock:
block = 7
elif y_pos > bedrock:
block = 0
else:
block = 1
self.update((x, y), block) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
You are making several mistakes here, first you are using nested for loops to iterate through two entire iterables, while nested for loops can have legitimate uses, it is not the case here, you need to use itertools.product to get rid of one unnecessary nesting.
Then you are repeatedly assigning these variables surface = 0; bedrock = 16; soil_amount = 3 inside the loop, the variables aren't mutated at all within the loop, they don't belong in a loop. This is completely pointless and hinders performance. They need to be moved outside of the loop. Or better yet, since you are using a class, they need to be become class variables, since they won't ever change (I guess).
Then the elif ladder, this is completely inefficient. Here you have three exact matches, (0, 3, 16), and three values for each of them (2, 3, 7). This is the perfect opportunity to use a dict, like this: {0: 2, 3: 3, 16: 7}, you can then check if a key is present by using in operator and get the corresponding value by querying the dict.
Then you have three explicit conditions, 0 < x < 3, 3 < x < 16 and 16 < x, with another implicit one that can only be tested if x is negative. What you are trying to do here is to find the closest element in the list [0, 3, 16] that is less than x. You can use bisect.bisect to find the index of that element (plus one).
Putting it all together, the code becomes:
class Chunk:
surface = 0
bedrock = 16
ground = 3
starts = (surface, ground, bedrock)
levels = dict(zip(starts, (2, 3, 7)))
block_sizes = (1, 3, 4, 0)
def generate(self):
for x, y in product(self.x_range, self.y_range):
y_pos = int(self.pos.y) + y
if y_pos in self.levels:
block = self.levels[y_pos]
else:
i = bisect(self.starts, y_pos)
block = self.block_sizes[i]
self.update((x, y), block) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
Nested loops, yet again
def set_blocks(self, blocks):
self.blocks = blocks
for x in self.x_range:
for y in self.y_range:
self.update((x, y))
I won't repeat myself, use the following:
def set_blocks(self, blocks):
self.blocks = blocks
for x, y in product(self.x_range, self.y_range):
self.update((x, y))
Repetition floating assignments
self.loader_chunk_pos = pygame.Vector2(convert(loader_pos, self.actual_chunk_size, self.actual_chunk_size)[0])
You have used the above line three times, each time only changing the first argument to the convert function. Make a function for that.
class World:
def __init__(self, loader_pos, blah, blahh):
self.set_loader_chunk_pos(loader_pos)
def set_loader_chunk_pos(self, pos):
self.loader_chunk_pos = pygame.Vector2(
convert(pos, self.actual_chunk_size, self.actual_chunk_size)[0]
)
Unnecessary list comprehension and inefficient way to get difference of sets
def handle_chunk_loader(self):
chunks_needed = [chunk_pos for chunk_pos in self.chunks_to_load(self.loader_chunk_pos)]
chunks_currently_loaded = [chunk_pos for chunk_pos in self.loaded_chunks]
self.load_chunks([chunk_pos for chunk_pos in chunks_needed if chunk_pos not in chunks_currently_loaded])
self.unload_chunks([chunk_pos for chunk_pos in chunks_currently_loaded if chunk_pos not in chunks_needed]) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
Don't do a list comprehension without any conditions whatsoever just to get all the elements in a collection and build a list. It is terribly inefficient and bad practice in general.
[e for e in d] is functionally equivalent to list(d), the latter: list constructor is much more concise and it is exactly designed for this very reason, just use it.
However using a list is not the correct thing to do here, immediately after converting you are checking all elements that are members of A and not members of B, in other words you are calculating the set difference between A and B, and there is a basic Python data class that is exactly designed for this sort of thing: set. Use it. You can then calculate the difference by seta - setb (if they are not sets, convert them first).
def handle_chunk_loader(self):
chunks_needed = set(self.chunks_to_load())
loaded_chunks = set(self.loaded_chunks)
self.load_chunks(chunks_needed - loaded_chunks)
self.unload_chunks(loaded_chunks - chunks_needed)
As you can see, I have not passed self.loader_chunk_pos, because I of course have refactored that function as well, also because you most likely won't pass any other argument to that function. So it shouldn't take any arguments (other than self).
Update
My previous advice holds but very unfortunately that only works for hashable data types and for whatever reason pygame.math.Vector2 is unhashable.
So it doesn't work--that is, without modifications. So I patched the unhashable class by subclassing it and overriding __hash__ dunder method, and it worked.
class Vector(pygame.math.Vector2):
def __hash__(self):
return int(self.x * 10 + self.y)
def handle_chunk_loader(self):
chunks_needed = {Vector(i) for i in self.chunks_to_load()}
loaded_chunks = {Vector(i) for i in self.loaded_chunks}
self.load_chunks(chunks_needed - loaded_chunks)
self.unload_chunks(loaded_chunks - chunks_needed) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
More repetition and other errors
def load_chunks(self, chunks_pos):
for pos in chunks_pos:
chunk_pos = (pos.x, pos.y)
block_data = self.innactive_block_data.get(chunk_pos, False)
self.loaded_chunks[chunk_pos] = Chunk(pos, self.chunk_size)
if block_data:
self.loaded_chunks[chunk_pos].set_blocks(block_data)
else:
self.loaded_chunks[chunk_pos].generate()
def unload_chunks(self, chunks_pos):
for chunk_pos in chunks_pos:
chunk = self.loaded_chunks.pop(chunk_pos)
if not self.innactive_block_data.get(chunk_pos, False) == chunk.blocks:
self.innactive_block_data[chunk_pos] = chunk.blocks
You have used self.innactive_block_data.get(chunk_pos, False) twice, make a function to that as well.
A = func()
if A:
do_something()
Don't do the above, instead, by using the Walrus (:=) operator, you can check and assign at the same time:
if A := func():
do_something()
And never ever use not A == B (unless you are overloading __ne__), it is unnecessary and against the fundamentals of Python. You are doing the inequality check and Python has an inequality operator !=. A != B is the same as not A == B but much more concise.
And you can use ternary instead of if else to reduce some nesting.
def get_data(self, chunk_pos):
return self.innactive_block_data.get(chunk_pos, False)
def load_chunks(self, chunks_pos):
for pos in chunks_pos:
chunk_pos = (pos.x, pos.y)
self.loaded_chunks[chunk_pos] = Chunk(pos, self.chunk_size)
(
self.loaded_chunks[chunk_pos].set_blocks(block_data)
if (block_data := self.get_data(chunk_pos))
else self.loaded_chunks[chunk_pos].generate()
)
def unload_chunks(self, chunks_pos):
for chunk_pos in chunks_pos:
chunk = self.loaded_chunks.pop(chunk_pos)
if self.get_data(chunk_pos) != chunk.blocks:
self.innactive_block_data[chunk_pos] = chunk.blocks | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
Repetition nth time and nested for loops
def chunks_to_load(self, loader_pos):
return [pygame.Vector2(chunk_pos_x*self.chunk_size, chunk_pos_y*self.chunk_size)
for chunk_pos_x in range(int(loader_pos.x)-self.loader_distance, int(loader_pos.x)+self.loader_distance+1)
for chunk_pos_y in range(int(loader_pos.y)-self.loader_distance, int(loader_pos.y)+self.loader_distance+1)]
Don't pass the loader_pos argument, since the function only gets called once in the entire script and with only one argument that is unlikely to be changed, you should access that variable directly.
And nested loops yet again. Use product.
Your ranges are constructed in the exact same way, the only difference is that you are accessing different attributes, you can actually make a function to create the ranges for you, and access the attributes with strs by using getattr.
def get_range(self, axis):
n = int(getattr(self.loader_chunk_pos, axis))
return range(
n - self.loader_distance,
n + self.loader_distance + 1,
)
def chunks_to_load(self):
return [
pygame.Vector2(chunk_pos_x * self.chunk_size, chunk_pos_y * self.chunk_size)
for chunk_pos_x, chunk_pos_y in product(
self.get_range("x"), self.get_range("y")
)
]
Repetition + 1
def change_pos(self, pos):
self.loader_pos += pos
self.loader_chunk_pos = pygame.Vector2(convert(self.loader_pos, self.actual_chunk_size, self.actual_chunk_size)[0])
def set_pos(self, pos):
self.loader_pos = pos
self.loader_chunk_pos = pygame.Vector2(convert(pos, self.actual_chunk_size, self.actual_chunk_size)[0])
Don't use the above, use below example:
def set_loader_chunk_pos(self, pos):
self.loader_chunk_pos = pygame.Vector2(
convert(pos, self.actual_chunk_size, self.actual_chunk_size)[0]
)
def change_pos(self, pos):
self.loader_pos += pos
self.set_loader_chunk_pos(self.loader_pos) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def change_pos(self, pos):
self.loader_pos += pos
self.set_loader_chunk_pos(self.loader_pos)
def set_pos(self, pos):
self.loader_pos = pos
self.set_loader_chunk_pos(pos)
Unnecessary variable assignment
chunk_screen_pos = ch.actual_pos
While it is generally a good idea to assign named variables, here it is completely unnecessary as it is only used immediately after assignment once.
Your code is of very poor quality, though it is understandable considering you very likely copied from ChatGPT. If you didn't copy from ChatGPT, then the quality of your code is about the same level as what ChatGPT would generate. You have a long way to go. But I don't mean to discourage you, you just have a lot to learn and huge potential to improve.
2D_MC.py
import pygame
import world
from itertools import product
from win32api import GetSystemMetrics
TITLE = "2d_MC"
RESOLUTION = tuple(map(GetSystemMetrics, (0, 1)))
MOVEMENT_SPEED = 5
def get_key(key): return getattr(pygame, f"K_{key}")
KEYS = list(map(get_key, ("UP", "DOWN", "LEFT", "RIGHT")))
def get_vector(bools):
vertical, positive = bools
a, b = MOVEMENT_SPEED * (-1, 1)[positive], 0
if vertical:
a, b = b, a
return pygame.Vector2(a, b)
VECTORS = dict(zip(KEYS, map(get_vector, product((1, 0), (0, 1)))))
def handle_events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
keys = pygame.key.get_pressed()
exclusive = [False, False]
for i, key in enumerate(KEYS):
if keys[key]:
exclusive[i % 2] = True
if all(exclusive):
break
overworld.change_pos(VECTORS[key])
return False
def draw():
screen.fill((255, 255, 255))
overworld.render(screen, True, other_offset=window_rect.center)
def game_logic():
overworld.handle_chunk_loader() | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def game_logic():
overworld.handle_chunk_loader()
def run_game():
while not handle_events():
game_logic()
draw()
pygame.display.update(window_rect)
clock.tick()
print(clock.get_fps())
pygame.quit()
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(RESOLUTION)
window_rect = pygame.Rect((0, 0), RESOLUTION)
clock = pygame.time.Clock()
pygame.display.set_caption(TITLE)
pygame.event.set_allowed([pygame.KEYDOWN, pygame.QUIT])
overworld = world.World(pygame.Vector2(0, 0), 2, 8)
run_game()
world.py
import pygame
from bisect import bisect
from itertools import product
BLOCK_SIZE = 64
BLOCK_TEXTURE_NAMES = [
"textures/void.png",
"textures/air.png",
"textures/grass_block.png",
"textures/dirt.png",
"textures/stone.png",
"textures/sandstone.png",
"textures/sand.png",
"textures/bedrock.png",
"textures/oak_log.png",
"textures/oak_leaves.png",
"textures/cobblestone.png",
]
def block_texture(texture):
return pygame.transform.scale(
pygame.image.load(texture), (BLOCK_SIZE, BLOCK_SIZE)
).convert_alpha()
def convert(pos, convert_value_x, convert_value_y):
"""Converts coordinate systems."""
nx, rx = divmod(pos.x, convert_value_x)
ny, ry = divmod(pos.y, convert_value_y)
return ((nx, ny), (rx, ry))
class Chunk:
surface = 0
bedrock = 16
ground = 3
starts = (surface, ground, bedrock)
levels = dict(zip(starts, (2, 3, 7)))
block_sizes = (1, 3, 4, 0) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def __init__(self, pos, size):
self.size = size
self.actual_size = size * BLOCK_SIZE
self.block_textures = [
block_texture(texture) for texture in BLOCK_TEXTURE_NAMES
]
self.backround_texture = block_texture("textures/backround.png")
self.pos = pos
self.actual_pos = pos * BLOCK_SIZE
self.surface = pygame.Surface((self.actual_size, self.actual_size))
self.x_range = range(self.size)
self.y_range = range(self.size)
self.blocks = {}
def update(self, block_pos, new_block=None):
vector = pygame.Vector2(block_pos) * BLOCK_SIZE
self.surface.blit(self.backround_texture, vector)
self.blocks[block_pos] = block = new_block or self.blocks[block_pos]
self.surface.blit(block, vector)
def generate(self):
for x, y in product(self.x_range, self.y_range):
y_pos = int(self.pos.y) + y
if y_pos in self.levels:
block = self.levels[y_pos]
else:
i = bisect(self.starts, y_pos)
block = self.block_sizes[i]
self.update((x, y), block)
def set_blocks(self, blocks):
self.blocks = blocks
for x, y in product(self.x_range, self.y_range):
self.update((x, y))
def __str__(self):
return str([self.blocks[(x, y)] for x in self.x_range for y in self.y_range])
class Vector(pygame.math.Vector2):
def __hash__(self):
return int(self.x * 10 + self.y)
class World:
def __init__(self, loader_pos, loader_distance, chunk_size):
self.chunk_size = chunk_size
self.actual_chunk_size = chunk_size * BLOCK_SIZE
self.loaded_chunks = {}
self.loader_pos = loader_pos
self.set_loader_chunk_pos(loader_pos)
self.loader_distance = loader_distance
self.rendered = pygame.Surface((1, 1)).convert_alpha()
self.innactive_block_data = {} | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def handle_chunk_loader(self):
chunks_needed = {Vector(i) for i in self.chunks_to_load()}
loaded_chunks = {Vector(i) for i in self.loaded_chunks}
self.load_chunks(chunks_needed - loaded_chunks)
self.unload_chunks(loaded_chunks - chunks_needed)
def get_data(self, chunk_pos):
return self.innactive_block_data.get(chunk_pos, False)
def load_chunks(self, chunks_pos):
for pos in chunks_pos:
chunk_pos = (pos.x, pos.y)
self.loaded_chunks[chunk_pos] = Chunk(pos, self.chunk_size)
(
self.loaded_chunks[chunk_pos].set_blocks(block_data)
if (block_data := self.get_data(chunk_pos))
else self.loaded_chunks[chunk_pos].generate()
)
def unload_chunks(self, chunks_pos):
for chunk_pos in chunks_pos:
chunk = self.loaded_chunks.pop(chunk_pos)
if self.get_data(chunk_pos) != chunk.blocks:
self.innactive_block_data[chunk_pos] = chunk.blocks
def get_block(self, pos):
chunk_pos, block_pos = convert(pos, self.chunk_size, self.chunk_size)
try:
return self.loaded_chunks[chunk_pos].blocks[block_pos]
except IndexError:
return False
def get_range(self, axis):
n = int(getattr(self.loader_chunk_pos, axis))
return range(
n - self.loader_distance,
n + self.loader_distance + 1,
)
def chunks_to_load(self):
return [
pygame.Vector2(chunk_pos_x * self.chunk_size, chunk_pos_y * self.chunk_size)
for chunk_pos_x, chunk_pos_y in product(
self.get_range("x"), self.get_range("y")
)
]
def set_loader_chunk_pos(self, pos):
self.loader_chunk_pos = pygame.Vector2(
convert(pos, self.actual_chunk_size, self.actual_chunk_size)[0]
) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, performance, game, pygame, minecraft
def change_pos(self, pos):
self.loader_pos += pos
self.set_loader_chunk_pos(self.loader_pos)
def set_pos(self, pos):
self.loader_pos = pos
self.set_loader_chunk_pos(pos)
def render(self, screen, use_pos, other_offset=0):
for ch in self.loaded_chunks.values():
screen.blit(
ch.surface,
(ch.actual_pos - self.loader_pos * int(use_pos)) + other_offset,
) | {
"domain": "codereview.stackexchange",
"id": 44750,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, game, pygame, minecraft",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
Title: ANN with Backpropagation for MINST data set
Question: 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:
import numpy as np
import pandas as pd
#read the data from file
data = pd.read_csv('data_set_file') #use the provided file or use cloud based ones
data = np.array(data)
m, n = data.shape
np.random.shuffle(data)
data_dev = data[0:1000].T
Y_dev = data_dev[0]
X_dev = data_dev[1:n]
X_dev = X_dev / 255.
data_train = data[1000:m].T
Y_train = data_train[0]
X_train = data_train[1:n]
X_train = X_train / 255.
def init_parameters():
W1 = np.random.normal(size=(10, 784)) * np.sqrt(1./(784))
b1 = np.random.normal(size=(10, 1)) * np.sqrt(1./10)
W2 = np.random.normal(size=(10, 10)) * np.sqrt(1./20)
b2 = np.random.normal(size=(10, 1)) * np.sqrt(1./(784))
return W1, b1, W2, b2
def ReLU(Z):
return np.maximum(Z, 0)
def softmax(Z):
exp = np.exp(Z - np.max(Z))
return exp / exp.sum(axis=0)
def forward_prop(W1, b1, W2, b2, X):
Z1 = W1.dot(X) + b1
A1 = ReLU(Z1)
Z2 = W2.dot(A1) + b2
A2 = softmax(Z2)
return Z1, A1, Z2, A2
def ReLU_deriv(Z):
return Z > 0
def one_hot(Y):
one_hot_Y = np.zeros((Y.size, Y.max() + 1))
one_hot_Y[np.arange(Y.size), Y] = 1
one_hot_Y = one_hot_Y.T
return one_hot_Y
def backward_prop(Z1, A1, Z2, A2, W1, W2, X, Y):
one_hot_Y = one_hot(Y)
dZ2 = A2 - one_hot_Y
dW2 = 1 / m * dZ2.dot(A1.T)
db2 = 1 / m * np.sum(dZ2, axis=1).reshape(-1, 1)
dZ1 = W2.T.dot(dZ2) * ReLU_deriv(Z1)
dW1 = 1 / m * dZ1.dot(X.T)
db1 = 1 / m * np.sum(dZ1, axis=1).reshape(-1, 1)
return dW1, db1, dW2, db2 | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
def update_parameters(W1, b1, W2, b2, dW1, db1, dW2, db2, a):
W1 = W1 - a * dW1
b1 = b1 - a * db1
W2 = W2 - a * dW2
b2 = b2 - a * db2
return W1, b1, W2, b2
def get_predictions(A2):
return np.argmax(A2, 0)
def get_accuracy(predictions, Y):
print(predictions, Y)
return np.sum(predictions == Y) / Y.size
def gradient_descent(X, Y, a, epochs):
W1, b1, W2, b2 = init_parameters()
for i in range(epochs):
Z1, A1, Z2, A2 = forward_prop(W1, b1, W2, b2, X)
dW1, db1, dW2, db2 = backward_prop(Z1, A1, Z2, A2, W1, W2, X, Y)
W1, b1, W2, b2 = update_parameters(W1, b1, W2, b2, dW1, db1, dW2, db2, a)
if i % 10 == 0:
print("Iteration: ", i)
predictions = get_predictions(A2)
print(get_accuracy(predictions, Y))
return W1, b1, W2, b2
W1, b1, W2, b2 = gradient_descent(X_train, Y_train, 0.10, 120)
def make_predictions(X, W1, b1, W2, b2):
_, _, _, A2 = forward_prop(W1, b1, W2, b2, X)
predictions = get_predictions(A2)
return predictions
dev_predictions = make_predictions(X_dev, W1, b1, W2, b2)
get_accuracy(dev_predictions, Y_dev)
Results:
Training_data accuracy
Dev_data
If there are improvements to the code feel free to share or point it out.
Things that I am confused about:
I am supposed to split the data into 70% training data, 10% dev data and 20% test data.
(While the data is not currently split in the right percentage and the test data is missing because I am not sure get of how I should use it)
From what I have gathered the training data is used to train the network. What am I supposed to do with the other 2 I used the dev data to see how the model generalized from the training data. Should I be doing something else with the test and dev data?
I am asking this because I have this question I am trying to answer: | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
percentage of correctness of the total test data set (20% of all
cases)
percentage of correctness of each of the classes in the test data set.
Edit:
This is how I would split the data:
#validation set (10%)
data_dev = data[0:4200].T
Y_dev = data_dev[0]
X_dev = data_dev[1:n]
X_dev = X_dev / 255.
#yesting set(20%).
data_test = data[4200:12600].T
Y_test = data_test[0]
X_test = data_test[1:n]
X_test = X_test / 255.
#training set (70%),
data_train = data[12600:m].T
Y_train = data_train[0]
X_train = data_train[1:n]
X_train = X_train / 255.
Answer: Your code has several major flaws, but first just what the heck is the dataset? What is the code all about?
I downloaded the text file, and opened it, and what the heck is it?
Okay, so the first column is named label, then the rest of the columns are named pixel-something. The rows seem to be all integers, and after some researching I determined the numbers to be all between 0 and 255.
The numbers are one byte, and the columns are named pixels? Oh, I got it, each row must represent a flattened grayscale image. But what exactly is the image?
The last column is pixel783, and the pixel column names start at pixel0, so there are 784 pixels per image. 784 pixels, the prime factorization of 784 is [2, 2, 2, 2, 7, 7], and, oh, the numbers can be rearranged to [28, 28], so each row starts with the label and then the bytes of a flattened 28x28 grayscale image!
But what are the images exactly?
I wrote the following code to find out:
import cv2
import numpy as np
from pathlib import Path
def to_image(data):
return np.array(data).reshape((28, -1))
data = Path("C:/Users/Xeni/Desktop/data.csv").read_text().splitlines()[1:]
for i, row in enumerate(data):
label, *row = list(map(int, row.split(',')))
cv2.imwrite(f'D:/dataset_images/{label}-{i}.png', to_image(row)) | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
These are 28x28 grayscale images of handwritten decimal digits that are already classified. There are 42K of them in total. So your neural network is used to classify handwritten digits! But you didn't mention the purpose of your code or the nature of the dataset anywhere in your question, you owe to clarify it.
Now onto the actual reviewing
Code execution at the top of script
data = pd.read_csv('data_set_file')
Don't do that, if you put code execution directly at the top of module, it can and will cause trouble when you try to import the module.
Instead use a main guard, so that the code will only be executed when the module is run directly, allowing the module to be imported.
Like this:
if __name__ == '__main__":
data = pd.read_csv('data_set_file')
Naming of globals
You have a lot of global variables in lowercase, you need to convert them to UPPERCASE to denote that they are global variables.
Floating code repetition and unnecessary variable assignment
data_dev = data[0:1000].T
Y_dev = data_dev[0]
X_dev = data_dev[1:n]
X_dev = X_dev / 255.
data_train = data[1000:m].T
Y_train = data_train[0]
X_train = data_train[1:n]
X_train = X_train / 255.
Did you notice that in the above two blocks of code, the only actual difference is the index slicing? Since you already used functions, you need to put repeated code into functions, and this should be put into functions.
You can use destructuring assignment to assign a sequence to two variables.
If you do a, b = (0, 1), then a == 0 and b == 1. But this doesn't work with sequences with more than two elements.
So you need to do this: a, *b = (0, 1, 2, 3, 4), then a == 0 and b == (1, 2, 3, 4). The * operator is unpacking the rest of the list, the above line first assigns the first element to a and then assigns whatever remains to b.
X_dev = data_dev[1:n]
X_dev = X_dev / 255. | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
You have a lot of intermediate variables like the example above. there is no need to do two assignments and do the second assignment immediately after the first assignment without ever using the first variable. And absolutely no need to assign a name and the immediately return the result.
Also adding a trailing . to ints to make the result of division floats is completely unnecessary, / is float division operator and the result is automatically float. To get int division result you have to use the floor division operator //.
Just do this: X_dev = data_dev[1:n] / 255 and this return do_something().
M, N = DATA.shape
def get_xy(start, end):
y, *x = DATA[start:end].T[:N]
return y, np.array(x) / 255
Y_DEV, X_DEV = get_xy(0, 4200)
Y_TEST, X_TEST = get_xy(4200, 12600)
Y_TRAIN, X_TRAIN = get_xy(12600, M)
Repetition and way too many arguments
def init_parameters():
W1 = np.random.normal(size=(10, 784)) * np.sqrt(1./(784))
b1 = np.random.normal(size=(10, 1)) * np.sqrt(1./10)
W2 = np.random.normal(size=(10, 10)) * np.sqrt(1./20)
b2 = np.random.normal(size=(10, 1)) * np.sqrt(1./(784))
return W1, b1, W2, b2 | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
In the above function you made several mistakes, first there is absolutely no need to use numpy.sqrt to get the square root of some number. You can use the built-in ** exponentiation operator for that. Just do n ** 0.5.
Second you used (10, 1) twice and np.sqrt(1./(784)) twice, you need to create variables for them.
Third 784 is a magic number, it is the number of pixels in each image, which is equivalent to the number of columns minus one. What if the input was different? What if the input has different number of columns? Then your code stops working outright. You need to calculate that number based on the number of columns.
Fourth you used the same line multiple times, with exactly the same number of variables and positions of variables. This is a prime candidate for a for loop, you just need to extract the variables into a collection and loop through that collection and operate on them in the loop body.
And finally you are passing way too many variables around, with different groups of four variables that are always passed in the same order. You need to refactor your code into a class so that class knows the variables without passing the arguments. And you need to put them into a stack and get them from the stack to make things easier.
def sqrt_inv(n):
return (1 / n) ** 0.5
L = N - 1
TEN_ONE, SQRT_INV_L = (10, 1), sqrt_inv(L)
PARAMETERS = (
((10, L), SQRT_INV_L),
(TEN_ONE, sqrt_inv(10)),
((10, 10), sqrt_inv(20)),
(TEN_ONE, SQRT_INV_L),
)
def init_parameters(self):
self.weights = [
np.random.normal(size=size) * scale for size, scale in PARAMETERS
] | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
I will explain the second function later.
Matrix multiplication
Don't use np.dot to get the dot product of two matrices. .dot() is six characters. You should use the matrix multiplication operator @ to do that. It is designed for exactly this purpose. And much more concise (saves five characters).
Repetition and passing way too many arguments that go around
def forward_prop(W1, b1, W2, b2, X):
Z1 = W1.dot(X) + b1
A1 = ReLU(Z1)
Z2 = W2.dot(A1) + b2
A2 = softmax(Z2)
return Z1, A1, Z2, A2
def backward_prop(Z1, A1, Z2, A2, W1, W2, X, Y):
one_hot_Y = one_hot(Y)
dZ2 = A2 - one_hot_Y
dW2 = 1 / m * dZ2.dot(A1.T)
db2 = 1 / m * np.sum(dZ2, axis=1).reshape(-1, 1)
dZ1 = W2.T.dot(dZ2) * ReLU_deriv(Z1)
dW1 = 1 / m * dZ1.dot(X.T)
db1 = 1 / m * np.sum(dZ1, axis=1).reshape(-1, 1)
return dW1, db1, dW2, db2
def update_parameters(W1, b1, W2, b2, dW1, db1, dW2, db2, a):
W1 = W1 - a * dW1
b1 = b1 - a * db1
W2 = W2 - a * dW2
b2 = b2 - a * db2
return W1, b1, W2, b2
def gradient_descent(X, Y, a, epochs):
W1, b1, W2, b2 = init_parameters()
for i in range(epochs):
Z1, A1, Z2, A2 = forward_prop(W1, b1, W2, b2, X)
dW1, db1, dW2, db2 = backward_prop(Z1, A1, Z2, A2, W1, W2, X, Y)
W1, b1, W2, b2 = update_parameters(W1, b1, W2, b2, dW1, db1, dW2, db2, a)
if i % 10 == 0:
print("Iteration: ", i)
predictions = get_predictions(A2)
print(get_accuracy(predictions, Y))
return W1, b1, W2, b2 | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
In the above mess you are doing way too many mistakes. You are reusing the same lines of code that have to be put into functions without putting them into functions. Passing way too many variables around, some of them are even not changed. And using two-stage intermediate assignments again. And not assigning 1/m as a global variable. And using i % 10 == 0 instead of not i % 10...
To solve the many problems, first consider update_parameters function. You are taking two groups of numbers, and assign the value of the element from the first group minus some number times the respective element from the second group with the same index, back to the element from the first group.
This is a perfect candidate for for loops, more specifically for a, b in zip(A, B):. The second group needs to be multiplied before-hand.
I have refactored the function to this:
def update_parameters(self):
self.weights = [a - b for a, b in zip(self.weights, self.deltas)]
If you put all those functions in the same class you don't have to pass all those arguments around at all.
You have three groups of four variables that are related, and that are always passed around together. If you put each four of the same group inside a list, you can make things much easier.
But then how do you access them? Use named attributes to mask list indexing.
Like this:
class Foo:
r = range(10)
@property
def last(self):
return self.r[-1]
Foo().last returns 9.
But here there are 12 properties, how do we add them while avoiding repetition?
Use setattr with functions already passed to property.
groups = (
("weights", ("W1", "b1", "W2", "b2")),
("corrections", ("Z1", "A1", "Z2", "A2")),
("deltas", ("dW1", "db1", "dW2", "db2")),
)
def add_property(group, name, i):
setattr(Neural_Network, name, property(lambda self: getattr(self, group)[i]))
for group, names in groups:
for i, name in enumerate(names):
add_property(group, name, i) | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
python, beginner, python-3.x, machine-learning, neural-network
I have refactored your code completely, and it is much better now.
(By the way the naming of your variables is really bad, it is even more confusing than my variable names. But I can't fix the variable names because I know how the code works but I have no idea WHY any of your neural network code works)
Refactored code:
import numpy as np
import pandas as pd
class Neural_Network:
@staticmethod
def ReLU(Z):
return np.maximum(Z, 0)
@staticmethod
def softmax(Z):
exp = np.exp(Z - np.max(Z))
return exp / exp.sum(axis=0)
@staticmethod
def ReLU_deriv(Z):
return Z > 0
@staticmethod
def one_hot(Y):
one_hot_Y = np.zeros((Y.size, Y.max() + 1))
one_hot_Y[np.arange(Y.size), Y] = 1
return one_hot_Y.T
@staticmethod
def calc_diff(dz, t):
return MINV * dz @ t, MINV * np.sum(dz, axis=1).reshape(-1, 1)
def __init__(self, X, Y, a):
self.X = X
self.Y = Y
self.a = a
self.init_parameters()
def init_parameters(self):
self.weights = [
np.random.normal(size=size) * scale for size, scale in PARAMETERS
]
def forward_prop(self):
Z1 = self.W1 @ self.X + self.b1
A1 = Neural_Network.ReLU(Z1)
Z2 = self.W2 @ A1 + self.b2
A2 = Neural_Network.softmax(Z2)
self.corrections = [Z1, A1, Z2, A2]
def backward_prop(self):
dZ2 = self.A2 - Neural_Network.one_hot(self.Y)
dW2, db2 = Neural_Network.calc_diff(dZ2, self.A1.T)
dZ1 = self.W2.T @ dZ2 * Neural_Network.ReLU_deriv(self.Z1)
dW1, db1 = Neural_Network.calc_diff(dZ1, self.X.T)
self.deltas = [self.a * i for i in (dW1, db1, dW2, db2)]
def update_parameters(self):
self.weights = [a - b for a, b in zip(self.weights, self.deltas)]
def get_predictions(self):
self.predictions = np.argmax(self.A2, 0) | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, machine-learning, neural-network",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.