instruction stringlengths 71 95.1k |
|---|
I frequently encounter the need for creating services that concurrently process messages from Redis queues. So I decided to share the knowledge I learned and help others easily bootstrap such a service. I would like a second opinion from code reviews of the library. Please do contribute if you feel like improving it!
G... |
I'd offer a couple of iterator accesses to the class member, both constant and non-constant. I came to the following solution, but it seems to me far more verbose than needed. I'd like somehow to merge the two function members get_c, get_m in some fashion, but I'm not sure if possible.
#include <iostream>
#include <vec... |
I am getting the probability of a string being similar to another string in Python using fuzzywuzzy lib.
Currently, I am doing this using a for loop and the search is time consuming.
Below is working code :
from fuzzywuzzy import fuzz
with open('all_nut_data.csv', newline='') as csvfile:
spamwriter = csv.DictReader... |
Any one suggest me right way to write mapping more then one table using spring-boot (jpa), i was done it, but its required more time to extract result,
Following are the Mapping of Pojo:
First:-
@Entity
@Table(name="DIM_CORPORATE_AND_SERVICE_ATTRIBUTE_MAPPING")
public class ServiceAttributeMapping {
@Id
@Gene... |
I have the following dictionary:
results_dict = {'Current model': {'Recall': 0.77,
'Precision': 0.1,
'F1_score': 0.18,
'Frauds': 94},
'New model': {'Recall': 0.96,
'Precision': 0.17,
'F1_score': 0.29,
'Frauds': 149}}
What I want is to make a comparison for each metric between the two models, and in case t... |
Problem statement (online source)
Given a digit string, return all possible letter combinations that the
number could represent.
A mapping of digit to letters (just like on the telephone buttons) is
given below.
Input: Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Althou... |
I've just rewritten this code (a simple gravitational restricted n-body simulation) to display using canvas, rather than SVG. The reason being that I'd like to be able to run it with many thousands of particles.
To my surprise I didn't see any sizable performance improvement after making the conversion. I'm wondering i... |
Heap Sort
A Binary Heap is a Complete Binary Tree where the items are stored in a special order such that the value in a parent node is greater or smaller than the two values in the children nodes.
Heap Sort is a comparison-based sorting algorithm — somewhat similar to selection sort — which divides a list into sorted... |
I have a Python function w/ specified functionality, and two proposed approaches - which do you prefer, and why? (performance, simplicity, clarity, etc) (both use import random)
PROBLEM: Need a plain Python function that accepts an arbitrary number of iterables (tuples, lists, dictionaries), and returns them shuffled ... |
I recently attempted a coding problem, but my solution was not well received during the interview (modified slightly to reduce Google-ability).
Suppose a child has several Lego blocks, and wants to build a toy from them. Every piece has a size, and when two pieces are combined a new piece is created whose size is the ... |
I'm working on writing a Chess Logic Library in JavaScript for learning purposes and was wondering how good these two slightly different implementations of a BitBoard are.
The first stores the board as a 64 length string of zeros and ones and the second uses an Array containing 8 numbers each representing a byte. The b... |
Given a tuple of elements, in elementTupleParam and the number in each combination r, we compute all the possible combinations of r elements, in a list of tuples. This is a recursive implementation.
One "challenge" is the inputs r, n, elementTuple, and the list holding the results, combinationList, are shared for all ... |
https://leetcode.com/problems/spiral-matrix-ii/
Please review for performance, how can this code run faster
Given a positive integer n, generate a square matrix filled with
elements from 1 to n^2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
using Microsoft.VisualStudio.Te... |
I am trying to draw 2d patterns onto grids of different geometric units. I have a small example for a halfmoon pattern on the grid below. In the future, I will add different kinds of movement (eg. fullmoon or circular motion). Eventually there will be different base geometric units as well.
I wonder if there's a way to... |
I wrote some code that iterates over some queries and counts the number of times each query appears in a vector of words. My first iteration iterated through all the words in the vector for each query which is wasteful. I improved it and come up with this.
unordered_map<string, int> matchingStrings(vector<string>& str... |
https://leetcode.com/problems/rotting-oranges/
Please review for coding style in 40 minutes job interview.
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell; the value 1 representing a
fresh orange; the value 2 representing a rotten orange. Every minute,
any fresh oran... |
I have a dictionary that looks like this
masterdict = {'a':['b','c','d','e'],
'b':['c','d','e'],
'c':['d','e'],
'd':['e']
'e':[]}
where the list has all the values that are 'compatible' with the key and vice-versa. Since the dictionary is non-redundant, repeated compatiblities are n... |
Here's my type:
data Tree a = Empty | Node a (Tree a) (Tree a)
Here's the instance declaration for Monoid:
instance (Monoid a) => Monoid (Tree a) where
mempty = Empty
mappend Empty Empty = Empty
mappend Empty t = t
mappend t Empty = t
mappend (Node val ta tb) (Node val' ta' tb') = (Node (mappend va... |
Brevity is for kings as it requires context and context is for kings. Me.
GitHub and NuGet
How many times you have been writing something like this passing those tedious logger/token parameters?
interface IMyService
{
void Method1(…, ILogger logger, CancellationToken token);
void Method2(…, ILogger logger, Canc... |
Recently I created a small project: 'media library' (which allow to search, sort and filter items) and I will be glad if some give me constructive feedback about my code. The starting point is Angular-CLI, and the full code with starting page is HERE. And below is 'main' model used in app
Here are all files which I ad... |
Its a conference service code from controller to DAO for conference application.
it contains controller, conference service, dao and entity class, I am seeking for any improvement or code review comments for this.
/**
* This class is responsible for representing as a conference features, this will be the entry po... |
I did this test for a job and the feedback was:
"while many were added to test private methods, they did not do anything to ensure the public interface worked correctly, edge cases were missed"
But I thought I covered the public interface and edge cases.
Any other improvements I could have made would be appreciated to... |
I'm creating a download manager in C# (in combination with Unity 2019.1.8, running the .NET 4.x equivalent (MONO) scripting back end). To accomplish this I decided to start using interfaces and class inheritance through an (abstract) base class. As those are things I have never used before, To get to know how they work... |
I have made an Android app called RunTracker - https://github.com/michaelnares/runtracker/tree/master/app. The intended functionality is that the app saves runs to the local filesystem, shows your current location and current run, and has a clickable list of runs. I feel that the existing code can be improved, but I'... |
Here is an async task queue implementation. The idea is to reuse node.js standard library as much as possible.
const { Readable, Writable } = require('stream');
const delay = (ms) =>
new Promise((resolve) => {
setTimeout(resolve, ms)
})
const task = (message) => {
console.log(`${message} started`)
return... |
lastbudget and lastactual are both Lists
These lists populate 2 columns in an infragistics ultragrid
PrevFY
Actual_c
So the grid has defined datasource already. These 2 columns I added programmaticly onto the grid which has a datasource.
(dgvBudget is the name of the ultragrid)
int rowIndex = dgvBudget.Rows.Count;
... |
I have multiple repositories that contain userId, paidDate and amount attributes like Bills(userId, paidDate, amount) Shoppings(userId, paidDate, amount) etc. I want to get sum of amounts and group them by userId and get something like this {user1: {amount1, amount2, amount3 ..}, user2: {amount4, ..}}
I created a expen... |
I am solving a problem of increasing the ROI of a retinal image using the below algorithm-
First, the set of pixels of the exterior border of the ROI is determined, i.e., pixels that are outside the ROI and are neighbors (using four-neighbourhood) to pixels inside it. Then, each pixel value of this set is replaced wit... |
How can my solution be improved / optimized?
explaination of db models :
thinkpad is a equipment of laptop subcategory.and laptop subcategory has a category called electronics.
now laptop can have many attributes like processor,ram,color,screen_size.
Question :
Find out all the equipments with theirequipment detail ,... |
I'n written this small file encryption module to work on my skills with the os module. It's my very first time using it to navigate files and file structures, so I'm sure some things can be improved. I used the following file structure to ensure it works with multiple directories:
File Structure
.
├── files
│ ├── fil... |
Update from Digitizing paper label system with Python
I have implemented a username and password log in and main application to be used after successful log in.
I am ready for some more feedback.
My main troubles is error handling. For example log in screen, I'll need to implement statement to show if user does not exi... |
Simplified the actual problem to focus on comparing/removing performance.
Given a set S with n elements , find the most optimal way to compare each element to all others until a condition is met that decides if and which item to remove. I experience long runtimes when n is high (e.g. n=3000 has a runtime of 2500ms on a... |
I am using EdgeJS in my application. The application is used to run a user-provided javascript program from C#. Because we allow execution of user scripts some sandboxing is required. I am using vm2 for sandboxing. Is it correct to add custom logic by overriding a function exposed by NodeJS library?
Here is the C# prog... |
I'm learning C so I thought to apply it to miniproject on reddit. The smorse function takes in a string and spits out some morse code. It works if you supply the function with only lowercase letters. I feel awkward making a first for loop in my smorse function to calculate the size of buffer I need to malloc and then m... |
2 years ago I did this:
SmallVector - std::vector like container on the stack
now, 2 years later, I am reinventing the wheel again, this time with fully constexpr SmallVector.
This time, because I decided it will have only constexpr functions, I decided to remove all non POD types.
#ifndef MY_SMALL_VECTOR_H_
#define MY... |
I have created my own wrapping framework for the COM interfaces exposed via Microsoft.Office.Interop.
MIRRORING WRAPPERS
The first purpose is to be able to unit test the rest of my applications, and also to be able to intuitively log some of the calls.
The wrapping is achieved through 2 layers of interfaces: the first... |
This is my attempt to write a numpy-optimized version of a nearest centroid classifier to classify some images from the MNIST data set of handwritten digits. I am somewhat new to numpy and was surprised by how succinctly this code could be written with the help of broadcasting and vectorized operations, but was wonderi... |
I'm building an example REST API in PHP in my local environment to learn how they work. The starting point was an online tutorial. The example is working fine; however, I have a hunch that there is room for improvement in the logic that handles the endpoints which is stored in a script called RestController.php.
Curr... |
Good day, it's my first time doing something like this so I wanted to solve some of the challenges on project Euler, however I reached a block on my code, even before I submitted I was aware that I would be unable to compile within time limits for numbers well beyond the million or close to a million, still went along ... |
Coursera has a course for beginning Machine Learning and the code is written in Octave. This is the beginning of a solution to the week 3 exercises but written in python. Instead of a terminal app I'm also trying to learn Pyside2. The actual functionality of the program may seem silly but I hope that some of the thing... |
This is an interesting example from G.Lanaro's book, Python High Performance. The program is a simple simulator which describes movement of particles based on their positions and angular velocities (x, y, and ang_v attributes of a Particle class). The bottleneck of the program is the evolve method which is initially im... |
First time on this exchange, so giving this a title was already a challenge.
So let's start at the beginning. This kind professor Güneş Erdoğan has published an CLP (Container Loading Problem) solver. His solution is made in a spreadsheet so it is VBA for Applications.
I have manually converted his code to a PHP script... |
Here's how I'd usually center align an item with absolute positioning:
img {
width: 100%;
height: auto;
}
.cat {
position: relative;
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 9999;
background: #fff;
padding: 12px;
}
a,
a:visited,
a:hover,
a:focus {
c... |
My code is working correctly, but is resulting in a "Assignment branch condition too high" warning with a score of 12.08 on CodeBeat.
Codebeat is an automated code review utility that helps developers write clean code. I have been using it lately in order to monitor the quality of my code since clean code is being a n... |
I have been using and developing a simple ORM and query builder library that I have found useful in it's practical application. I am pretty sure there are improvements to be made, and I welcome any suggestion you might have to improve this.
the full code is on github:
https://github.com/rmalchow/dbutils
the two parts a... |
I've been learning C# for a few months now, and I've done some basic things in java last year. I made a solution for the problem the title states, this is the task description.
Task description
A DNA sequence can be represented as a string consisting of the
letters A, C, G and T, which correspond to the types of su... |
What's better - to leave the IF block blank to do nothing, or to add a statement that basically does nothing (each link already has a href attribute)?
export function fixRelativeLinksOutsideOfEpub(dom): void {
const content = dom.window.document.querySelectorAll('a');
content.forEach((element: HTMLElement) => {... |
Recently I was studying about the benefits and uses of std::optional in C++17 (Bartek's Blog) and there I saw a line that said "std::optional can be used for Lazy Loading of Resources" . Upon digging a little bit, I saw that C++ does not have native support for Lazy evaluation. So I just gave it a try and wrote the fol... |
As we know, using PDO and prepared statements, binding a table or column using bindParam is not possible. So for this, I've figured out to use function parameters to do it by replacing the column names with the parameters, as shown in the example bellow.
function search($filter,$input,$type,$order,$sort,$limit){
$s... |
I have been using similar piece of code since a while. I have read some issues regarding treating mapped memory as a string. I am not sure about that though, so I just use strndup(3) to avoid it anyway.
It's often said to use fopen, fwrite and all those f* functions over read(2), write(2) etc. The reason being, these f... |
let generatorButton = document.getElementById("generator");
generatorButton.addEventListener("click", () => {
let passwordLength = 16;
let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_";
let password = "";
for (i = 0;i < passwordLength;i++){
passwor... |
I have a custom system for data validation; it handles anything from method parameters, return values, objects, etc. The core of this system is IValidationRule and its generic twin. There is a base class for actual implementations of validation rules (things like string length, database entity exists,...).
Data can hav... |
Most quicksort examples online use C-style arrays and indexes. I have written below quicksort implementation with STL style iterators. It looks fine to me, but I feel like I may be making more than necessary copies of iterators. I am open for any suggestions/improvements:
#include <iostream>
#include <vector>
#include ... |
Problem Statement
Given a hexadecimal string (hascii) and its binary specification (a list of byte field names, their offsets, and byte lengths), design classes to parse all byte-fields, cast bytes into suitable types for storage, and allow the user to write to a byte-field. For this purpose, I've created a simple bina... |
The idea is to init garbage heap in the beginning of main, use gmalloc, gcalloc and grealloc wrappers and free all allocated memory in the end of main. It helps to avoid memory leaks when writing programs for ejudge systems. Would like to hear general feedback on the idea and advices on how to improve the code (beginne... |
I want to be able to list every Transaction associated with a Client in date order.
Transaction has 2 sub-types: PaymentTransaction and ChargeTransaction.
The key difference between them is:
PaymentTransaction should be associated directly with a Client.
ChargeTransaction is associated with a Proposal, which in turn... |
Here's my android splash screen. I am trying to figure out a better way to write it. It just moves the logo up to the center of the screen. It's my third time creating a splash screen for an android app. I am just trying to figure out the best way to write more optimized code.
import androidx.appcompat.app.AppCompatAc... |
I've a function to split text on punctuation and leave the rest of the string (including whitespace in other items of the list):
import unicodedata
def split_on_punc(text):
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if is_punctua... |
My current code implementing a depth-first search works well for puzzle 1. But my code is too slow; I think I use too many loops and I am not sure I am using the right data structure. So I have a problem in puzzle 3,4,5. Please help me to make my code run faster.
Description:
The crossword file begins with a grid showi... |
This function takes in a string and a fixed list of vocab:
splits a string into words by spaces
for each word, check in the dictionary/vocab and find the longest matching substrings, if none matching use the [UNK] word
if a word is longer than a predefined length, it'll also become [UNK]
Code:
def tokenize(text, voca... |
I'm writing a utility method which pipes given ResponseSpec's body and gives to the caller a change to read it.
static <R> Mono<R> pipeBodyAndApply(
final WebClient.ResponseSpec spec,
final ExecutorService executor,
final Function<? super ReadableByteChannel, ? extends R> function) {
return ... |
I am writing a small program which reads some JSON files, passes the content to an API, then saves the response in some more JSON files. A pretty simple task, and the code works fine, but I have been away from node for a few years and wanted to make sure I'm using all this new async stuff right! Any comments welcome.
N... |
I have a class Installment and a method executeTransaction. The field totalBalance represents the difference between total due and total paid. Inside method executeTransaction the installment object is modified using setters. And after every setter the updateTotalBalance is called.
public class Installment {
priv... |
As a component of some trading software, I wrote function parse_ticks(), as part of an Exchange class that models the Bitcoin derivatives exchange BitMEX.
The purpose of parse_ticks() is to convert the previous minutes stored tick data (a list of individual trades, obtained by calling all_ticks = self.ws.get_ticks()) i... |
I am developing an Angular application who also consumes an external REST API. I am also trying the OpenAPI generator using a TypeScript template.
The OK path is the following:
call a method that requires a username + password and get a token
set the token on a configuration object
update the generated instance API c... |
This code relies on Python3.7.4
I'm learning Heapsort in python 3. Please show me the errors in my code. Runs on my computer but tell me if Python rules or not.
class Heap:
'''constructor'''
def __init__(self,lis):
self.lis=lis
self.a=[]
def heapify(self,i):
self.r=(i-1)//2 #To get t... |
I was successful in solving a challenge in codility, but my solution failed performance tests. How can I improve my solution?
Challenge:
Integers K, M and a non-empty array A consisting of N integers, not
bigger than M, are given.
The leader of the array is a value that occurs in more than half of
the elements of ... |
Implemented the quick sort algorithm in python, It was just for learning it, now I want to port it to C.
Thoughts on the quality of my python implementation?
from random import randint, shuffle
def swap(array, a, b):
array[a], array[b] = array[b], array[a]
def quick_sort(array, start=0, end=None):
if end is ... |
Experimenting with operator overloading for the first time. Based on my reading, it appears to be a bit of a minefield.
Have I fallen into any traps?
namespace Units
{
class Degree; // Forward declare Degree so it can be passed by reference into Radian.
/// \class Radian
/// Encapsulates a double, and used... |
First of all, here is an overview of my application. I want to create a multiple-choice app, on android, using data stored on a remote MySQL database. The DB has 100 questions that will appear in random order.
My php script returns a JSON array with the following results
[
{
"id": 1,
"Question": " blahblahbla... |
https://leetcode.com/problems/critical-connections-in-a-network/
Please review for memory and runtime performance.
There are n servers numbered from 0 to n-1 connected by undirected
server-to-server connections forming a network where connections[i] =
[a, b] represents a connection between servers a and b. Any ser... |
I wrote a quick-select filter in C on Wednesday. (The code is below.)
It is a filter in the UNIX tradition:
It reads from standard input k, the rank of the integer to select, n, the number of elements, and then n integers.
It outputs the kth highest integer.
(A perhaps better design would take k as an argument—but a ... |
A few days ago I saw a nice video on YouTube with prof Thorsten Altenkirch about recursion and the Tower of Hanoi puzzle. Today I tried to reproduce the code from the video and came to this:
A = "A"
B = "B"
C = "C"
def move_one(src, dst):
print("Move piece from {} to {}.".format(src,dst))
def move_multiple(n, src... |
I'm working on a personal project to get better with C#, and as part of that I have a zip file with 20 or so images saved inside. I want to load those images out of the zip file and display them in my WPF app. I have it working, but I don't know if what I have is the best way to go about this. The goal is to load the i... |
I have this script to format var_export's result string. The information in the output is good, but I need know if the code performance is good or if it can be improved.
https://wtools.io/php-sandbox/biDk
<?php
#Variable:
$Test = [];
$Test['Check1'] = null;
$Test['Check2'] ... |
I have a number of async calls that get chained conditionally based on the previous data dependency. I.e. perform call A -> if the result is defined/not an error execute a side effect, if not perform another call.
I originally started with nested subscribes but I was told that is not a good practice. Next I moved to r... |
I'm writting this poker hand evaluator and it's really coming along. But, as you can see I repeat myself many times and I would love to know what's your thought process when you're repeating yourself? Other than this, it's not finished. I still need to account for high cards etc. But you get the jist of it. I'm really ... |
I just finished this command-line implementation of the Mastermind board game that allows two players to play against each other. I'm fairly new to Ruby, but I think I did a decent job with this. However, I'm sure there are some things I could've done better, so please let me know if there are.
class Codebreaker
attr... |
I am trying to solve this LeetCode question:
Given a non-empty string s and a dictionary wordDict containing a list
of non-empty words, add spaces in s to construct a sentence where each
word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multipl... |
Simulate a tic-tac-toe game
Requirements
A player is picked at random as a first player.
The two players plays tic tac toe game.
The game ends when the board is full or either one of the player wins.
Return the board status and result after end of the game.
Player Class
class Player:
def __init__(self, nam... |
Here is a new version of a segmented and wheel factorized Sieve of Eratosthenes. It currently uses mod 30 wheel factorization to eliminate multiples of 2, 3, and 5 in the sieve data structure to gain speed. It wraps the wheel with segmentation in order to reduce its memory footprint so it can scale up to N in the bil... |
This is just a simple monitor for shopify products for an array of sites. It involves parsing the /products.json of the site, checking if each product ID is already stored as a key in redis and if it isn't it needs to notify a group of discord members (haven't implemented yet). Really appreciate any feedback given!
con... |
I was solving one competitive coding question having integer bounds 2^100. Fortunately, it was a dp question and I didn't need an array of that size. Practically we cannot create an array of size more than Integer.MAX_VALUE.
But I was thinking of creating a multidimensional array and treat it as a one-dimensional arra... |
I'm writing my first game and would love some advice on how to get away from all this hardcoding I'm using...
Each Character has "abilities" (all individual functions) but I can't seem to figure out how to streamline this. Example:
def lightning_bolt(self):
if self.is_stunned:
print("Stunned...ability unsuc... |
I have a function that takes an object ("token") and three additional parameters of different types ("obj1", "obj2", "obj3"). The object "token" has an 'IsSatisfied' method that may take none, 1, 2, or 3 paremeters of types matching "obj1", "obj2", "obj3". Versions of "token" that have 1 or more parameters are generi... |
https://leetcode.com/problems/burst-balloons/
Given n balloons, indexed from 0 to n-1, each balloon is painted with
a number on it represented by array nums. You are asked to burst all
the balloons. If you burst balloon i, the number of coins you will get is calculated as:
$$ nums[left] * nums[i] * nums[right] $... |
I'm checking if an byte array contains a another Byte Array with this Code:
private int IndexOf(int index, byte[] AllBytes, byte[] searchByteArray)
{
for (int i = index; i <= AllBytes.Length - 1 - searchByteArray.Length - 1; i++)
{
for (int j = 0; j <= searchByteArray.Length - 1; j++)
{
... |
I'm working on a small piece of my personal website. I'd like a timeline logging all of my relevant achievements in my career in Computer Science, in general. I'd like to implement a feature that would allow the user to focus on a specific section of the timeline.
I have implemented a fairly sparse version of what I wo... |
I'm currently learning C by working on my first project.
It's a calculator with a parser that transforms input into an operator tree. These trees consist of nodes of different types: Operators (inner nodes), constants and variables. My first attempt was to create a single struct node and just put everything a Node migh... |
Inspired by this blogpost I decided to try and make it possible to have ranges of enum members that dwim, aka. that contain the actual members and not a stringified form.
This is the result. I'm looking for comments and wether I overlook a pitfall. Also, maybe EnumMember subset can be expressed in a more performant wa... |
Below is my code for the Fantasy Game Inventory problem from Chapter 5 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner or more efficient?
The code starts out with a dictionary "inv" that contains the player's current inventory as well as a list "dragon_loot" that contains the ite... |
I am beginner in OOP. And i want you to analyze my piece of code and give me some recommendations.
My task was :
RPG game give a chance to choose race of Hero : Argonian, Breton, altmer, nord. In addition to choosing a race, the user has the opportunity to choose these characteristics : sex, color skin,weight,tattoo, h... |
I got frustrated with the jargon and created an alternative state management solution. Its up at https://github.com/smakazmi/react-soliit. It goes something like this
import React from "react";
export default class StateStore<T> {
private listeners: Array<Function>;
constructor(public state: T) {
this.listene... |
I have coded a speedreading training bash script. My targed was to make some experience with bash in a funny way.
It essentially does the following:
Prints to screen a random number consisting of a default number of digits
Erases that number after a default time interval
Waits for the user input
if the user enters a... |
Now I have this very simple priority queue. add and changePriority both run in \$\mathcal{O}(n)\$ and extractMinimum in \$\Theta(1)\$:
net.coderodde.util.pq.PriorityQueue:
package net.coderodde.util.pq;
/**
* This interface defines the API for priority queue data structures.
*
* @author Rodion "rodde" Efremov
* @... |
I am currently working on a AIS message decoder written in pure Python. It's just a little project to teach me some things about binary data, decoding, etc. Because I am only programming for about a year or so I am not quite sure, if my approaches is reasonable. The full source code be found here: https://github.com/M0... |
I have a piece of working code that takes some strings from Consul configuration exports, sanitizes them a little and converts them into valid json and/or hocon structures.
While I am iterating over a vector of Nodes in the process function, I couldn't come up with a better solution than having to clone them. After in... |
This is a programming challenge.
I have been given the following input:
\$n\$ where n is size of sequence
\$k\$ is an integer
a sequence \$A_0, A_1, A_2, \ldots A_{n-1}\$
I need to perform for each index from 0 to (k-1) inclusive
find a,b
where a = A[i % n] and b = A[n - (i % n) - 1]
then set A[i % n] = a XOR b
... |
I'm learning Rust.
I find it sometimes confusing when compared to other programming languages, especially when dealing with strings and slices.
Her's an implementation of the 99 beer song that I've written, but the code feels clunky and I think it's bad.
How would you have written it, if it was a production code of a r... |
How can I improve this code? Is it somehow possible to remove fields from HTML and pass all necessary data through FormGroup?
app.components.ts
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.