instruction stringlengths 71 95.1k |
|---|
#include <stdio.h>
#include <limits.h>
#define MAX_SIZE 5
#define FULL INT_MAX
#define EMPTY INT_MIN
int Q[MAX_SIZE]; // linear queue //
int rear = -1;
int front = 0;
// condition for empty is Qsize is zero (front > rear) //
// condition for full is rear is at last index (rear == MAX_SIZE - 1) //
... |
Problem Statement
From the National Institute of Standards and Technology's Office of Weights and Measures, one can find a handy list of all the metric prefixes:
e.g.
Purpose
Name
Symbol
Factor
Name
larger quantities or whole units
quetta
Q
$$10^{30}$$
nonillion
ronna
R
$$10^{27}$$
octillion
yotta
Y
$$10^... |
This is my code to generate a FASTA file containing multiple records with randomized DNA sequences with distinct length. I am looking for feedback on how to write this script better.
"""
Generates random fasta file.
Number of records and length of each record is given by user.
"""
from Bio import SeqIO
from Bio... |
Update: Okay, after trying to use this for a while, I think it's probably a bad idea. Please use (lambda x: x["a"] + x["b"])(df) if really necessary or use df.assign(c=lambda x: x["a"] + x["b"]) (with CoW enabled for performance reasons) which supports chaining!
I've a syntactic sugar hack to make it easier to create a... |
in my MATLAB code I describe a model for price formation with stale returns
in this framework there are 2 type of trader: informed traders who always trade in the "right direction" and noise trader who make their buy/sell decision throwing a coin with likelihood of 50% for a buy/sell order. in my work the probability o... |
I'm using WooCommerce Subscriptions and here's what I want to do:
Use free shipping for all recurring orders even if the minimum isn’t met.
Get rid of any other free shipping choices (like free priority/express) for recurring orders. Only the one free option should remain.
Make sure that the free shipping choice for t... |
This script is called every minute, but I want it to run continuously instead of making that many requests to the radio station and I think that urllib.request can be replaced with the requests module. If possible I would like also to store the title and the artist separately.
It would be great if someone can help me o... |
Implement TSP problem using best first algorithm (so it will be
backtracking, branch-and-bound, and best-first). Since you are looking
for a cycle, the start/finish city is not important. Therefore we
assume that start and finish city is always index 0.
For the bound use solution of the relaxed problem as discussed in... |
A week ago I posted this question and after reading the answers and accepting one I decided to refactor my code quite heavily. I would like to get some feedback on this newer version.
The changes
No more predicates! I'd like it to look exactly like Python's input() function.
Always return a string and let the user par... |
This is my first C++ class, implementing union find. I’ve tested the implementation very shoddily by checking that unifying two points connects them, and that works. I did a first draft in Python and translated it to C++. I use two buffers to keep track of the traversed items instead of creating a vector each time. Unf... |
A lot of the time when working in DevOps, documentation and code snippets from colleagues will be based on bash. Most of those same commands work seamlessly in PowerShell; but setting environment variables doesn't; e.g. export DEMO_CLIENT_ID="ff3b7b84-e041-4e76-993e-239930808aa7".
I've written the below function so I ... |
This is my .zprofile, it recently got nuked so I remade it. I made it clearer and better then my previous .zprofile and then I heard about this site so I want to know how can I improve this code.
# Setting PATH for Python 3.11
export PATH="/Library/Frameworks/Python.framework/Versions/3.11/bin:$PATH"
alias python=pytho... |
In the codebase I inherited, I have this function which converts a number and unit into milliseconds:
function convertToMs(duration){
const matcher = new RegExp(/-?(\d+)(ms|[smhd])/);
const matches = matcher.exec(duration);
const digit = Number(matches[1]);
const suffix = matches[2];
let milliSeconds = di... |
This is the code for Pylect, a Python terminal I worked on a while ago which also caused my Desktop to get destroyed because of bad code. I use it infrequently but I would like a review for the code since this is a bit larger project that has span multiple months so there is some unclear bad code hidden in there likely... |
For a given integer array of size n, find all possible sub arrays of size k which range from 1 to n.
Now find the common item which is also a minimum in all sub-arrays of size k, if no common item is found then use -1 and add that to the result list.
For example:
Input array : [4,3,3,4,2]
Result :
[-1,-1,3,3,2]
Expla... |
C$50 Finance is a web application built with Flask that allows users to manage their stock portfolios. It enables users to check real-time stock prices, view their portfolio values, and buy/sell stocks.
The full specification of the problem set can be found here:
C$50 Finance.
The code passes all the green checks on ch... |
I created a SDK in C for my Rust project (a key value store in Rust). It should give access to the HTTP routes in a simple manner. (I never worked with C outside of university.)
I used:
libcurl to call the HTTP endpoints from C, because it is a well known library and works on almost any system.
CMake to make it easier... |
I made IMAP(IMAPS) notifier on boost-ext/sml state machine.
There is an opinion that networking is best done on machines.
Compile in C++20. Tested on GMail server. Uses karastojko/mailio (and therefore boost+openssl)
Just checking new emails every c_RecheckInterval_minutes minutes.
Here are two key points that concern ... |
I have this repository. The idea is that the user may measure for how long the thread is preempted with given priority class/thread priority.
CommandLineParser.h:
#define COM_GITHUB_CODERODDE_WTPDMT_UTIL_COMMAND_LINE_PARSER_HPP
#include <filesystem>
#include <functional>
#include <iomanip>
#include <iostream>
#include... |
I have many Jenkins jobs looking approximately like the example below. I wanted to create reusable functions to encapsulate repetitive parts of the Jenkins Job DSL, so that I can then apply these across the job definitions.
Here are two implemented solution attempts and one additional idea (without implementation).
I'd... |
I'm developing a client-server game application in Python. Here's the scenario:
Clients connect to the server and register.
After registration, all clients see a main menu.
One client can initiate a game, selecting a number of players (x).
The selected clients should transition to an in-game state and receive new messa... |
I'm trying to implement the dynamics of Dengue transmission between mosquitoes and humans. I decided create two classes, one for the human population and another for the mosquitoes. Both are based on an abstract class. I tried to optimize the different methods of each class by vectorizing them with numpy matrices. It w... |
the game is quite simple, you have to constantly guess the letters of a hidden word, but has a limited number of wrong attempts. The word you are looking for should be a random word from Wikipedia. I would like to get a review from you.
I used libcURL and the cURLpp wrapper.
Compilation (with Cygwin): g++ -L/usr/local/... |
I’d love some critique, pointers or any improvement to my code.
My project was mainly to record a video, through a Flask Application (online), then save it and display it on the Flask Application. Will probably do it through Vimeo API or something.
It’s just a demo. I still need to remove the timer, so it records until... |
Alarm, timer and stopwatch in the style of the standard library.
Important design notes:
The accessors do not update internal state, the user is responsible to call check() or update() prior to access to ensure latest state.
The classes are not thread-safe for performance and simplicity, the user is responsible for th... |
The purpose of this code is to parse any expression as could appear in C that involves doubles or functions that involve only doubles.
I have written parsers before:
Command line calculator in C
Basic recursive descent parser in C
This is an upgraded version that uses more descriptive variable names and structures in... |
I am trying to teach myself some composability using CRTP and concepts.
I came up with this simple example and wondered, what I could/should do better there
or, if it is a reasonable starting point?
Godbolt compiler explorer link: https://godbolt.org/z/dd3xTfz44
#include <iostream>
#include <string>
#include <type_trai... |
I am doing C++ for over a year and this is my game I tried making tic-tac-toe. And it's also my first program that uses multiple source files.
main.cpp
#include"Header.h"
#include"GUI.h"
#include"UI.h"
int main()
{
int* board = new int[9] {0, 0, 0, 0, 0, 0, 0, 0, 0};
// 1 2 3
// 4 5 6
// 7 8 9
i... |
I am currently experimenting with self validating Java beans in order to avoid the creation of objects with invalid states, while keeping the validation knowledge inside the bean. The goals I have in mind are:
Avoid polluting the bean with too much validation code for readability purposes.
Make the validation process ... |
create or replace procedure upsertTrackingItemMetric(
p_template_id number,
p_jobDef varchar2,
p_metric_type varchar2,
p_metric_value varchar2
)
is
PRAGMA AUTONOMOUS_TRANSACTION;
sig_att_id number := null;
sig_grp_id number := null;
tims_id number := null;
const_error_metric_id NUMBE... |
I am trying to write the Ackermann function iterative in m and recursive in n. I got to this point where the code I provided below work for all values below Ack(5,0) but it overflows after this value. I am not sure where and I am not sure how to optimize it.
What I am trying to achieve is this:
$$Ack(m,n)=Ack(m-1,Ack(m... |
This is a follow-up question for A recursive_sum Template Function Implementation with Unwrap Level in C++, A recursive_reduce_all Template Function Implementation in C++, A recursive_reduce Template Function with Unwrap Level Implementation in C++ and A recursive_depth Function Implementation with Target Type Paramete... |
...with properly packaged/type-hinted code, automated testing, and no dependencies. Do note that this package requires Python 3.12 or later.
Only pyproject.toml and non-test .py files are included here; still, there are about 1400 LOC. For non-code files (and/or a better code-reading experience), view the project on Gi... |
I require a PRNG which:
Has repeatable results from a given state.
Is both seeded from and has a state containing a sufficiently large amount of data (somewhere in the region of 700 bits or more) to cover every possible permutation of a fairly large Fisher-Yates shuffle.
Can be run on .NET.
A few generators exist whi... |
I've got a task to implement simple event source and i did: project
Events structure
### order base
- id
- employee_id
- datetime
### order registered
- fields from order base
- client_id
- delivery_time
- merch_id
- merch_price
### order canceled
- fields from order base
- reason
### other orders have the same ... |
I have a table representing a class hierarchy using the TPH model.
Some of those sub classes have navigation properties (collections and/or references).
I'm trying to preload them as I know I will need them later in the process.
I'm also trying to not have to manually write the casting and loading of all those properti... |
This was back when I was new to coding on Scratch (as in the case of coding projects entirely from scratch) around 7-8 months ago with my Cookie Clicker in Scratch project that I made pretty much entirely myself. Now, what seemed to be a huge barrier for me was summing values so I could add a Buy 100 function for the i... |
I’m using mySQL to create and adjacency list model type of table. I have only one level, that is a parent with children, like this:
TABLE article (article_id, title, parent_article_id)
Here’s a sample data
article_id title parent_article_id
-------------------------------------
45 abc null
61 m... |
First, I have to say that this game lacks 5 features that I don't care:
Flags
Chording
Timer
Actual mouse movement
Good graphics
When starting the program, the player is meeted with a "Choose difficulty" menu. They will move around by pressing ASWD, choose an option by pressing enter/space, and quit at anytime by pre... |
This is my first ever program in Rust. I've made it using only the book, the reference, and any documentation about the crates/functions I was using on the official rust lang website.
I have the feeling this could be cleaned up a lot. I'm looking for suggestions.
extern crate rand;
extern crate device_query;
use std::... |
I am trying to write an HTTP/1.0 (RFC 1945) parser in C, so I started with the Request-Line. Ideally, the parser should return one of the three:
The request is valid.
The request is malformed, but appended data could make it valid.
The request is malformed and no appended data can make it valid.
The idea is to know w... |
Recently I had an interview question about extracting records that matched certain criteria from a 2D List of strings. The premise was a CSV file was parsed into a List<List<string>>, and I need to filter them based on a record type (only keep "SALE" and "REFUND") and sort them by the date and time found in the record.... |
This is a French Republican Calendar / Gregorian Calendar converter I've written; it returns an accurate date for all the dates I've tested (mostly dates in the present age, although it also lines up with historical French Republican Dates, give or take a day- depending on whether or not they use the Romme Rule.
I'm wo... |
While implementing a proprietary networking protocol, I found myself instantiating buffers of different sizes all the time, reading from a std::io::Reader into it and then parsing its content into a primitive number type.
To make working with these readers more comfortable, I implemented the crate rw-exact-ext:
use std... |
Recently I wrote my own implementation of a utility for recursive output of the directories' contents, kind of similar to the ls Linux utility with the -Ro flags. As a training, I wrote it in C.
I would love to hear your feedback on possible optimizations, better error handling, flaws in implementation, or the code in ... |
I implemented a CSV Parser with Separation of concerns and SOLID principles in mind.
Does that code match the principles?
Here a sample data (CSV):
Participant;Eagerness;Education;Stability;Total
"John Doe";6.4;"G";1.3;9.0
"John Smith";2.9;"X";1.5;;
Main file:
<?php
require __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . ... |
I want to create a String from the part of the vector.
My code:
fn main() {
let v = vec!['a', 'b', 'c', 'd'];
let mut res = String::new(); // expect to have "cd"
let start_pos: usize = 2;
for i in start_pos..v.len() {
res.push(v[i]);
}
println!("{}", res); // "cd"
}
Is it possible to d... |
I try to program a small app to track my cost spendings. As state management I use Cubit. As I am a flutter beginner, I wanted to verify if I implemented it correctly.
The UI consists of 2 screens: 1 for the cost entry, 1 for the listing of the entered expenses. Concerning architecture, I followed the cubit guidelines:... |
I wanted to write a utility method for learning purposes to determine if a given date (year, month and day) falls within EU summer time or not, without using any of the Java library methods. Is here something (logically) to simplify or is it an antipattern?
import java.util.Arrays;
/**
* Die mitteleuropäische Sommerz... |
I'm looking for a code review of my custom memory allocation library (written for educational purposes), which includes malloc(), calloc(), realloc(), and free() functions.
Review Goals:
Does the code ensure that the pointers returned by *alloc() are properly aligned for all types, as required by C standards, to avoid... |
So I am working on recreating a hidden minigame from PvZ Brutal Mode EX+/Unnamed Mod in Scratch for fun here. While I am making some considerable progress on it, I'm having trouble simplifying the code for choosing the plants you want to use before going into the minigame.
What I am doing right now is using a list of a... |
For my Bachelor thesis, I made a PicoBlaze Assembler and Emulator in JavaScript. I've discussed it on many Internet forums, and quite a few people have complained that the core of my assembler is hard-to-follow due to lots of if-branchings. So, what are some other ways of making the core of the assembler? Do the cores ... |
messy json file is parsed and should output the N highest
record IDs & scores by score in descending order, highest score first.
the code works but i wonder if there is better readability, help me refactor it.
The function takes 2 args - the data file path and num of scores to return:
python myprogram.py highest score_... |
I have the following classes:
public record LocalCcmProgram : LocalCcmSoftwareBase, IInstallableProgram<LocalCcmProgram>, ICacheInfoProvider
{
// Unimportant properties and methods
public LocalCcmProgram Install()
{
_logger.Debug("Request to install {type} {name}", GetType(), Name);
Valida... |
I'd like to show you two versions of my two functions that support my logging tools. Their purpose is to log a different message (here abort) when an error occured and it matches the filter specified by the user. By default the error message is logged.
Version-1 of this code uses the classical if to handle the optional... |
The Verilog module describes a ROM memory. An initialization file is needed for the INIT_FILE parameter.
Below are Makefile, gtkwave.tcl to launch gtkwave, launch_tb.py (please use it to start simulation) and rom_tb.py as well as rom.sv.
Refer also to the cocotb home page.
rom.sv
module rom #
(
parameter integer DATA... |
"Wordle50" is a command-line-based adaptation of the popular Wordle daily word game. In this word-guessing game, players aim to decipher a randomly selected word with lengths varying from 5 to 8 characters, drawn from a predefined word list (text files). They are granted one extra guess compared to the length of the ta... |
I wrote my first code in Java and I need constructive criticism and code review.
This is an implementation of the well-known "2048" sliding-blocks game.
package com.example.simple2048game;
import static javafx.scene.text.Font.font;
public class GameBoard {
static double PANE_SIZE = 100 * GameMatrix.getInstance(... |
We were asked to improve the merge sort algorithm by introducing insertion sort to the code. We have been tasked with doing this by utilising a "levels" logic. Here is the exact description of the mentioned task:
This parameter will be incremented by 1 inside the merge_sort before the two recursive calls. It will keep... |
I wrote a solver for the snake cube puzzle. The solver can be easily adapted to arbitrary snakes.
Since the program takes only a few seconds to run, I didn't care to optimize for speed, instead I strived for clarity and simplicity.
Is it possible to avoid the repeated Dir. in the definition of afterTurn? If it weren't ... |
This is a follow-up question for A recursive_reduce Template Function with Unwrap Level Implementation in C++ and A recursive_reduce_string Template Function Implementation in C++. Considering the issue mentioned in G. Sliepen's answer, some modifications are made here:
It is not generic enough. Even if you only want... |
This is a huge project that I have worked on for the past few months, it contains 16 scripts, one of the scripts is used to analyze the other scripts. There are 111004 characters in all the script files, this exceeds the character limit of 65536 characters for a single post, and this figure doesn't include all the js... |
I am refactoring an old project, made in Nodejs with Express, applying the MVC pattern, today it is a fairly simple project: handling of the FCM and Remote Config tools from Firebase.
Would it be helpful, or is it good practice, to add the services file to work together with the controller?
The FCM part would look like... |
This question is part of a series of posts about my massive Tic Tac Toe game with AI players, the previous question is: GUI Tic-Tac-Toe game with six AI players - part 1: the UI. This question includes all the code necessary to stylize the GUI.
The final part is: GUI Tic-Tac-Toe game with AI, part 3: control and logic
... |
After watching Stroustrup's presentation on performance comparison between vectors and linked lists (https://youtu.be/YQs6IC-vgmo?si=9r5wXqnwkmN29xqn), I've decided it would be a good problem to get a hang of C. To that end, I've profiled how long gthe removal of all elements from the lists by sampling random indices t... |
I've got this idea (based on experience) that logging plain messages isn't just enough to monitor an application so I built an abstraction layer on top of the built-in logging package.
NOTE: I have refactored virtually the entire previous code as I wasn't happy with it at all.
Basiacally what it does, is to automatic... |
This is the last part of the series of posts about my GUI Tic Tac Toe game, the previous two question are GUI Tic-Tac-Toe game with six AI players - part 1: the UI and GUI Tic-Tac-Toe game with six AI players - part 2: the styling.
I have created a GitHub repository for this project, there you can find everything you... |
I have a Web API and for some requests we are sending requests to a third party API that requires request authentication. It's a simple bearer token, which I'd like to reuse across requests, because the authentication process can take up to two seconds roughly, and obviously I don't want to flood the external service. ... |
I'm a newbie python developer who accidentally studied the concept of
Abstract classes
and I found it pretty much helpful to implement due to the SOLID principles.
At the very moment of testing and learning the concept, I found out that using a abstract class also as an mix-in class would be a great Idea, so I decided ... |
I wrote a dynamic Gateway (there were other collaborators, but the version below is 90% my code). What makes it dynamic is the fact that it builds routes in runtime from Swagger docs it fetches from other Eureka applications. So the basic flow is:
It looks around and finds other Eureka applications
It fetches docs fro... |
In short, the algorithm must find the longest sequence that joins together common sequences from two lists (a more formal specification is given in the code's header).
The lists are assumed to contain the same elements without duplicates.
Example: from [1,2,3,4,5,6] and [1,4,5,2,6,3] the algorithm should return [1,4,5,... |
I recently finished implementing a radix sort for objects where either one of the keys is numeric, or can be expressed numerically via an iteratee.
type KeysCorrespondingToValueType<T, V> = {
[K in keyof T]-?: T[K] extends V ? K : never;
}[keyof T];
type Iteratee<T, V> = KeysCorrespondingToValueType<T, V> | ((item: ... |
I want to learn the proper way to gracefully shutdown a http.Server{}. Some answers I found would not handle ctrl-c signals. Others would handle it, but it would lock on the channel read if the server closed itself.
To handle the above situations, I came up with this template. I'm not very experienced when system signa... |
I'm working on an electro-thermal simulation with variable parameters.
Model require the calculation of all the electrical and thermal quantities at each time step, between a starting and ending time. Parameters change at each time step according to instantaneous electrical or thermal quantities values.
Current impleme... |
I am running the following code to conduct a simulation. I have a dataset of around 100K observations. The simulation does the following:
It randomly assign 10 "friends" to each observation
Take the average of the variable normalized_score of the 10 friends
Run a regression where the left hand side variable is the nor... |
Script to prevent nested root shells shall do exactly as said, plus some niceties like an error message when someone runs it with some argument/option.
#!/bin/sh
set -o nounset; set -o errexit
error()
{
printf >&2 '%b\n' "$@"
exit 1
}
is_root()
{
[ "$(id -u)" -eq 0 ]
}
start_root_shell()
{
exec sud... |
I think many days ago, I randomly got introduced to cucumber developement, And it seemed like a conventional and interesting principle of software development.
At this very time, I'm concentrating on creating a Linux based terminal software.
For this sprint, I decided to use a principle of cucumber development which is... |
Filter is a C program that allows you to apply filters to BMP images.
Usage:
Usage: filter [OPTIONS] <infile> <outfile>
Review Goals:
General coding comments, style, potential undefined behavior, et cetera.
How can I eliminate the use of the non-standard packed attribute from the code?
Code:
bmp.h:
// BMP-related data... |
I saw few similar solutions, but they all relied on C-style arrays and str utils, so I thought I would write a higher level C++ only implementation with a vector as an exercise. I have not implemented all the functions yet but wanted to first check if this looks to be on the right path or if there are some major issues... |
I wrote my first code in Rust and decided to recall the buddy algorithm, which I suggested at work for our embedded software.
I hope you can give me some advise on things like:
How to make it safe (not use unsafe-keyword), while keeping in mind that the purpose of this algorithm is to managing someone static heap in s... |
Here's a code challenge I got. (I could not solve the challenge, I ran out of time. I rephrased the challenge language and I am trying the challenge again for personal growth & computer science knowledge)
Consider an array A of N integers.
You can delete zero or more of its elements.
Then take the remaining elements a... |
I am designing code for OrderBook based in C++, based on STL library. Note that there is a related question here, however it is more simple - it does not support deletion of orders, and I intend to add deletion as well as modification.
The prices can be floats here, and I have modeled the orderbook as a map of key = pr... |
I'm developing a custom date input format to enhance user experience in scenarios where birthdays and expiration dates are inputted. Traditional date fields and date picker libraries often fall short in offering intuitive user interactions. My script has been designed to:
Enforce a month value range from 01 to 12.
Ens... |
I made a game in Python where you play Pong against an AI. As I am quite new to pygame, I would be grateful to hear any possible improvements.
This is my code:
import random
import pygame
from pygame.locals import (
K_UP, K_DOWN,
K_w, K_s,
QUIT
)
BG_COLOR = (255,) * 3
FG_COLOR = (0,) * 3
SCREEN_WIDTH = ... |
Another shared_ptr implementation. My main idea was to write it in a way you could do:
MySharedPtr derivedPt(new derived());
MySharedPtr<base> basePt(move(derivedPt));
basePt.reset();
where the derived class is destroyed properly without a virtual destructor. I did not find a similar one so thought to try and write on... |
I want to compare the procedure time for each number of process. I made 5000000 numbers in input.txt in random order. I read it and do bucket sorting with multiprocessing (let the number of buckets = number of process) and I record the time spending to do bucket sorting. I am wondering if my code is doing multiprocessi... |
This is a follow up to my previous implementation:
The input is of the format
ACTION [OID [SYMBOL SIDE QTY PX]]
ACTION: single character value with the following definitions
O - place order, requires OID, SYMBOL, SIDE, QTY, PX
X - cancel order, requires OID
P - print sorted book (see example below)... |
Several days ago, a question on this topic was posted to SO. The problem turned out to be the OP's test cases did not reveal a deficiency in the code. This challenge caught my attention. Writing the following has provided entertainment for a number of rainy hours.
I've had a look at several "Review" postings (looking f... |
Task:
An ATM dispenses banknotes with the following values/denominations: {5, 30, 35, 40, 150, 200}. The user should be able to repeatedly enter an amount divisible by 5 without leaving a remainder. The denomination of banknotes with the smallest possible number of notes should be issued that corresponds to the amount.... |
I want to create a very basic physics engine in SFML. I also want to be able to control objects using Dear ImGui. So I created this basic foundation. My main problem with it is how I handle rendering the GUI, because I couldn't find another way to implement it, either just drawing an object, or drawing object and a GUI... |
Very new in Haskell, as a first easy program I went for an old algorithm of mine to approximate pi by counting points within a circle. The snippet below is what I could get working. I had quite an issue with types (you will notice very extensive use of fromIntegral) and would also like to know about performance, since ... |
My Download habit is notorious and my download folder end up piled up with random downloads, I created a python script to maintain my download folder in windows
upon running the script it moves files with appropriate extension into its designated folder
.mp4 files will be moved to video folder
more extension and fold... |
For the purpose of this discussion, I have the following function:
def countSetBits(num):
cnt = 0
while num:
cnt += num & 0b1
num >>= 1
return cnt
It counts the number of set bits in a given num's binary representation. For example, take 10 whose binary rep is 0b1010 -- countSetBits(10) should equal 2.
I... |
I am trying to implement a simple malloc and free. The buffer is a char array.
Each chunk's address is calculated using the size of the previous chunk.
#define BUFF_SZ 64
typedef struct {
int sz;
int used;
}blk_hdr;
char buff[BUFF_SZ];
blk_hdr *start,*end;
void init()
{
start = buff;
start->sz = BUF... |
How to improve this code, how to make it accessible to get user feedback?
This is a minimal clock time validation app. There is a clock face and the user is asked to validate the time the clock hands show. It is written in Python with Turtle and Tkinter. This is the first app I made. I tried to compose the code so that... |
Related to this question and this answer, I would like to have a second review from you on a modified version.
The problem I tried to solve
Some kind of "Minimum count of numbers required from given array to represent S" (see here).
Algorithms that I used
Some kind of dynamic programming array (see here), but I don't k... |
So I was tasked with providing a function that returns how many exact occurrences of attribute word appear in attribute text. The goal is for the function to be as fast as possible, and I managed to get down to 0.21 seconds. When using python -m pytest file.py. Here is what I got:
def count_occurrences_in_text(word, te... |
I have written a Python function called merge_arrays which takes two lists and returns the new list merge without duplicate.
The function works as expected, but my code very complicated, and I'm looking for ways to optimize it.
Below is my current implementation:
def update_if_new(d, results, element):
if element ... |
Array-List-int.h
#ifndef ARRAY_LIST_INT
#define ARRAY_LIST_INT
#include <stddef.h>
#include <stdbool.h>
////////////////////////////////////////////////////////////////////////////////
// AL_int x; creates an object handler called 'x' for an array list.
// The creation of an object handler for an array list must be ... |
Looking for code reviews of these two encryption methods. And if GCM is better or worse than CBC with HMAC.
AES-GCM
public static async Task<byte[]> EncryptAsyncV2(byte[] plainText, byte[] password, byte[] nonce, byte[] salt)
{
try
{
if (plainText == null)
throw new Argum... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.