instruction stringlengths 71 95.1k |
|---|
I've been grinding some Leetcode for an interview coming up and just completed Square Spiral in Javascript.
Looking for feedback on performance. This ranked faster than 58% of submissions, would there be anyway to increase the speed using a similar implementation to what I have here?
let matrix = [
[1, 2, 3, 4, 5],... |
I'm working on a simple Leaky Bucket algorithm.
I have found a lot of samples on the internet, but something always bothers me.
Most of them use Collections and DateTime to track current actions and calculate the time of a Delay.
So, I try a controversial (according to my co-workers) implementation, using 2 semaphores ... |
I am computing pairwise Euclidean distances for 3-D vectors representing particle positions in a periodic system. The minimum image convention is applied for each periodic boundary such that a particle only considers the nearest image of another particle when computing the distance.
This code is part of a larger post-p... |
<!DOCTYPE html> <!--Declare the doctype as the html standard of HTML 5-->
<html lang="en-us"> <!--Lang Attribute to declare the language of a webpage-->
<head> <!--Every html doc needs a head which contains important information for viewing the code on different devices.-->
<meta charset="UTF-8"> <!--The... |
Here is the improved code
#include <iostream>
#include <sstream>
#include <string>
#include <random>
#include <vector>
#include <iomanip>
enum class ending
{
win ,
lose ,
tie
};
enum class States
{
Human ,
robot ,
blank
};
enum class command
{
deletE ,
move
};
class BOARD {
publi... |
I solved problem 58 in Project Euler and I am happy with my solution. However, are there any areas where I can improve my code here as I am learning how to write good python code.
Prompt:
Starting with 1 and spiralling anticlockwise in the following way, a
square spiral with side length 7 is formed.
37 36 35 34 33 32 ... |
This is my 1st Python program I've actually written and I have little to no background in the language. I just figured I could learn and do something that interested me at the same time.
I'm not a book learner. I can't just sit down and read a bunch of technical documents and stuff like that so I'm sure a lot of this c... |
This ip core simply generates a sine wave according a .mem file. It is required to specify rom depth equal to number of the sine points, the init file and the data size contained in the file. The phase offset and frequency are used as control signals.
It also houses the ROM module as well as the ip core and ROM testben... |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
class Student {
// Student class properties
int number;
Double grade;
// Student constructor
public Student(int index) {
Random generator = new Random();
number = index+1;
grade = generator.nextDouble()*20;
}
}
clas... |
I need a function of type forall (n :: Nat). RandomGen q => q -> Vec n q. Obviously this is possible to do (correctly, don't just repeat) using split.
(Documentation links: Nat, RandomGen, Vec, repeat, split, induction1.)
I generalized this to not specifically be about RNGs by taking the splitting/unfolding function as... |
I'm trying to create a Collider class which will process collisions between different classes of the same base. One restriction is that I want these classes know nothing about each other, now they depend on Base and Collider classes only. Here is my code:
collidees.h
#pragma once
#include "collider.h"
#define ALLOW_C... |
I'm trying to make a safe builder using Kotlin that can be partially built and then copied, perhaps multiple times, to avoid repetition. Note that the properties that are reused aren't always the same - I've reused name and real here, but sometimes age and real or only age might be reused. This is what it looks like (M... |
This is a script that I've written for personal use, and to educate myself. The script is a bit comment heavy to help future me remember all the details & design choices made at the time of writing.
The use case is simply to synchronize/copy files to an AWS S3 bucket using AWS CLI. There's a separate CDK part of the pr... |
This code models two vehicle types, with a method to accept a string representing a boost to change speed.
How can I optimize performance in inheritance child class?
How can I reduce the code inside BMW class?
How can I use additional variables to reduce the child class code?
class Maruti{
public $currentSpeed;
... |
This is quite a specific script I have written, for Kubernetes Cluster monitoring purposes (specifically the Nodes). Essentially, I need to ensure that the Nodes within a NodeGroup all have the same labels and label values, or else they will not be scaled out evenly for Node Scale out in the version of Kubernetes we ar... |
Update at the end
Is it possible to implement IDisposable pattern correctly while using object composition principle to promote code-reuse, reduce code duplication and hide verbose "official" implementation?
Rational
Composition over inheritance is a good principle
Implementing IDisposable correctly and thoroughly i... |
Python Noob building an automation irrigation system in Python for Raspberry Pi.
Python has two functions in the most basic use case:
on/off the LED (which will in future be a relay->pump) and
Notifies "This is out of water" (which will in future be a HTTP post)
I have a GPIO switch that working successfully on: wat... |
Hello programming gurus/reviewers,
I attempted to solve the Minimum Window Substring (Leetcode 76) problem using Python 3. My solution involved using Counters and backtracking. On submission, the solution worked for all cases, other than the last test case where the strings were almost 10000 characters long. This last ... |
I have been coding in Java for about a month now and I'm seeking advice for my program on things I can improve. This project was mainly made for me to incorporate all the new things I learned and utilize them effectively. I appreciate any feedback :).
About the program itself, it takes in a string and reverses it. It a... |
This code was an answer to my own question on SO, however I am looking at the line global X and wondering if there is a better way to do this. I try to minimize the amount of global declarations in my code in order to avoid namespace collisions. I'm considering changing this code to use multiprocessing.shared_memory, b... |
I'm developing a screen recording application using java. I've modified code from https://dzone.com/articles/screen-record-play-using-java where all the external jars required for this application are available.
If I lower captureInterval to 25 then the application runs out of memory - i.e. it throws a java.lang.OutOfM... |
I just wrote my pong DQN. It seems to work. I'm looking for a performance based review on anything that might slow down the training in complex models.
main.py:
import gym
import torch
import torch.optim as optim
import matplotlib.pyplot as plt
from tensorboardX import SummaryWriter
import wrappers
import model
impor... |
I wrote some code and realized they share similar logic. I am struggling to share the logic and welcome any suggestions.
public List<string> SendTemplateAsSampleEmail(MtaConnection mtaConnection, ICollection<EmailRecipient> recipients,
SimpleContentDto renderedContent)
{
var errorStrings ... |
Kind of a noob at Python here, and this is one of my first "big"(big for a beginner like me) project that I undertook with Tkinter and Pynput. Basically, this code will simulate an enemy's movement pattern based on some conditions that I made(you will be able to see the different "phases" being printed out on the conso... |
After much prompting from this post I wanted to build a simple, in-memory, thread-safe cache.
The only caveat (as far as I was originally concerned) was the need for two different absolute expiration times for cached objects - those being based on a property of the item being cached (IsFailureItem). This is for a .NET ... |
I am new to quant. finance and trying to calculate trend, momentum, correlation and volatility. Below are the functions I have created
import pandas as pd
def roll_correlation(first_df, second_df, rolling_period):
"""
Rolling correlation
"""
return first_df.rolling(rolling_period).corr(second_df)
de... |
My code in Julia, almost identical to the Python code (see below), runs in 4.6 s while the Python version runs in 2.4 s. Obviously there is a lot or room for improvement.
function Problem12()
#=
The sequence of triangle numbers is generated by adding the natural
numbers. So the 7th triangle number would be... |
I am completely new to JavaScript and I will be grateful for your comments on my Electron app (electron is a JS framework allowing to create of desktop apps).
I needed to create an application that stores a small database and allows me to do simple operations on the data. I just include a small fraction of that app her... |
Recently I was assigned a URL shortener design problem while interviewing with a well known organization. Here is the exact problem statement:
Build a simple URL shortener service that will accept a URL as an argument over a REST API and return a shortened URL as a result.
The URL and shortened URL should be stored ... |
I wrote the below as a solution to:
Problem
Find the highest product of three numbers in a list
Constraints
Is the input a list of integers?
Yes
Can we get negative inputs?
Yes
Can there be duplicate entries in the input?
Yes
Will there always be at least three integers?
No
Can we assume the inputs are val... |
I am working with C#, Npgsql, EF Core and Postgres.
I defined an endpoint for a paginated search, where the filters and orderBy column are dynamic. The endpoint accepts a PaginationOptions instance:
public class PaginationOptions
{
public int Page { get; set; }
public int ItemsPerPage { get; set; }
public s... |
I completed the following question but it seems a lot of space complexity.
Do you think is there a way to complete it with graph search or so?
Thanks for the comments.
Suppose we have some input data describing a graph of relationships between parents and children over multiple generations. The data is formatted as a l... |
I've put together an example single file upload script that attempts to cover all the things PHP could check for prior to allowing a successful file upload. Is there anything else maybe now available in PHP 7.4+ I could use to make this more secure? For example, I use filter_input below even though I don't find it in m... |
Coming from a Java/Scala background with a strong focus on OOP+FP, I recently started working with Excel+VBA to implement a front-end for a SaaS. It was like stepping way back in time, over two decades, in software engineering trying to understand how to use and exploit VBA.
In the ensuing 3 months of being immersed in... |
This nice hack should allow you to split a tuple into N-element tuples, thereby effectively splitting a tuple into pairs, triples, ... For example, this allows you to split an input parameter pack, into N-element tuples. Your thoughts?
template <std::size_t N>
constexpr auto split(auto&& t) noexcept
{
static_assert(s... |
I have made a thread art generator that creates thread patterns from images. Mine is a bit different as it outputs an embroidery file (It embroiders quite nicely, though the settings need a lot of tweaking and the output file needs resizing) The code is quite inefficient, but that's python for you.
from PIL import Imag... |
I have written a cryptographic hashing class named Ccksum::DigestHasher that allows the caller to select a hashing algorithm by name via OpenSSL's EVP interface. This class is the bread and butter of my Ccksum programming project. Here is the code so far (I combined the header and source files for the readability of th... |
I started making a game in curses, but I feel like I am displaying the map inefficiently and ineffectively.
Here's the code (only the relevant parts):
import curses
world_map = [
'00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
'00000000... |
We wrote a code that parallelizes the divide phase of the mergesort algorithm. I.e. every recursive call is assigned to a thread but our teacher was disappointed because he said we should also parallelize the merge function. I have researched how one can do this and I found these (algorithm 3) lecture notes which chang... |
I want to refactor this code to a better version without all this repetition, this code is working 100% the way it is right now but every refactoring effort is making it useless, any idea or can this be considered the maximum ?
let div = document.querySelector('.results')
if (results < 0) {
let item = `<div cl... |
QUESTION:
You will set up simultaneous thumb wrestling matches. In each match, two trainers will pair off to thumb wrestle. The trainer with fewer bananas will bet all their bananas, and the other trainer will match the bet. The winner will receive all of the bet bananas. You don't pair off trainers with the same numbe... |
origin code:
# add this class to make the code can be a reproducible example.In acutually environment all attribute could be True or False.
class Capabilities:
def __init__(self) -> None:
self.canEditCompany = True
self.canDeleteCompany = True
self.canShareCompany = True
self.canAddF... |
I am looking for a simpler implementation of the following question.
Could it get better?
I am expecting the new solution via DFS again. Thanks.
OA: Given a 2d matrix with chars and a target string.
Check if the matrix contains this target string
by only going right or down each time from the beginning point.
public cl... |
Based on a previous post, Accelerating creation of matrices and finding ways for optimal scaling, we managed to accelerate the way that I construct a matrix in Rcpp (inputs for example are at the end of the post). The code used is the following:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [... |
I started implementing the folowing Matrix class in order to get a better understanding of templates classes in general. For now, it lacks a lot of features, it does very basic things:
addition
multiplication (only matrix X matrix multiplication is available here)
transpose
conversion to a string
Here are some points... |
I implemented the Maximum Profit in Job Scheduling algorithm in JavaScript, but I'm having performance issue.
The problem:
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].
You're given the startTime, endTime and profit arrays, return the maximum p... |
I wrote a short function to iterate over a list starting at a given index, then flipping back and forth between left and right values.
import itertools
from typing import Generator
def bidirectional_iterate(lst: list, index: int) -> Generator:
for left, right in itertools.zip_longest(reversed(lst[:index]), lst[in... |
Hello how can i send a token from the msg.sender to mycontract through a function inside my contract?
i tried to do a transferFrom
"IERC20(old_tokenAddress).transferFrom(msg.sender, address(this), query_oldBalance(msg.sender));" but i get: execution reverted: ERC20: transfer amount exceeds allowance even if i put
th... |
So I have this piece of code that produces following error:
cannot return value referencing local variable `key_name`
returns a value referencing data owned by the current function
I want it to evaluate the Key range and produce a map of strings, but it fails on the line map. I can't seem to set up the ownership right... |
The first function will always try to correct the final result, while the second uses a conditional to know when to compensate. I think that in general the second function will be faster, but it will look a little worse than the first.
int floor_mod1(int a, int b)
{
int mod = a % b;
return (mod + b) % b;
}
int... |
I am trying to build a model that allows me to estimate the spread of disease in the population. The setup is similar to the SIR model, with the difference that this model includes the stochastic component.
I have written an algorithm to carry out the simulation, but the lead times are really high. Could you please hel... |
With my VB.Net Windows Forms application, I would like to rotate and project a 3D object. The program works so far, which is why I'm reporting here and not Stack Overflow, but it's slow.
I've already made two optimizations:
1.) All points that are on the back of the object, i.e. that cannot be seen, are not drawn. Unde... |
New Scala dev here. Is there a more idiomatic or efficient way to accomplish this in Scala?
Given a list of the following strings, I need to obtain the unique 'main parts' once any parts including and after a "-" have been removed.
The output should be a list of sorted strings. Also note both ";" and "," have been use... |
I have been on the C++ learning grind for the last 2 weeks using caveofprogramming videos so don't judge too hard if this seems like a dumb question.
My last lesson covered arrays and the assignment was to make a 10x10 times table using multidimensional arrays. I succeeded in making this times table but with my knowled... |
I'm playing around with understanding array looping speed.
I'm trying to make the contenders equivalent and close to realistic.
Is this a good approach?
Are there other iteration approaches to test?
let suite = new Benchmark.Suite();
const length = 10000;
const arrayToTest = [];
for (let i = 0; i < length; i += 1)... |
I've been trying to make a rubik's cube project and it succeeds nicely . The only problem(or something like that) is that i need to optimize my code for easier understanding and more flexibility. Here's my code to optimize:
[...]//Code for creating cubes
int main()
{
[...]//some extra codes
while (!glfwWindowShould... |
The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are cube.
The following co... |
This is a custom case insensitive nested dictionary class created by me, its main usage is to populate QTreeWidget and keep track of said QTreeWidget, the main incentive behind this class is to prevent case insensitive duplicates from entering the tree, and to report the indexes of the nested keys (d = {'a': {'a': {'a'... |
Im just trying to setup my shader function in a class in a way that would make me work with it easier and in a more understandable way.
In Shader.h:
#pragma once
#include"Includes.h"
#include<unordered_map>
namespace GAME
{
enum class Shader_Type
{
NONE = -1,
VERTEX = 0,
FRAGMENT = 1,
... |
#include <iostream>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <sstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#incl... |
I have a csv file that looks like this:
time, price
0 2021-07-23T20:00:00.000221421Z 368.06
1 2021-07-23T20:00:00.001131397Z 368.06
2 2021-07-23T20:00:00.008030544Z 368.06
3 2021-07-23T20:00:00.00807574Z 368.06
4 2021-07-23T20:00:00.008084129Z 368.06
... ... ...
32435 2021-07-23T23:59:46.272261376... |
Problem:
Given two csv files science_courses.csv and other_courses.csv, which has students name and their respective course points. Calculate the CGPA and sort by the same (highest to lowest CGPA).
sample file content:
science_courses.csv:
Name,Physics,Chemistry
Susan,6.0,5.5
James,4.7,8.5
Linda,4.5,6.3
Mathew,7.7,5.4... |
I'm learning PHP and try to write some scripts as I go along. I wrote this script and it worked. I would like to know if this script can be improved.
The purpose of the script below is to prompt the user to input the version of the backup file, and proceed to make a backup fo the Nextcloud directory.
Thanks in advance.... |
My goal is to write code that picks several random numbers from a range without repeating any previously chosen numbers.
I figured out a functional solution for my problem but it seems very bulky and there must be a way to do this in fewer lines. Mine feels brute force and not very elegant and becomes super unwieldy if... |
I have this Python code:
def main() -> None:
print("Welcome To UltiList!")
lst = []
len_of_list = int(input("Enter the len of the list: "))
while len(lst) <= len_of_list:
print(">> ", end="")
args = input().strip().split(" ")
if args[0] == "append":
lst.append(int(... |
This is a problem from Daily Coding Problem. I have implemented it in Java.
For a function f I have used Runnable interface.
Problem:
This problem was asked by Apple.
Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
Solution:
import java.util.*;
import java.util.... |
I have implemented a simple XOR encryption in Python. However I am not sure this is the right implementation or it can be further improved ?
from math import ceil
from random import uniform
from numpy import array, repeat, vectorize
#---------- HELPER FUNCTIONS ----------#
def addtrailingzero(byte):
"""
Ad... |
I am new to python, and even more new to vectorization. I have attempted to vectorize a custom similarity function that should return a matrix of pairwise similarities between each row in an input array.
IMPORTS:
import numpy as np
from itertools import product
from numpy.lib.stride_tricks import sliding_window_view
I... |
Benchmark
An optimised 4x4 double precision matrix multiply using intel AVX intrinsics. Two different variations.
Gist
For quick benchmark (with a compatible system) copy paste the command below. Runs tests on clang and gcc on optimisation levels 0 -> 3. Runs a naive matrix multiplication NORMAL as a reference.
curl -O... |
i have created an object orientated Calculator without GUI.
i have provided only the most important parts of the code. I want to add another review question for those parts (especially: MathResult and Operands)
Interface Calculator
public interface Calculator {
MathResult<?> calculate(String operation);
}
Interfac... |
I would like to ask you to verify the following implementation of the PIMPL idiom. In this dummy implementation the stream is read into a string.
X.h
#ifndef X_H
#define X_H
#include <memory>
#include <istream>
namespace mynamespace
{
class X
{
class XImplementation;
std::unique_ptr<XImplement... |
This is the first time I have recoded in C for several years and I would like to know how clean my code is.
#include <stdio.h>
#include <string.h>
#define EXIT_SUCCESS 0
void fizzbuzz(int n) {
char result[9] = ""; // strlen("fizzbuzz") + 1 == 9
if (n % 3 == 0) strcat(result, "fizz");
if (n % 5 == 0) strc... |
This is a Python case insensitive dictionary that is ordered and has integer indexes for the keys and values.
I just wrote it today.
It is ordered because I am using Python 3.9.6 and plain dict is already ordered by default.
It prevents case insensitive duplicate keys from entering the dictionary (e.g. if 'Adele' is al... |
Im currently working on a filtering keywords. I have two lists which I called positive and negative.
Scenarios:
if POSITIVE matches and NOT NEGATIVEmatches = True
if POSITIVE matches and NEGATIVEmatches = False
if NOT POSITIVE(Then no need to check NEGATIVE) = False.
I have done something like this:
import re
from ty... |
class RadarChecker:
def __init__(self) -> None:
self._issues = set()
@property
def issues(self) -> Set[str]:
return self._issues
@property
def _checkers(self) -> Iterable[Callable]:
return (
self._check_1,
self._check_2,
self._check_3,
... |
I have recently been learning Haskell, and wrote a minesweeper project as an exercise. Here is link to the project.
Basically the code is separated into two parts, the pure part (no monads) and impure part (deals with random and IO). Since I'm pretty new, I'm a little iffy about the whole setup. Any advice would be app... |
I wanted to make a bounded slider since the ranged slider wxwidgets includes isnt very useful for my use case. I wanted a left and right bounded slider to control a dynamic way to control a graph or plot x-range.
I got a good head start from a person who made a library in Python and ended up creating my own version in ... |
I recently tried to solve the first non-repeating character problem. Please tell me if my solution is valid. I'm aiming for O(n) with a single loop.
My thinking is, it would be easy to tell you what the last non repeated character is, just:
loop each char
if map[char] doesn't exist
output = char
store char ... |
I've just started to learn C++.
I have this class and I don't know where to put the following two lines because of the catch:
delete[] chost;
delete[] cport;
I think they are in the right place, but I have doubts because in C++ doesn't exist finally.
Header:
#pragma once
#include <string>
#include "TelnetClient.h"
cl... |
I have a python script to archive some data (export from mongo to a local json file and then upload it to s3)
Is there a better way to implement/improve the current flow? Each step should be be retried in case of failure and if the step is still failing after the set no of retries it shouldn't run the other steps but c... |
In general my page is slow and has several points in the code that I believe can be improved, even in relation to the structure used. Anyway, the biggest problem is:
The page I'm creating is very simple. The problem is that I created the entire first section - i.e. <div class="column ..."> but then I had to use the fam... |
I'm trying to write something like an adjusted run-length encoding for row-wise bit matrices. Specifically I want to "collapse" runs of 1s into the number of 1s in that run while maintaining the same number of 0s as original (right-padding as necessary). For example:
input_v = np.array([
[0, 1, 0, 0, 1, 1, 0, 1],
[... |
Code is meant to be used in Windows .NET (tested with dotnet5.0) to dynamically load C library and return delegate of given function
Code lower is result of my attempt to rewrite the [DllImport] annotations based header file, that was provided by 3rd party along with the DLL library itself, when multiple instances of g... |
I had this as a project last school year and decided to try and optimize it. I'm curious to see how much I have learned; is this a good way of doing it?
import os
dict = {
# "empId": ["title", name]
"000001": ["ceo", "joe", "smith"],
"000002": ["co", "bob", "konn"],
"000003": ["lead designer", "koss", "kl... |
I've built a very simple personal website, everything is in a single file because it is very straightforward, but I think the JS script could be better structured. All it does is fetch some repos from the GitHub API and displays them in a horrible format.
This is it (index.html):
<!DOCTYPE html>
<html lang="en">
<hea... |
I am very new to Vue.js, I just stumbled on a very hard thing to do (at least for me) where Vue was complaining about mutating a prop (children shouldn't change parent props apparently). I was about to give up at 8~ hour mark, but then it worked! Then not only that, I came with another solution. Here are the two soluti... |
I have a program that uses pandas to read csv files and then generates and saves graphical charts. I have been trying to follow the SOLID principles so I have tried to seperate responsibilities.
So far the project has the structure of
GUI
├─ Service
│ ├─ Business Logic
│ │ ├─ DataReader
│ │ ├─ ChartGenerator
The ... |
I am trying to find the "Number of trailing zeros of N!" (N factorial).
In the python code I am trying to find the factorial first and then the number of trailing zeros. However, I am getting "Execution Timed Out" error.
Why is this code giving the error? Is there anyway to optimize the code to decrease the execution ... |
I have created common function for CRUD operations.
I am using Sequelize JS, I have created all models in Sequelize
I have written stored procedures in mysql for CRUD operations for each module/tables I have
GetItems
GetItemById
CreateItem
UpdateItem
Deleteitem
Then I have created Common CRUD function in Utilitie... |
I've been trying to learn a bit of JavaScript over the last few weeks, and inspired by this current hot network question, I tried creating a function for finding the first non-repeating character in a string. Is my approach a decent one, and is there any obvious improvements which can be made?
function firstNonRepeatin... |
I wrote a program for Conway's Game Of Life in Java. Are there any improvements I could make?
main class:
package main;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
public class GameOfLife {
static Board board;
static Window window;
static Input input = new... |
I have a dataframe which contains information of programmers like: country, programming languages. etc:
COUNTRY PROGRAMMING_LANGUAGE
usa javascript
uk python;swift;kotlin
india python;ruby
usa c++;c;assembly;python
canada java;php;golang;ruby
angola python;c#
india c;ja... |
The code below works, but it seems it could be done better. Is there a better/more efficient way to do this?
Given:
All days off ("relief days") will be consecutive.
Relief days will be imported as a string. Days of week are represented by their first letter. "S" can represent Saturday or Sunday, "T" can represent Tue... |
I created this sample and wanted any advice on how to make this code; cleaner, more effective, just overall better! I need to add the key word and only if the NegativeScheduleCalendar enum is before the ScheduleCalendar enum. The only way I was able to do this was to loop the list and checking if they are after each ot... |
I am trying to improve my file upload handler filter.
Environment
Since any client-side validation is easily circumvented, there is none in this code, for ease of testing. Not even an accept="image/*" on the <input> element. Production code will include some client side validation.
The upload handler is set up to first... |
I decided to learn a little about AutoHotKey, to practice a little and learn about classes.
I ended up writting a basic ini file parser.
Class Ini {
ini_file := ""
ini_data := {}
__New(ini_file)
{
if ini_file
{
this.ini_file := ini_file
Try
{
... |
This is LeetCode question 387 if anyone is interested. The task is to accept a string and find the first char that appears only once, and return its index. If no char appears only once then return -1. Examples are:
input: "leetcode"
output: 0
input: "loveleetcode"
output: 2
input: "aabb"
output: -1
In the first exam... |
I'm fairly new to time series databases in general and Influx in particular.
My objective is to build a simple and general-use API that will allow me to write and read data from an Influx Database.
I used Influx on a previous project and I found that building the API for the database was pretty mechanical, so I decided... |
I asked the same question on StackOverflow but was told to instead ask here since it was better suited. I have a function that I implemented. It is doing a lot of heavy lifting. I would like to optimise it or in other words try to find repeating code and simplify it a little bit. I'll show my implementation below:
setM... |
The task is:
Given an array of integers, return the minimum required increment to
make each element unique.
Sample Input 1: [3, 4, 2, 2, 6]
Sample Output 1: 3 (One of the 2s should be incremented to 5)
Sample Input 2: [3, 4, 5]
Sample Output 2: 0 (There is no duplicate)
My code works by shifting all numbers even if t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.