instruction stringlengths 71 95.1k |
|---|
I wrote this program which generates anagrams for a given word.
The init function will create a dictionary of words. it can be read from a text file or array. Here I'm reading words from an array to create my dictionary.
I would like some advice on how to optimize this code or any changes or suggestions needed to impro... |
This is a simple strlen function with registers documented:
;in rdi - string to measure
;out rax - len
.my_strlen:
test rdi, rdi
jz ptr_error
or rcx, 0xFFFFFFFFFFFFFFFF
mov al, 0
cld
repne scasb
mov rax, 0xFFFFFFFFFFFFFFFF
sub rax, rcx
ret
NOTE: This code assumes a "C-Style string"; that is, a NUL-terminated string.
|
I am new to writing utility functions. I wrote a python program to return a Python logger with custom settings. Please review this code and provide comments on how to improve it. I am looking for comments on
Coding Style
Coherence & Coupling
Readability
I am intending to share this code across all projects. So any c... |
I have finished a raycaster, and I want to optimize it before I add other features, such as variable height walls, texture mapping and lighting. I'd like someone to review the code so I can improve it further.
Pastebin
#include <stdio.h>
#include <SDL2/SDL.h>
#include <sys/time.h>
const int RESX = 960;
const int RESY ... |
I am fairly new into asp.net MVC c# I am working on request holiday app where an employee can request holidays. The problem is the app works fine, however, I am trying to set 8 hours a day when an employee requests a holiday I have scratching my head from 2 days already seen every topic in StackOverflow and here and s... |
I'm trying to process numerical input arguments for a function. Users can mix ints, floats, and "array-like" things of ints and float, as long as they are all length=1 or the same length>1.
Now I convert them as follows:
convert to float convert to np.ndarray; dtype==float
---------------... |
Review on this draft please: clang-8 -std=c++17
Simple wrapper class template for std::map & std::list (or alternatively std:unordered_map & std::vector) for the purpose of "retaining insertion order". This is quite a frequently asked question, eg
https://stackoverflow.com/questions/2266179/c-stl-map-i-dont-want-it-to... |
A quine is a program whose only job it is to reproduce the source file that was used to create the executable in the first place.
This stackoverflow post provides some reasoning about its usefulness.
Below I present 5 different quines.
The nice quine
This program has an embedded copy of its complete source (minus that... |
I wrote this code since I'm going through the hackerrank challenges, however, it takes way too long to run.
Its function is described on the title, but just to clear it up, we need to count the minimum amount of swaps needed to order a set of ascending integers.
def minimumSwaps(arr):
count = 0
correct = [(x+1)... |
I started learning VBA for an internship, 3 months ago. This is the last project I have worked on.
It does all the tasks it has to do, it's all about code review. I will be grateful for all suggestions for optimization of solutions/other solutions, good practices (writing, commenting on the code) and everything else th... |
I'm growing a web server in Haskell that interfaces with TCP sockets using network. To read the HTTP header of the client's message, I use the following function:
import Network.Socket hiding ( recv )
import Network.Socket.ByteString ( recv )
import qualified Data.ByteString ... |
I want to significantly tidy this code as its cluttered and repetitive
var myDate = "No MOT"
if ((myData[0]["motTests"][0]["expiryDate"].string) != nil) {
let theDate=myData[0]["motTests"][0]["expiryDate"].string
let msYear = theDate!.prefix(4)
let msMonth = theDate!.suffix(5).prefix(2)
let msDay = th... |
I made a function that outputs the sum of the value of each letter in a word. For example if I input hello my function would output 52.
def words_to_marks(s):
import string
values = {} # dictionary to store value of each alphabet
values_of_words = [] # to store final value of words
for in... |
Is there a better way to write this code.
Suppose I have 10 files to delete and I have to repeat code (public function destroy() ) 10 times.
First remove the database entry.
List item, then remove the file.
OOP - "don't repeat yourself", it works but I repeat the code.
public function image_path() {
return ... |
I am in the process of trying to teach myself Python, and am at a point where I feel some general feedback on my styling/code efficiency would be super useful in order for me to progress.
I have created a simple banking system in order to practice OOP (which I am still finding a little confusing).
Would anyone be able ... |
UPDATE: Current best state of a solution incorporating feedback and further development is in this answer.
Review on this Design#2 please:
Simple wrapper class template for std::map for the purpose of "retaining insertion order". This is quite a frequently asked question, here and here.
This is the follow on 2nd Desi... |
I've started learning Rust recently using the Rust book.
In one of the chapters, the authors encourage the reader to experiment with closures, and try to create a generic cache implementation.
I've managed to get it working as below. However, it irks me that I need to add Clone trait on the input argument in the get() ... |
I have written a matrix class using python, allowing me to perform a variety of operations on matrices. I'm pretty happy with how it performs, and everything works fine. However, I feel like the way I've handled the initialiser could be much improved.
I wasn't sure how to handle different possible cases for the argumen... |
This fasm x64 (Linux) code seems very crude and repetitive, but it gets the job done. How could I perform this task in a more idiomatic manner?
format ELF64 executable 3
segment readable executable
entry $
prompt_user:
mov edx,prompt_len
lea rsi,[prompt] ;<------ String
mov edi,1 ; STDOUT
mov eax,1 ; s... |
I have two buttons
1) Chat button
2) Annotation Button
On tap each view comes from bottom and when tap outside view hidden back (Please refer the screen shot)
On tap On annotation
On tap on Chat
To Handle This I have created following classes
//Annotaion Card
struct CardInfo {
enum CardState {
ca... |
I'm trying to make a dice game with three dice and with rules.
It costs 10 credits to roll the dice.
If you get 6 6 6 you win 90 credits.
If you get 5 5 5, 4 4 4, 3 3 3, 2 2 2, 1 1 1, you win 40 credits.
If two of the dice have the same number you win 0 credits (because it costs 10 to roll).
Here's what I've done so ... |
I have a HashMap and I want to convert data in it to a Response object. Is it possible to achieve this code that parses the string in a better and optimized and cleaner way, maybe by using streams?
class Converter{
public static void main(String[] args) {
Map<String, Long> map = new HashMap<String, Long>();
... |
GitHub and NuGet
I would like to use DynamicObject derived types to execute REST API/NodeJS module calls. It would also help to capture API shape in a strictly typed manner, so here comes an interface proxy which hides low level machinery allowing to do tricks like this:
[TestMethod]
public void Call()
{
dynamic c... |
For my Python project, I wanted to make a crossword game GUI with SQL connectivity to display high scores. I tried to learn tkinter, but the only difficulty was that I cannot use classes or objects as they are not taught at my school yet. Still I managed to make a highly inefficient and ugly looking code (I am a newbi... |
I have written many variations of the Sieve of Eratosthenses, which is the fastest way to generate a large collection of primes. (@slepic asked for clarification, which I provide in an answer below. My intended statement is that a sieve in general is much faster than naive methods at generating lots of primes; not tha... |
This is my second script in my first language so I'm trying to get oriented and better foundations. I noticed in the while loop I got really messy but I couldn't google my way to a better solution that I could understand. With that, I'd appreciate any feedback that makes my code more "pythonic" or clean.
import random... |
I am trying to build an OOP design for an election system.
A citizen can nominate themselves to be a contender. So all contenders are citizens. I was thinking of keeping the relation ship IS-A by having contender extend citizen, but I am not able to understand how i will have a citizen nominate themselves then.
Citizen... |
I'm learning OOPs design principles and design patterns. As an exercise, I came up with this model for multiple user authentication using OOPs. I plan to build this on top of a Flask server, but I've just mocked the behavior for now.
Please let me know your thoughts about the implementation design. Thanks in advance.... |
Can you please help me fulfill the following?
Requirements:
Create an iterable with unique elements. Their order should be preserved:
a | b | a | c → a | b | c
The program must continually write to stdout.
The program must be computationally efficient.
The program must be written in the Functional programming paradig... |
I have the following Django models setup:
class Publication(models.Model):
value=models.CharField(max_length=255, unique=True)
class Article(models.Model):
filename = models.CharField(max_length=255)
publication = models.ForeignKey(Publication, on_delete=models.CASCADE)
class Image(models.Model):
name... |
I'm new to using VBA. What I'm working on is to copy details from a master file to multiple sheets within a worksheet.
I'm facing a performance problem when I run my code, my Excel file keeps blinking and not responding.
My code is as follows.
Sub Button1_Click()
Dim lastrow As Long
Dim erow As Long
Dim i As Integer
M... |
I was wondering if any of you would mind reviewing my program? I'm a beginner / aspiring programmer and I'm looking for tips on how I could make my program more efficient. For example, have I made good use of sub-routines / functions? Am I using classes properly? Is there anything I could do to perhaps shorten the leng... |
Context
I'm looking into design patterns. My first try is using the Decorator Pattern.
Question:
Is there another (maybe standard) approach to applying modifications in a decorator other than explicitly overwriting in the constructor?
-
Car Interface
<?php
interface CarInterface
{
public function drive();
}
C... |
I've decided to write a very simply output programming language. All the user does is write ASCII values inside ASCII fish, and the interpreter pieces the values together and outputs them.
I'm mainly looking for feedback on the interpreter, as the language itself is very easy to understand.
Here's what a Hello, World! ... |
GitHub and NuGet
Allows to invoke public/private REST API just by defining an interface. 200 lines of C# in total.
Demo
Sample API is publicly available at http://jsonplaceholder.typicode.com:
public interface ITypicode : IDisposable
{
[Description("GET posts")]
Task<BlogPost[]> GetAsync();
[Description("G... |
def start():
import time
ans = input("Do you wish to start again? [y/n]\n")
if ans == 'y' or ans == "yes" or ans == "":
print(' \n' * 30)
main()
elif ans == 'n' or ans == "no":
exit()
else:
print("Invalid Input\n")
time.sleep(3)
start()
def main():
... |
I wish to generate an online feedback system. Requirements are
Admin can enter feedback questions
Admin will select these questions and create a feedback session
One Question can be used in many feedback session
User can select any feedback session and answer/rate
one user can answer same feedback session more than o... |
So, I'm implementing LZ77 compression algorithm. To compress any file type, I use its binary representation and then read it as chars (because 1 char is equal to 1 byte, afaik) to a std::string. Current program version compresses and decompresses files (.txt, .bmp, etc) just fine – size of raw file in bytes matches the... |
I have a struct of integers and I am trying to increase them based on rules. For example, rule_1 is the max limit that the first increase should reach.
I want to change the order of additions based on priorities map (a=1,b=2,c=3), increase first "a", then "b", then "c". If I change the priorities (a=3,b=2,c=1), the ad... |
Inspired by this question.
Here's the code:
class FishyError(Exception):
__module__ = Exception.__module__
def string_to_fishy(string: str) -> str:
"""
Converts a string to fishy code
Examples:
Hello World!
><72> ><101> ><108> ><108> ><111> ><32> ><87> ><111> ><114> ><108> ><100> ><33>... |
I am trying to improve the efficiency of my code,
The Question is:
Given a value n, where n is in the range [0 .. 500], return the number of digits equal to 1 in the decimal representation of the number \$11^n\$.
Naturally when dealing with a larger power (where n is a large number), this reduces the efficiency drastic... |
Here's what I've come up with:
def bf_interpreter(code: str) -> str:
"""
Interprets BrainF**k code
Examples:
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
Hello World!
+++++>++++[<+>-]++++++++[<++++++>-]<.
9
... |
I have a small todo app where you can add and mark todos as completed. I structured it that all the data is kept in the parent container (TodoWrapper), that renders 2 components which are the toDo list and the createTodo component. I see others who are having state inside the createTodo component wonder if that is good... |
I am learning OOP, concretely Java, by developing a real life business application for aimed for repair shops. I have followed MVC pattern design for GUI elements of my application. I was wondering do my input dialog controller classes has to much responsibilities. They set ComboBox models, button ActionListeners, veri... |
This question is the adaptation of this question in C++. (I'm the author of that code as well).
The code:
#include <bits/stdc++.h>
std::string bf_interpreter(std::string code){
long long int ptr = 0;
std::vector<int> values = {0};
long long int length = 1;
std::vector<int> brackets;
std::string ... |
Is this good way of creating tests? I have no experience how they do it in companies. Ignore uppercase names of variables.. I may change it eventually.
reduction_strategy.py defines my ListArray class, which I've written unit tests for.
ListArray defines object that takes care of matrices containing symbolic elements. ... |
I am trying to practice OOP and TDD concepts,
I have written this code for Mars rover challenge from
marsrovertechchallenge .
Can you please review my code from my GitHub repository?
Or you can review the four files below.
This would be really helpful for me to improve my OOP skills.
The MarsRoverCode.java contain the... |
I created a simple script that is used to implement Google's Chromecast wallpaper-images as the wallpaper of my Gnome desktop.
The script extract the images from 2 different sources:
A static webpage containing a collection of the Chromecast images
A dynamic (javscript driven) webpage that shows a different wallpape... |
I've been trying to remember old programming concepts like data structures.
My first challenge was about implementing my own array of positive integers:
#include<stdio.h>
#include<stdlib.h>
int* array_initialize(int size) {
return calloc(size, size * sizeof(int));
}
void array_set(int *array, int index, int value... |
I'm new in Prolog. So, I'm not sure if my code is ok and optimized. I'm also not sure if I use recursion correctly.
Task: find students that has at least 1 bad grade (1 or 2) and print them in table
hasBadGrades(N) :- student(_, N, G), containsBadGrades(G).
containsBadGrades([H|T]) :- wildcard_match('*/[1-2]', H); co... |
I wrote a program which solves Pentomino puzzles by using Knuth's Algorithm X. My priorities were: readability, straightforwardness and brevity of the solution, so I didn't try to squeeze as much performance as possible by eliminating function calls in some places or similar tricks.
I am interested in:
The code review... |
I am making a Reddit bot and to prevent my bot from posting to the same comment twice, instead of making a database, I decided I would rather create a temporary list (or "queue") that once appended to, checks to ensure the maximum length of the queue hasn't been exceeded. Once exceeded, however, the queue is cleared.
c... |
I'm trying to do a simple implementation of a scp wrapper in Elixir.
The code is working as intended, but I got a feeling that the error conditions can be simplified. Besides error handling, I don't the best way to append the -r flag if the source_path is a directory with a cond keyword.
defmodule Scp do
def scp(user... |
I have a part of my code I want to optimize.
I use if statement to skip the analyze if the values are not the one I want.
Just to help the comprehension, in my data, R1 is between range(6,15); mis in range(0,1); spacer in range (0,10).
My code is working, but it would be better if it will run faster according to the a... |
Consider I have many enums (Java) that looks somewhat like this:
@AllArgsConstructor
@Getter
public enum PopularPeriod {
MONTHLY ("MON"),
BIMONTHLY ("BMN"),
QUARTERLY ("QTR"),
SEMI_ANNUALLY ("SMA"),
ANNUALLY ("ANL");
private final String value;
}
Now, a usual use, I'd think, would be to get the enum o... |
The following works as expected but I wonder if there is a more idiomatic way to check the input kwargs against the user-required (non-defaulted) arguments.
It is written in this way: so that as I continue to develop and modify my script and add attributes, I simply need to add them to the class variable defaults = {'A... |
I have a form built with react, formik and yup, and this form has some async validations. Apparently, some users were able to bypass these validations, and to prevent some errors, I wanted to disable the submit button when there's a pending http request.
Many years ago, I used to handle this very easily with jQuery, bu... |
I am learning to write test cases in iOS using Swift. I was stuck at testing static functions from my Utilities class, so I tried to mock that class and then test the cases. Please let me know if its the correct approach or else tell me how to do that. Here is my code:
import XCTest
@testable import ConnectAndSell
cla... |
I have a Canny Edge Detection Code written in C++. I would like to know how can I make it more robust in terms of detecting all the edges correctly and save it? Is this the best possible edge detection possible? Can the coders find any error in my code? Below is a picture of how the code looks like.
#include <opencv2/i... |
I have a live webcam windows which means there are six subdivided windows in a single window live. And show pictures in colored and black and white. Is there anyway I can make the code minimalistically minimized? I believe the code is considerably long.
import cv2
import cv
import numpy as np
import matplotlib.image a... |
The following classes are used for web development. And I was wondering if I'm implementing them correctly specially the Base class.
This is a version 2.0 of the question the classes are as follows:
MyPDO
Session
Security
Base
Examples:
<?php
//using the autoloader
require "../classes/autoloader.php";
// checking if... |
I have a C++ program where the input are 2 arrays, each containing a and z number of elements. The program then creates all possible combinations using all elements in both arrays. For example, if one array had 2^4 elements and the other had 2^7 elements, the total possible combinations would be (16 - 1) * (128 - 1) = ... |
I have functioning code that I wrote what seems like a long time ago in a Worksheet_Change event, and even though this works I'm sure that it can be written better. I'm thinking passing the items like CustName = Split(cell.Offset(0,-1).Value, "-")(0) to a variable in a Sub or Function for generating the Email, might b... |
I have this code to weave the split_input ['5,4 4,5 8,7', '6,3 3,2 9,6 4,3', '7,6', '9,8', '5,5 7,8 6,5 6,4'] together. However I feel like this can be done more efficient (especially the weave function) but I have no clue how to improve it without importing any modules.
class Class1:
def __init__(self, row):
... |
I have e single live webcam camera. I have displayed one color image, black and white image and canny edge image. Do you think I should put a scrollbar for the canny edge detection amount to make it a standard program or current threshold is fine?
import cv2
import cv
import numpy as np
import matplotlib.image as mpimg... |
Please bear in mind, I've only started learning c++ this week, and as such, would love topic suggestions for which I should master, to become better at C++.
Below, is my code for a singly linkedlist. It doesn't have complete functionality, just the ability to print, append, and add a node at a specified index.
Current... |
I have an array of hashes (price_params['items']) where each item has a key called quantity what I'm trying to do is to clean every duplicate of each item but keeping the count of the times the item was found in the array in the unique one that I'm leaving (using the quantity key to keep that value)
This is my code so ... |
We have to execute a bunch of jobs , each have an ID and they are passed on to the processor . Since the processor can only work on a limited number of jobs (denoted by deleteBatchSizeMax in the code snippet),we are using a paged approach so that only a subset is picked up by the processor.To implement this we have a f... |
This mandelbulb-set generator creates a .xyz file which contains all the points that are in the set which lie on a 3D grid. It does what it is supposed to.
However, the number of calculations done is proportional to the cube of the resolution*, which means that the script takes very long if the resolution is in the ord... |
I was trying to create a simple RAII wrapper with rule of 5 for a TCP POSIX socket. My aim was to try learn how to apply rule of five in different situations, but this one was somehow tricky.
class tcp_socket {
public:
tcp_socket() {
_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
tcp_socket(cons... |
I have a tool that displays data in some format. For example, it can display a list of dogs in a CSV or JSON formats.
In the code, I had a lot of places where I had to check the format and display the data in that format. The only difference between the code blocks is the calls to the data.
Some of them call get_name(... |
Problem
Developers in my team are new to Docker. I wanted to provide a way to accomplish general Docker housekeeping tasks (like pruning unused images and compacting the Hyper-V volume) largely automatically.
Solution
The PowerShell script below is designed to be run either interactively or as a service. When run non-i... |
Requirements (Installed using Scoop)
scoop install nasm dosbox
Build (Using NASM)
nasm -g tasks.asm -o tasks.com
-g enables debugging capabilities
Execute (Using DOSBox)
mount H: C:\com\parent\path
H:
tasks.com
tasks.asm
Sections are added for clarity.
[org 100h]
section .text
main:
lea si, [task_a]
... |
I am trying to create a very basic class: Line as follows:
class Line:
def __init__(self, x1, y1, x2=None, y2=None, dx=None, dy=None):
self._x1 = x1
self._y1 = y1
if dx is None:
if x2 is None:
raise ValueError("You must specify either x2 or dx. both argument are... |
Code
Problem
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return False
height = len(matrix)
width = len(matrix[0])... |
Advent of Code, Day 3 Problem Definitions
input1 = 'R995,U982,R941,U681,L40,D390,R223,U84,L549,U568,R693,D410,R779,U33,L54,D18,L201,U616,R583,D502,R307,U46,L726,D355,L62,D973,R134,U619,L952,U669,L28,U729,L622,D821,R814,D149,L713,U380,R720,U438,L112,U587,R161,U789,R959,U254,R51,U648,R259,U555,R863,U610,L33,D97,L825,D489... |
The goal of the function is to find out how to get from one angle to another angle. Two things are involved: the amount to move by and the direction (+ means turn right, - means turn left). The most the angle will have to move by is 180deg. The function is rather short. I wanted to avoid using and trig functions or pi.... |
I'm trying to "build" a few "spaceships" in my code. I'm feeling it's a good idea to enumerate all the spaceships and use that as a subscript to build and use an array that holds the spaceships' properties. After researching Stack Overflow and other places, I found a solution that works, but I'm feeling it's not very e... |
I have recently tried to get a better grip on machine learning from a point of implementation - not statistics. I've read several explanations of an implementation of a Neural Network via pseudocode and this is the result - a Toy Neural Network.
I have used several sources from medium.com and towardsdatascience.com (if... |
Advent of Code 2019: Day 3
I'm doing Advent of Code this year. Below is my attempt at day 3:
Problem
Part One
--- Day 3: Crossed Wires ---
The gravity assist was successful, and you're well on your way to the Venus refuelling station. During the rush back on Earth, the fuel management system wasn't completely instal... |
Advent of Code 2019: Day 1
I'm doing Advent of Code this year. Below is my attempt at day 1:
Problem
Part One
--- Day 1: The Tyranny of the Rocket Equation ---
Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely a... |
I have created one generic Page class for store paging information with its data.
The class look like:
public class Page<T>
where T : new()
{
private List<T> _list = new List<T>();
[JsonProperty(PropertyName = "total_count")]
public long TotalCount { get; set; }
[JsonProperty(PropertyName = "pag... |
Suppose I have a list that holds a list of column names:
columns = [
'Village Trustee V Belleville', 'Unnamed: 74', 'Unnamed: 75',
'Village President V Black Earth', 'Village Trustee V Black Earth',
'Unnamed: 78', 'Unnamed: 79', 'Village President V Blue Mounds',
'Village Trustee V Blue ... |
This program is yet to become user-friendly and is still in development, but I wanted to improve the current code.
from random import choice
from os import system
clear = lambda: system('cls') # FOR WINDOWS ONLY
words = [i.strip() for i in open('words.txt').readlines()]
# Possible stages
STAGES = [
"""
---... |
I made a Tic Tac Toe game using C. Here two players, player1 and player2, can participate and play. Please rate my code and suggest improvements.
#include<stdio.h>
#include<conio.h>
void board(char t[]);
int cheak(char T[]);
void main()
{
int i=0,n,r=100,p=1;
char TOT[9]={'1','2','3','4','5','6','7','8','9'};
char a='... |
I am very new to Kotlin and I am trying to achieve this:
I get a batch of PersonDetails to save or update
In the batch, the same PersonDetails with name is different locale can be present.
The end goal of this method is to merge the batch itself and also merge the existing entries in Database then return the updated d... |
I've been trying to create a shared example to quickly and efficiently test controllers with CRUD operations that might also be nested.
I came up with this solution that works, but I feel that can be improved.
module ApiHelper
RSpec.shared_examples "a CRUD controller" do |model:|
def self.controller_has_acti... |
I'm writing extension methods to shorten the code required to get custom Claims from an IPrincipal. I have two general forms for the bodies of these methods.
Form 1
public static long? GetFirmId(this IPrincipal principal)
{
return ((ClaimsPrincipal) principal)?.FindFirst(nameof(User.FirmId)) == null
? defau... |
Using systemd's .path unit to run a Python script whenever a httpd config file is changed. The Python script creates a backup of the config and logs the differences of the newly modified and backup file. After that it checks the syntax of the httpd config and gracefully reloads the web server service.
The Python script... |
What can make this code better?
And how could I improve this code?
Oh and what I would love is if someone has a project that is not that
challenging but I could learn a lot from it :)
import java.util.Scanner;
public class RockPaperScissors {
final static int ROCK = 1;
final static int PAPER = 2;
final... |
I was reminded by an achievement notification yesterday of this question of mine, posted nearly four and a half years ago. After reading through my own code and the review posted, I decided to re-implement it.
Thus far, I have implemented a few changes:
The function has been renamed to mapping_replace, perhaps more c... |
I wrote this snippet to allocate blocks of memory, whose sizes and number are available during initialisation. I choose to equally divide the statically allocated memory. There are some error checks before allocating a block to a pool of memory and I maintain a free list in the memory blocks. It is not thread safe at t... |
Follow-up to Partial Zilog Z80 emulator written in C++
I would say that I'm still new to the language, so I'm going to keep the beginner tag this time.
Changes:
I've implemented the suggestions from @1201ProgramAlarm and have implemented about ¼ of the instructions in the main set.
I have in general reduced code duplic... |
I'm writing a Rust library to facilitate implementing the following C API in Rust. That is, it should be possible to create a Rust-idiomatic implementation by depending on my wrapper library.
// Called first. Implementer may allocate memory here.
void init();
// For each input: start is called, then run is called repe... |
I am working on a very simple 3D vector class, which I can use to set up and access three-dimensional vectors using a wrapper around std::vector. It's not intended to be foolproof, just good enough to get by.
The main goal is to make it simple to use, explicit and easy to debug. I have often accidentally put in out-of-... |
I found it useful to execute multiple reads in parallel using a set of my extension methods for TaskFactory, which could be used as:
static async Task Main(string[] args)
{
var (r1, r2, r3, r4) = await Task.Factory.StartNew(
Read1Async, Read2Async, Read3Async, Read4Async);
async Task<int> Read1Async() ... |
I wrote a simple Python 3 program that takes data from either a file or standard input and xor encrypts or decrypts the data. By default, the output is encoded in base64, however there is a flag for disabling that --raw. It works as intended except when I am using the raw mode, in which case an extra line and some rand... |
I don't like this function. Looks too imperative.
It takes two sorted lists and returns a sorted intersection of the two lists. There is an implicit assumption that there are no duplicate elements in either list.
Please don't suggest converting (even one of) the arguments to set, or using some sort of library function.... |
Because I often have to deal with two Variants that may or may not be Null, we need a null-safe equality test, so I came up with IsDistinct which works but I have some issues with the code:
When I tried to keep it terse, the readability was harmed.
When I tried to expand the logic for readability, it still makes for s... |
Objective
To create a unique id with few characters as possible.
Language: C#
Engine Unity3D
Target : iOS && iPadOS
Scenario
I found quite a few solutions from Stack Exchange but would like to know if someone could just look at my code to review it. It is a very important module IMO
Code
/// <summary>
/// ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.