instruction stringlengths 71 95.1k |
|---|
I tried to make a password generator and at first it works as intended, generating a password with lowercase, uppercase and special characters but I can only generate passwords of up to 19 characters any more and the script sends an error about a string being too big or something.
import random
generator = "qwertyuiop... |
Add 2 strings representing 2 doubles, return the sum of the 2 doubles in string format. Please review my code. Is there a cleaner way of writing the code where we have to add the 2 doubles digit by digit?
for example, s1 is '9.9' and s2 is '8.8', we need to return '18.7'.
The requirement is that we cannot pad zeros f... |
Mu solution to Leetcode problem Cousins in Binary Tree works, but the code feels bulky. Is there a better way to solve this problem, particularly to use less additional variables? I will appreciate any suggestions on how to improve this code.
Problem:
In a binary tree, the root node is at depth 0, and children of each... |
Any comments, critiques or questions about this? I'm using this as the base for a few rectangular board based toy programs like Conway's life and snake. Usage includes configuration of board size at runtime, hence the type doesn't carry size info, only the instances.
#include <utility>
template<typename type>
class Ar... |
Below is my function to solve the Minion Game problem on HackerRank along with the problem description.
It works wonderfully with regular-length strings, like 'banana', but when it comes to really long ones (ones that produce output counter in the vicinity of 7501500, result in a runtime error (or memory error, dependi... |
I have a string "abbbbccdddd" and the function should return "a1b4c2d4".
This is what I have written in Scala.
Iterative-version
def compress(str: String) = {
val chars = List(str).flatten.map(_.toString) ++ List(null)
var result: String = ""
var lookBack: String = chars.head
var occurance: Int = 0
chars.fo... |
I wanted to open source some code to scrape and analyze publicly-filed stock buys and sells from U.S. senators. I'm not familiar with code style for Jupyter notebooks or pandas in general. Would it be possible for you to review my short notebook? The original can be found here.
Ideally I would get the scraping code rev... |
I made some code about solar system stimulation in C. It is working, but it looks too long.
So, Are there some ways to shorten my code?
Also this website told me your code is too full to upload this.
#include <Windows.h>
#include <stdio.h>
#include <math.h>
#define solar_size 20
#define PI 3.141592654
#define rad angl... |
I'm very new to the JavaScript, and hence I would like to get a feel on the language by writing some of the basic programs. One of those is the following visualization of the Bubble Sort:
Code:
<!DOCTYPE html>
<html>
<body style="background: pink">
<p id="word" style="color: black">Bubble sort: visualization</... |
I was given a API project by my co-worker to work on half created a system in slim PHP. The project consists of the Models and controllers. When the route is called it calls the Controller with the necessary function in the Controller, then query data from the database in Model functions and get back the response.
I wa... |
I am new to Python. Amateur, enthusiast and learner.
I have developed code which visits one particular website. Crawls through it to reach a certain repository, downloads the records from there to the local disk. It has too many while- and for-loops nested inside one another. It has nested functions too. How can I refa... |
I am implementing a few Celery background tasks (e.g sending an email, subscribing someone to an Audience via Mailchimp API, etc.) and my project relies on a Flask application factory.
Now, I am trying to understand if the way I've used application contexts makes sense at all or if it can be improved (I've quite a few... |
I've created something that I called System, where you can login, create the files and delete the files.
It's not any kind of big project, but it's the biggest project I made in PHP OOP so far. It uses MySQL PDO database connection. Passwords are not hashed since there's no registration page. The thing I'm not sure abo... |
Here is the code for balance retrieval from EMPLOYEES record. Please simplify and improve it accordingly. It is working fine and I have no problem with it but I believe that's not the correct way to do it.
Public Sub GET_BALANCE_VALUE(EMPLOYEE_ID As Integer, EMPLOYEE_NAME As String, ByRef BALANCE As Integer)
Dim co... |
I am having a small piece of code in my project. There are too many if condition. How can I rewrite it better to make it more readable, remove any redundancy etc and cleaner way? I am using Java 8.
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
... |
New to python.
I am converting multiple html files to csv. Developed a full code. It can easily convert 50+ files at a time but after 200+ files, the code takes too much time and with 1000s to convert, it seems that I should look for some other solution all together. Hope to receive some suggestion to speed up the pro... |
we have homework in Java to do some users, contracts, and some API. We should create a user with some information about him and one of that information should be address (one where he live and one where post should come) But I am not sure if I did it correctly.
I create a package called user inside which i created User... |
I'm working in swift and I've got a custom class Array2D to handle fixed-width, two-dimensional arrays of integers. What I'm trying to do is write a simple, ideally-elegant function max() -> Int? to behave the same way as for a 1-D array: return nil if the array is empty, or else the maximum value in the array. I make ... |
I am trying to build a 12-column CSS grid system very similar to Bootstrap. 4 breakpoints are supported: normal, sm, md, and lg. Anyway, here is the code:
.row {
position: relative;
width: 100%;
}
.row [class^="col-"] {
float: left;
}
.row::after {
content: "";
display: table;
clear: both;
}
[cl... |
I am creating a c++ library implementing Java Functional Programming alike interface. In short, the code will look like this:
vector<string> buffer = ... ; // A buffer contains some strings
new IntStream(0, 100).map([](int a){
return (a * 0x2344DDEF) & 0xF;
}).map([=](int a) {
return buffer[a];
}).foreach([](st... |
I came across in a code base # TODO this seems very clumsy to duplicate the loop code like this? so I figured I'd give it a shot as a learning exercise. I'd like some feedback on what I came up with, particularly:
Is this proper idiomatic Julia, or close? Or am I just writing Python in Julia?
What explains the differe... |
In the past I have made programs that have generate a buddhabrot with mostly success however all of them were on the CPU and single threaded. As a result they were all slow so I wanted to remake the program but this time I wanted it to be fast and I decided to make it in CUDA. However I had never made a program in CUDA... |
I wrote a socket library in C++, to wrap Winsock.
I found it a bit tiring using winsock2 - I'd say it's a bit complex, compared to, for instance, the Python socket library.
My code, header file:
#pragma once
#pragma comment(lib,"WS2_32.lib")
#include <winsock2.h>
#include <Ws2tcpip.h>
#include <windows.h>
#include <str... |
Multiple forms make use of the autocomplete of material, which gives a resulting code that is repetitive and difficult to maintain.
The controller is left with pairs of repeated methods [for each controller].
displayFn(option?: Interface): string | undefined {
return option ? option.Property : undefined;
}
filterAut... |
Application Summary
I received a call from a client asking for a "simple app" that notified him via text message whenever a "Jeep Wrangler" is posted to Facebook Marketplace. It sounded simple enough, so I took the gig. I figured I would leverage FB's Graph API or possibly simply set up a filter in his account, or some... |
This class represents a single entry in a log file of the Common Log Format. Can this be improved? I think I might be able to use delegation to pluck values from the matcher. Ideally I would be able to set these values at declaration time.
Kotlin code
data class CommonLogEntry(private val entry: String) {
... |
I am currently backing up remote OS' while preserving the permissions using rsync:
rsync -aAX --numeric-ids --delete ... root@X.X.X.X:/ /backup/server/
Now I want to backup the backup to a third party. I currently have:
tar --xattrs -czpf - "/backup/server/" | openssl enc -aes-256-cbc -a -salt -pass pass:"$KEY" -out "... |
This is a small script to update an external HDD, every night at 23:00, in the background.
Can you tell me how I can improve it?
What section in this code can be written as a class? Maybe the log function?
This line -> from distutils import dir_util. How can I write this to follow the same format as my other imports?... |
I created a simple bank program. The program asks for the user’s name and a starting balance. From there, the user can do 4 things, Check Balance, Add Funds, Transfer Funds and Exit the program. Check Balance simply returns the name of the user along with the remaining amount of funds in his account. Add Funds asks the... |
This Flask app, which makes use of SQLAlchemy, a MySQL server which is only reachable via SSH and Flask-Login, is the base on which I want to write an application which has login protected pages.
Registering users is a feature that I still have to write in a better way, but it works for now and testing purposes.
I'm po... |
I have a stored procedure the every 5 min run in sqlserver
high cost iO/cpu
do you have any idea to tune this query
ALTER PROCEDURE [dbo].[doc_Letters_SyncBulkUpdate]
@TrackerStatusSync BIT
AS
UPDATE doc_Letters SET
[CentralDeptNo] = tempLetters.[CentralDeptNo],
[IncomingNo] = tempLetters.[Incomi... |
I'm beginner in rust.
I would ask code review of my finite state machine.
Main feature :
static (event, state and transition)
support pushdown
It is the first step, second step is to use macro for generate section.
In my example i have 3 events (e1, e2, e3), 4 states (red, green, blue , rainbow). There are 4 type ... |
I recently had a need to convert a TrueType font to a Game Boy tileset, so I wrote a program to do it.
This correctly aligns the characters on an 8x8 plane and outputs in the form of RGBDS-style GBZ80 assembly.
Needs the FreeType library installed; use the Makefile (or copy the commands) to compile it.
drawtile.c:
/*
... |
I'm newly exploring time series databases, and trying to wrap my head around what data I'll store and how I'll query it. Also, I'm relatively new to TypeScript. This prototype exercises my current understanding of how it will work.
What I most want feedback on is:
TypeScript idioms: am I following them? Does anythin... |
I am calculating the log-likelihood of data that have some observations censored. For uncensored "a" clusters, the likelihood calculates P(Y=y). For censored "b" clusters, it calculates that Y is at least size Y, P(Y≥y). So the likelihood is L=mult[P(Y=y)P(Y≥y)].
The below code is my working, actual-in-use code that c... |
My code passes 11 out of 12 test cases. I was wondering where I can improve my code. NOTE: This code needs performance improvement, as it is working for most of the cases. To mu knowledge it would work for all the test cases where the size of arrays is smaller than 200.
Here is the question:
Alice is playing an arcade... |
Let me preface this with saying that it's probably not necessary to understand all the math behind this to review my code. Unless you have a lot of spare time or a very strong interest I also wouldn't try too hard to understand the background if you don't already know some of the basics, like what a symmetric polynomia... |
I had just put together my first public project: simple(sane) new-handler for c++.
It allocates some reserved memory on start up, then releases it piece by piece. It may also raise a signal when each piece is released. It allows to monitor approaching of low memory conditions and gracefully handle them at the system l... |
the following tutorial uses an interceptor to show/hide a loading bar:
https://www.freakyjolly.com/http-global-loader-progress-bar-using-angular-interceptors/
export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest<any>[] = [];
constructor(private loaderService: LoaderService) { }... |
So I'm on level 5 of Google Foobar, and the Question is Expanding Nebula.
It goes as follows :
Expanding Nebula
You've escaped Commander Lambda's exploding space station along with numerous escape pods full of bunnies. But - oh no! - one of the escape pods has flown into a nearby nebula, causing you to lose track of ... |
So I was investigating overflow safe division for a class that uses an int64 member with a given RESOLUTION ( 10000 ) for the fractional part. To preserve precision in the fractional part during an easy division you would multiply by the resolution first, which if the number is large enough results in an overflow. I ca... |
I'm learning python (started about 30 hours ago) and my son asked if I could make a hangman game. Well, okay, I'll give that a try. I'm sure this code is crap, but I'll never learn if I don't ask how I could have done this better. Anything that's poor practice or doesn't scale? (I won't ask what's sloppy - it's all... |
This is a mix of data structure and multi threading concept based question. (This is only for understanding and learning purpose) The language for the solution : Java
A Queue with FIFO behavior needs to be implemented by having underlying data structure as Stack.
Enqueue and Dequeue need to be parallel and need not blo... |
I have made a linear interpolation functions as a side project of mine. It assumes everything is sorted before hand - x and f(x) are the same length.
I would like to ask for:
general recommendations
if I can improve the design (generalize it to all iterables like std::array etc...)
and for further performance optimiza... |
I've just learned about custom wrapper classes and I'm a bit confused about a couple of things.
First, what's the utility of such tool? From what I understand you can mimic the copied class behaviour but with slight modifications. Is this tool used often?
Also, could you please have a look at my code? I know I'm suppo... |
The rules of John Conway's Game of Life are simple:
An OFF pixel that has 3 live neighbours is turned ON.
An ON pixel that has anything other than 2 or 3 live neighbours is turned OFF.
Many people that program this game select the easiest of video modes: the 320x200 256-color mode. To satisfy my desire for a smoot... |
Could you please tear my code apart? It's an exercise from CodeGym. Recently I changed a few things within my coding practices, namely:
Not writing all my solutions on main. Instead, trying to create methods to make the code more organised.
Instantiating the class on main to call the methods.
Using try with resources... |
So I have just started to work with SQL and I have tested my script and is working very well when it comes to my database.
The database is used for shopping. What I mean by that is that I scrape a website that I love (Flowers etc) and then I collect each item that has been updated on the website and add it to my datab... |
Firstly, have a good day to all,
I've been trying to learn PyQt5 nowadays. I wrote a code about check box state changing depends on other check box. It looks work. I wonder your feed back.
Thank you for your time.
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class CheckBox(QWidget):
def __... |
Here is a "Roman Numerals" kata implementation. Given a decimal number one has to return a corresponding roman number.
I have following questions:
Is memory management correct? Here I assume that the caller is responsible for freeing memory.
Does this code conform to c code style?
Does it look like idiomatic c?
Thank... |
I have rewritten the Vector2 class that I usually use in my projects. The code looks as follows:
#pragma once
#include <type_traits>
#include <utility>
#include <iostream>
namespace ae
{
// Does T support constexpr?
template <Literal T>
concept Literal = std::is_fundamental_v<T>;
template <Literal T>... |
In a bash 3 script for OSX machines, I needed the functional equivalent of the realpath command, complete with support for the --relative-to and --relative-base options.
I would normally just install the homebrew coreutils formula, but I need this script to work when bootstrapping a new machine with no network or XCode... |
I want to read a vector of eight bytes, convert them into hexadecimal, store them in a std::string and finally write them into a binary file.
I am looking for suggestions and recommendations to improve the efficiency and readability of the code.
#include <vector>
#include <string_view>
#include <iostream>
#include <fst... |
I am brand new to writing my own code. I just started the CS50x intro class and have so far made it to pset 2 readability. It's getting easier to understand what's going on. I just wanted to get some opinions on the code that I wrote to see if there were possible improvements/changes that I could make.
#include <stdio.... |
To practice Object-Oriented Python and learning how to write tests, I found an exercise and solved it as below(all classes are put in one block of code to make the question a little bit more readable):
import sys
import random
from typing import List, Tuple, Dict, Optional
from abc import ABC, abstractmethod
class Car... |
I've been learning Python now for 3 months as I find it really interesting to code. I want to be able to apply for junior dev positions and as I have no formal education I thought I'd make a project to feature what I know.
The project is still to be compeltely finsihed but it's got the meat of it done. I created a scri... |
I find myself often encountering a use case where I need to fetch paginated data, where I need all of the data. Currently I use something similar to below to handle these cases:
def fetch_paginated_data(api_base, query, good_citizen_rate):
encoded = urllib.parse.quote(query.encode('utf-8'))
initial = f'{api... |
Goal:
Goal of this application is to sign in using MySQL database and across the forms access the username and access id.
Reason I am sharing the username is for only reason at the moment, is to display a welcome message for the user.
For the access id, depending on what number id, different dashboard buttons will rest... |
My code: https://ideone.com/DZeIZv
#include <atomic>
template <class T> class Seqlock {
std::atomic<int> seq_;
T val_;
public:
Seqlock(T value = T())
: val_(value) {
}
// concurrent calls are NOT allowed
void store(T value) {
const int seq0 = seq_.load(std::memory_order_relaxe... |
Find a bitwise XOR for a range for.e.g (5,8) --> 5 bitXOR 6 | 7 bitXOR 8 3 bitXOR 15 12
Expected worst time Complexity - O(log(n))
Expected worst space Complexity - O(1)
I have written the below code, could you please help me to improve it?
static List<Integer> list;
public static void main(String[] args) {
... |
Introduction
I've created a typed Promise implementation in Java for Android, borrowing ideas from this article for a JavaScript implementation, by Forbes Lindesay.
To allow for "asynchronicity", my implementation posts callbacks (Promise.Callback) to the message queue of main thread (Looper.getMainLooper()). I don't k... |
Here's a dynamic loopable string array that doesn't require a count to be maintained at the caller level.
Definition
char **getList() {
char **items = (char *[]) {"John", "Jane", NULL}; // dynamic/variable hard coded list
int size = 0;
for (char **ptr = items; *ptr; ptr++) { // count items
size++;... |
I would like to convert a string like "1 2 3-5" to an array of numbers [1, 2, 3, 4, 5].
Following the robustness principle, the list doesn't need to be separated by spaces, comma on any other separator is accepted. The only mandatory syntax is A-B to represent range from A to B (inclusive). Also, it's ok to ignore malf... |
I have written a series of functions to solve kenkens. The general strategy is to eliminate possibilities until only one remains for each cell. This first function eliminates all possibilities that can't be used to satisfy the operation and target constraints.
I'm interested in any feedback concerning style and effici... |
So, I've tried to make a simple math library in Rust. What do you think about it?
const PRECISION: f64=512.; //Balance between speed and precision here.
fn ln(x:f64) -> f64 {
let mut sum=0.;
let epsilon=(x-1.)/(5.*PRECISION);
let mut i=1.;
while (epsilon>0. && i<x) || (epsilon<0. && i>x) {
sum+... |
I am busy on a protected page with login and I want know if there is more protection needed. It is a very simple system without database etc...
authentication.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$account = array (
'sebas' => '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruX... |
I wanted to use an external global state to a React.js application with a redux-like sort of pattern (with reducers, actions, etc). However, I don't want to use redux itself, as it's just a small project and redux might be too much boilerplate.
Below is a sort of imitation of Redux with React.js Hooks and State. It's a... |
I wanted to write a simple implementation for a high card game. Basically two cards are drawn and the higher one wins. Additional rules: support for multiple decks, if same suits drawn then the higher colour wins, if same colour and suit (possible as there's multiple decks) then resolve a tie by dealing a further card... |
The Problem
I have a module with several sibling classes that share a method with a similar name. These methods receive the same basic arguments, however, for a number of the sibling classes the method in question can take different arguments that are irrelevant to the methods defined in its siblings. For example:
clas... |
I'm in the process of creating my first web app using node with mongodb on the backend. I could use some opinions on the schemas/models I've set up.
I have three schemas: User, Pet, Food. Here's the general relationship of them:
Users have pets -> Pets have a list of ingredients and list of favorite foods -> Food has l... |
I have a class Main that uses fn(cls, ...) methods from several modules; they're used exclusively by Main. Each module is 500-1000 lines long (without docstrings); the idea is to "break up" various Main methods to ease debugging and readability, instead of packing them all into one class and make a 9000+ lines file.
E... |
i try to make an app for a mobile store
class Mobile(models.Model):
model= models.CharField(max_length=30,unique=True)
created_at = models.DateTimeField(auto_now_add=True)
edited_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Storage(models.Model):
mod... |
When keeping track of various pieces of information in a variable when using a dispatch group, I've fallen into a pattern of protecting the variable using a serial queue, and then ultimately notifying on that queue to do something with the final value. Is there a more idiomatic way to protect things?
Here's an example ... |
This is a simple command line interface program that just keeps track of duration spent on multiple tasks.
Any areas of improvements are welcomed to be pointed out.
import json
import datetime
dt = datetime.datetime
td = datetime.timedelta
def encode_time(t):
if isinstance(t, dt):
return {
'_... |
A common use for Keras LSTM layers is to generate text. There are
many examples showing you how to do it.
The usual method is to convert the text into a sequence of tokens and
then slice up the sequence into overlapping windows which is used as
inputs and the windows following tokens are the outputs.
So if your token s... |
Goal: extract methods/functions defined in module. This excludes:
Imports
Lambda methods
Magic methods
Builtin methods
Class methods
Classes
Non-original definitions (i.e. function assignments, alt_name = orig_fn)
My approach + test below. Any room for improvement, or false positives/negatives? (In particular I wonde... |
Hello, I'm a C++ beginner, learning the language while trying to code Project Euler problems. I'm having trouble coding problem 14, which I'll copy here:
The following iterative sequence is defined for the set of positive
integers:
n → n/2 (n is even) n → 3n + 1 (n is odd)
Using the rule above and starting with 13, ... |
I am making a 2d graphics engine. I am somewhat new to JavaScript and have been winging this project. So far it creates a background (a tilemap made of smaller images in a grid) and sprites ( a small image
with a higher z index). I ommited my test code, as I didn't care for that to be reviewed, but if it needs to be i... |
I have created a bash script to generate a HTML file, which will have the duration of the audio/video files in the current folder. The script uses ffprobe to fetch the duration in the quiet mode and file to get the mime-type. Although, the script works as intended, it feels a bit slow. I was wondering if it is possible... |
I have the following code which works fine but the execution time is more which I want to reduce. I guess this happens since each file is opened and then the operation is performed. Is there a way to open the file once, perform all operations, and then close it, which may improve the processing speed?
At a high level, ... |
Below program find a minimum positive number that is greater than 0, it doesn't occur in the array. My solution actually works fulfil performance-wise. However, Codelity has given 55% only, I m trying to understand what is the potential issues with below code?
For example, given A = [1, 3, 6, 4, 1, 2], the function sh... |
I recently played around with a script that got some data from the Google API. As I didn't want to spam requests at the service (and potentially get blocked), I made this decorator, which caches the result of a function for a specified amount of time. Any call after the time-to-live (TTL) will call the function again.
... |
I'm learning C++ and did some reading here and elsewhere on trie structures. I've written a simple class that performs insert and match using a sorted vector as the underlying container.
I used unique_ptr, but I get nervous using the .get() method to access the raw pointer. Is there a better way?
Also, I had to o... |
I'm writing an app with NativeScript 6.4.1 and Angular version 8.
There are a series of UI events in iOS that you can watch to see what the keyboard is doing:
https://developer.apple.com/documentation/uikit/uikeyboarddidhidenotification?language=objc
I wrote a service to watch and subscribe to these changes.
Do you see... |
I have a function written in Groovy which needs to save a record and also return response from the server.
Function is working fine, but I am not happy with the design because I have a problem with multiple nesting.
This is the function:
Map scanAccessRecord(GrailsParameterMap params){
Map response
Date curren... |
all.
This component is meant to take in an array of available options and provide the user an easy way to choose multiple options. Each time the selected options are changed/updated, those options are console logged.
I'm hoping that someone could provide any criticism on my current code. I want to make sure that the co... |
Ahoy friends.
Right now i'm selling a huge amount of HDDs and usually i used DBAN or nwipe to perform this actions.
Unfortunately the PRNG Mersenne Twister is quite slow, so i get a throughput of around 100MB/s for 16 HDDs, which takes a really long time.
I'm majoring electric engineering, but i had some C programming ... |
When writing image processing/computer vision algorithms, I usually use double in computations and then I have to remap the values back into std::uint8_t range, because that is what PNG supports. The main problem is that the image is represented as multi channel entries in a matrix, and remapping should be done for eac... |
The question is as follows: Given a collection of distinct integers, return all possible permutations. Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Here is my backtracking solution for the problem, where I added the num_calls variable to keep track of the number ... |
I wrote a simple prime sieve in Python. But it ended up looking... ugly. I included a few of the most basic optimizations. When posting this question SE suggested a bunch of questions on the same topic, which lead me to some improvements. But few were in generator form.
It's the optimizations' fault.
Unfortunately I ca... |
Straight insertion sort
When inserting an element into its proper location to the left, one can achieve that by \$n\$ adjacent swaps which totals to \$3n\$ assignments. Straight insertion sort, instead, stores the element and than performs \$n\$ chain shifts to the right.
Binary insertion sort
Just like conventional in... |
I have written a C program to sort files (on Windows) into dynamically created subfolders based on information found in their data headers. I am a newb at C, especially memory management. The code works. I have tested it on a small sample of 6 files. The next step is to put it into "production" and have it sort a giant... |
A program that generates questions to train your number base conversion skills. This program is made to ask questions about octet, binary and hexadecimal. No other bases. It first asks a series of questions to the user such as "amount of questions", "question type" and "base". Then, it starts generating questions based... |
Any improvements?
import datetime
import json
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
"""
This method will only be called if an object is passed to the parent JSON encoder in the case
it doesn't know how to deal with.
In case the object passed to the encode... |
Kosaraju algorithm is mainly phrased as two recursive subroutines running postorder DFS twice to mark SCCs with linear time complexity O(V+E) below,
For each vertex \$u\$ of the graph, mark \$u\$ as unvisited. Let \$L\$ be empty.
For each vertex \$u\$ of the graph do Visit(\$u\$), where Visit(\$u\$) is the recursive... |
I am trying to implement the Jagged Diagonal Storage code in Cuda for Sparse Matrix - Vector multiplication. The code I wrote is as follows but I'm not sure about it:
__global__ jds_kernel(JDSMatrix jds, float * invector, float * outvector){
int i = blockIdx.x * blockDime.x + threadIdx.x;
int row = jds.rows[i];
... |
I have some code that boots up a minecraft server, more complicated then most. I'm looking for some positive criticism on how to improve my code (and coding practice!).
File:
::Copyright notice
::RandomWords.py
::By Dylan Prins
::
::This work is licensed under CC BY 4.0.
::To view a copy of this license, visit
::https:... |
I'm currently in a programming competition where time is key, therefore I'm trying to optimize my solution as much as possible. I am trying to implement a BFS Flood Fill solution on a map size of 30x30 (900 operations) where the time limit is 1 second. I'm falling a bit short on time (a little bit above 1 second). I ch... |
I have been learning about refactoring and I have this method that I'm wondering if I should split into two for code cleanness. First, the method as one, next the method split in two:
Method not split:
public static ArrayList<String> getFilePathOrName(String pathOrName) {
ArrayList<String> files = new ArrayList<>()... |
I did the Divisible Sum Pairs problem on HackerRank
input: n is length of array ar, k is an integer value.
a pair is define only if ar[i]+ar[j] is dividable by k where i < j.
Problem: find and return pairs in array.
def divisibleSumPairs(n, k, ar):
i=0 #pointer 1
j=1 #pointer 2 is faster tha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.