instruction stringlengths 71 95.1k |
|---|
I have this code:
export function is_palindrome(num: number): boolean {
return [...num.toString()].reverse().join("") === num.toString();
}
which checks if a number is a palindrome(i.e 9009 reversed is still 9009), I do this by using the spread operator on num.toString(), reversing the array, joining it, and then ... |
I wrote this method a few years ago in a Ruby on Rails project, which I think I am not proud of. How can I make this code better to show in-depth professionalism in Ruby?
lib/merchant/web_csv_importer.rb
# frozen_string_literal: true
require 'open-uri'
require 'csv'
class WebCsvImporter
attr_accessor :url
def in... |
I'm working on a calendar for my office. Every people has his own column and there is a line for every day.
There are some periodic date, where, for example, given people have to be working on the week-end. But most of the dates are coming from a MySQL database.
So it does a double loop (people vs dates) in which every... |
I'd like to build an app in Flask that can switch between talking to a PostGresql and a Mongo DB. As I understand it, the Strategy Pattern is about being able to switch algorithms that are referred to by some method call on the fly. So, I think this pattern would be relevant because I want to switch out what abstract... |
I have the following method that I am trying to optimize. Currently, the method works great, however, it takes a little over 3 hours to complete. I feel like, using some nifty LINQ joins, it should be able to run in minutes. Here is the method:
public async Task UpdateEmailTable(IEnumerable<StudentEmail> students)
... |
Hello I'm doing a mini project that is modeled after pitch constellation.
--> https://en.wikipedia.org/wiki/Chromatic_circle
Basically, pitch constellation is modeled after a clock where each note is assigned a number. When the wheel goes clockwise it goes up the scale, and when it goes counterclockwise it goes down. I... |
I've been working on a simple hashmap in C. Here is hashmap.h:
#ifndef __HASHMAP_H__
#define __HASHMAP_H__
#include <stdlib.h>
#include <stdbool.h>
typedef size_t (*HashFunction)(void*);
typedef bool (*CompareFunction)(void*, void*);
struct Pair {
size_t hash_id;
void* key;
void* value;
struct Pair* ... |
This is a follow-up question for Avoiding requires clause if possible on a series recursive function in C++ and A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++. Thanks to indi's detailed and clear answer. I got the key point "The po... |
I recently whipped up a Battleship program with Java as part of my Basic OOP class in university. The class is done but all we get are grades. I would really love, though, to know where and what I can improve upon. Is there a better way to implement my code? (It's still my first year in software engineering, just in ca... |
I was told I need code in order for someone to review my UML Class Diagram for my Noughts and Crosses console application. I would like to know if it's intuitive, whether you could make a program based on it, and whether any improvements need to be made on it.
#include <iostream>
#include <vector>
#include... |
I am new to coding for ~1 week. I know that I learn best by doing, and so I decided to work on a small and simple project while utilizing various online sources to learn as I go.
Anyway, I decided to write a little program that asks the user to input their age and then prompts the user to enter an age they wish to be w... |
I'm looking for some feedback on my first 'real' Python program. Started with Python a few days ago and wanted to get right into it and make something hands on.
Currently the program lets you download audio and video for a YouTube video using Pytube. It allows you specify the location to save the download, whether to d... |
Here is a very simple Matrix Multiplication console application using multiple threads (one per row), I'm just looking for feedback to keep improving :) thank you in advance
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <thread>
using nam... |
#!/usr/bin/env python3
'''
Asymmetric criptography of chat messages.
'''
#TODO: implement perfect foreward secrecy
#Because of forward secrecy an attacker would need to have access to the internal SSH state of either the client or server at the time the SSH connection still exists.
#TODO: protect aainst traffic analy... |
I am learning .NET for about a month now ..and i am practicing by making a simple WinForms project ..now almost my WinForms is completed ..i need to gather your suggestion on how my progress is going and the code is efficient or not , kindly review this below code and share you valuable suggestions:
using System;
using... |
I'm very new to haskell (I never used Monads, Functors and other things) and FP in general. I decided to write the simplest parser I possibly can with some expansion possibilities. (I have a general interest in programming languages, so this is why I chose to do this...).
I have a simple parser type:
type Parser a = St... |
Problem
Reduce the number to 1 in a minimal number of steps, following the rules:
If the number is even, divide it by 2.
Otherwise, increment or decrement it by 1.
Limit: s can be up to 309 digits long.
Solution
public static int solution(String s) {
BigInteger n = new BigInteger(s);
BigInteger one = BigInteg... |
(I asked this Question in stackoverflow (Delphi) and they suggested that I try here.
Is there a site to submit my Delphi 7 coding to?
Hi I am learning how to build compound components. My latest works fine, but I am wondering if there is a site where I could submit my code and receive feedback.
I would like this feedb... |
I wrote a Tic-Tac-Toe game for two players, where each player uses the same keyboard. It's not a school project or anything, I just thought this would be fun to code for practice.
I'm open to and looking for any sort of feedback. Do the comments contain sufficient detail to understand the code? Are the functions separa... |
The following SQL code keeps only the MAX(date) rows with the same id and question values. I would like to know if there is a simpler/ shorter syntax returning the same result.
with
tbl_src as (select * from `tests2.o1.mc` order by id, date),
tbl_max_date as (
select
id,
question,
MAX(date) as max_date
... |
I'm a beginner and tried to make a decimal to any base converter using C and I plan to upgrade it to an any base to any base converter.
This is my code: (questions at the bottom)
#include <stdio.h>
#include <stdlib.h>
//DECIMAL TO ANY BASE
void decIntTAB();
void decFraTAB();
int digitCount();
void printOut();
int ma... |
I am using a dual channels DAQ card with data stream mode. I wrote some code for analysis/calculation and put them to the main code for operation.
However, the FIFO overflow warning sign always occur once its total data reach around 4300 MS (the DAQ on board memory is 8GB).
I am well-known that a complicated calculatio... |
I have implemented a code to resolve following interview question. Please advice how it can be improved folks. Thanks in advance.
Given an array of time intervals (start, end) for classroom lectures
(possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], yo... |
Let's say I have this array.
items = [
{
amount: 100,
add: true
},
{
amount: 50,
add: false
},
{
amount: 100,
add: true
}
]
What I want to do is add the amount if add is true and subtract it if add is false.
This code uses an extra total variable.
total = 0
items.each do |item|
if... |
Context
I am building an algorithm that automatically assigns a planning to drivers. However there is a lot of pre-processing and reused outputs. I try to structure it in a maintainable way.
Questions
I created a class Availability that represents the number of hours each driver has each day. There is a base planning, ... |
I created a console-based TicTacToe game in Python. So far, everything works as expected. I decided to keep the class static, because I figured there would be no use for multiple game states at once. Is there anything I can improve on?
class TicTacToe:
"""Plays a 2-player TicTacToe Game."""
__curr_player = Fal... |
I have created a named function with signature PadInternal(base, width, paddingStr) where:
base is a string you want to add padding to
width is the length of the individual chunks
paddingStr is the string to pad with
called from a cell like:
PadInternal("Hello", 1, " ") = "H e l l o"
PadInternal("World", 3, "**") = ... |
I have written the below code while helping one of the colleague over the SO and this code working as desired, but I feel there may be some improvement specially on the string formatting syntax's which can be better reviewed by experts here.
Code snippet:
#!/python3/bin/python
import pandas as pd
pd.set_option('expand_... |
I wrote this little utility program that saves and load digital images such as videos, pictures among others in a database. I used click module for it's interface. Am fairly new to click and sqlite module. I would love to enhance and improve this project and would love to get feedbacks concerning what I have done so fa... |
This is a follow-up question for A recursive_transform for std::vector with various return type, A recursive_transform Template Function with Execution Policy, A recursive_count_if Template Function with Execution Policy in C++, Avoiding requires clause if possible on a series recursive function in C++ and A recursive_... |
I have this method (consisting of three methods) that I need to use for looking through objects that are going to be serializes and logged as json objects.
a bit of intro (not necessary to read)
The initial problem was that I noticed that sometimes I would receive data in objects from external api's that would contain ... |
My code checks if a new subbed episode of a TV show is out by checking the designated blog. The blogs url returns a json which is then parsed for episode number, direct video link, embed video link, and banner image. The retrieved episode number is then compared to the current episode number which is read in from a jas... |
This is my code:
export function all_divisors(num: number): number[] {
return range(1, num+1).filter(i => num % i === 0).toArray();
}
the range function(docs) is part of the IterPlus library and is a pretty self-explanatory inclusive-exclusive range function, again, what I'm doing using the filter function is pret... |
A code to check the time slice for each thread separately, it will receive an integer number from the command line for the number of threads to run simultaneously. Would love some feedback on what is possible to be done differently in order to improve it (e.g different functions to use which are more accurate?, etc.).... |
Suppose you have a main window and open a dialog to do some kind of specific operation on your data. The dialog has interactive elements such as QSpinBoxes and QComboBoxes that determine properties of the operation. For convenience, the default (or most recent) values are stored in the project data, and are updated acc... |
I have a React component that renders the form of a model (called riskModel). This form is used in two different context; for creation and edition of a specific model.
In this form, there are many different complex inputs, such as:
Dynamic graph sections that include a .json file of a specific format, a title and a de... |
Here is a composable IHandler<T> implementation. Any ideas on how to make it shorter and get rid of exception being thrown?
interface Handler<T> {
fun handle(e: T)
operator fun <TOther> plus(other: Handler<TOther>): Handler<Any> =
Composite(this, other)
private class Composite<T1, T2>(
pri... |
I have a piece of code which works but I am looking for an optimal solution, if one exists. I have a column value and the value can only range from 2 to 10 including 2 and 10. The base value inside a switch is 18. Whenever the column value increases by 1, I need to decrease the value inside the switch by 0.5.
This is w... |
Article: https://arxiv.org/pdf/2009.07047v1.pdf
Full Code: https://colab.research.google.com/drive/1KZZuIa7Lk13ImZLJ3b-kxMfcveOPaWvN#scrollTo=XhdMfBFtzaEH
Dataset: https://drive.google.com/file/d/1IliW9Z7s6B9VBadQ7BahFLnXLt_mmGzg/view?usp=sharing
First Block
import os
import sys
import torch
import torch.nn as nn
impor... |
I have a class Accounts with an array of account numbers and an array of balances I have a member function add_acc that adds an account. But before adding an account, I want to check if the account no. to be added, already exists or not. If it exists then an error message is displayed else the new account is added. In ... |
I'm working on a Python class that is a cyclic generator, like itertools.cycle, but it offers access to its current state and executes a callback after the completion of each cycle.
I'm looking for feedback on the way I've implemented this so that I might improve it or find a better way.
In this version, I've used iter... |
The other day, I had occasion to want to look into an ancient piece of Z80 software written for a Sinclair Spectrum computer. Software for this machine was typically saved to audio tape, and today people use the TAP format to store and exchange Spectrum software. The format is a very literal translation of the origin... |
I have the following code:
export type AvatarSize = "xs" | "sm" | "md";
const sizes = new Map<AvatarSize, 32 | 44 | 104>([
["xs", 32],
["sm", 44],
["md", 104]
]);
To me, it feels dirty. I wonder if there is any other way to write it without hard-coding the sizes?
Thanks!
|
I need a JavaScript-function which always computes the date of the next day. Then returns the date as a string, formatted in the way: dd.mm.yyyy
I wrote this code:
const getDateStringForTomorrow = () => {
const millisOfDay = 1000 * 60 * 60 * 24;
const oTomorrow = new Date(Date.now() + millisOfDay);
const ... |
I have this code that uses three methods to do certain tasks. One creates an array, another reverses it and the other one prints it out(it was required to use three methods). A person recommended me to upload my code here as there are a few things that need to be improved.
They said that I do not need to return arrays ... |
I am building some statistic counter in Java.
Each metric could have flexible depth so the implementation should able to explore the depth when value insert or update.
So I implement like below (with Test)
public class TestRecursiveMap {
private void recursiveRegister(Map<String, Object> target, String[] keys, int... |
I have a class named Employee and another (reg_employee) that instantiates the former class.
I want to know if this code can be improved.
class Employee:
def __init__(self):
self.Name = ''
self.Id = 0
self.Age = 0
self.company = 0
self.title = ''
self.Level = 0
... |
I display the current user location, using Geolocation - and activate/cancel it according to button click and map view.
This is managed by the state isLocateUser.
When the app is ready, the default state isLocateUser is T, the Map component renders and looking for the current user location, via the custom hook useWatc... |
I have a transactional batch inserts where previous batch insert results will be used in another batch insert. My code below already works and just want to ask if there are part of the code to be improved.
Multi.new()
|> Multi.insert(:template, ChecklistTemplate.changeset(%ChecklistTemplate{}, attrs))
... |
So I wrote this simple program to place a certain number of people on a list of seats whilst maintaining maximum social distance.
Given that there is at least one empty seat, calculate the maximum.distance from an empty seat to the closest occupied seat and return the available seat.
How can this be improved to be bett... |
Current implementation
I am using a normalized weighted Levenshtein distance for two utf32 strings with the following costs (insertion: 1, deletion: 1, replacement: 2). The normalization is performed in the following way:
1 - distance / (s1.size() + s2.size())
In cases where I am only interested in results above a cer... |
I've been playing with some genealogical files in XML lately and wanted to create a transform that would list, for each person, the person's name, the count of ancestors, and the list of ancestors. Here's what I came up with, but I'd like to see if there's a better way to do this.
<?xml version="1.0" encoding="iso-885... |
I'm writing a program that creates curling sequences -- in short this means that we start with a given sequences, consisting of 2's and 3's (i.e. a mix of 22 of them), and look for repetition at the end of the sequence. The curling number, i.e. highest frequency of a period at the end of the sequence is then appended t... |
This is the follow up question of How can we optimizing Java BigInteger operations?
Problem
Reduce the number to 1 in a minimal number of steps, following the rules:
If the number is even, divide it by 2.
Otherwise, increment or decrement it by 1.
Limit: s can be up to 309 digits long.
Solution
The solution I have com... |
This is a snippet of code written in Python 3.9 to implement the concept of "enum unions": an enum made up of several sub-enums whose set of members is the union of the sub-enums' members. This aims to be fully compatible with the standard library enum. Up-to-date code with some documentation can be found here.
Usage a... |
I wrote this mini thread pool in JavaScript that takes a maximum number of concurrently running tasks and runs them in the order it was given. I appreciate any feedback or review. Thank you.
class TaskPool {
constructor(poolSize) {
this.poolSize = poolSize;
this.queue = [];
this.runningTasks = 0;
this... |
I built an allsky camera with a temperature sensor and a heater. The heater is supposed to turn when the sensor (measure_temp()) return a temperature below 8, which is checked every 15 minutes. However, about every 4th measurement fails and so I included an error handler that returns 7, so that the heater turns on if t... |
I built a solver for Tents puzzles using the CaDiCaL SAT solver. The code works and runs quickly, it takes less than 0.1 seconds for a 60x60 tents puzzle on a 2,6 GHz Dual-Core Intel Core i5 2013 Macbook Pro. Note that the tents website can't handle puzzles greater than 25x25, the 60x60 board was created by a custom s... |
I developed this feature that I think can be improved quite a bit. The result is the desired one, but it took me many lines of code. Any idea to optimize it?
import json
import urllib.request
dni = 71179047
def get_cuit(dni):
request = urllib.request.Request('https://www.cuitonline.com/search.php?q=' + str(dn... |
I wrote a connect four game for two players, where each player uses the same keyboard. I programmed this solely in hopes of improving my skills.
I'm open to and looking for any sort of feedback. Do the comments contain sufficient detail to understand the code? Are the functions separated into their individual mechanism... |
Please review my strstr implementation in terms of time/space efficiency and overall readability. I am preparing for a coding assessment coming up as I am looking to pivot my career from Physics to Computer Science. This is an exercise from the interview practice questions on CodeSignal. My implementation successfully ... |
Background
In one of our repositories we have a folder called player_test where we store all player_test related .py files. We realized that there are certain static csv files we use to do some processing. So we decided to create a folder called player_test_input inside the player_test folder. The player_test_input sho... |
I'm trying to develop an OOP way of thinking. I was hoping someone would be kind enough to spare some of their valuable time to review my Grade Calculator OOP program. As always, I'd like to know what I've done well, what I should improve upon, and any suggestions on how I could perhaps improve what I have? By the way,... |
I've come up with some simple implementation for algorithms in C and more specifically for std::accumulate alternate since I need something like it recently. Can you provide some review on the approach?
#include <stdio.h>
#include <string.h>
#define ARRSIZE(X) (sizeof(X) / sizeof(X[0]))
#define ACCUMULATE(RET, FIRS... |
A legacy project was upgraded from legacy code that used either SystemV FIFO device (or similar queue on Windows platform) which was deeply ingrained into every thread's implementation. Following implementation of locking queue with a wait was meant to emulate original FIFO use:
#include <queue>
// target platform does... |
I have implemented a message queue for inter thread communication just like POSIX message queue. I want to know whether there is any scope for performance improvement and also any bugs which need to be corrected. This is my code:
#include <iostream>
#include <cstring>
#include <list>
#include <vector>
#include <thread>... |
This is a follow-up question for A recursive_transform Template Function Implementation with std::invocable concept in C++ and A recursive_transform Template Function with Execution Policy. Based on the previous questions, I am trying to consider execution policy parameter for recursive_transform function here.
The exp... |
Some time ago, I wrote this answer to a question about creating a command line menu. I referred to it recently and noticed a few things that I wanted to improve.
Purpose
As with the original version, the purpose is to have a class which simplifies the construction and use of a command line (console) menu.
The improvem... |
My code takes the input submitted by $ _POST, via a checkbox array. I process the array and check the sent data if there is a particular string in it, which is set as my default. If I have a string, which is my default, I just go through implode and add ",", if my default string is missing in the data. I add and sort t... |
I recently bumped into dry-python/returns, which seems like a very useful project. In the project description, the authors describe a snippet which can be written with their Maybe container in a better way (according to the authors):
The original code is:
if user is not None:
balance = user.get_balance()
if b... |
This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function that takes a dictionary argument that represents a chess board (ex: {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', etc.}) and returns True or False depending on if the board is valid.
A valid board will have (A) exactly one... |
I have classes that have some data, and whenever this data changes, it should notify observers of that data change. There also should be a method to add new observers.
My first approach was to use a property with a custom setter. This means that whenever the = operator was used on the data it would call the custom sett... |
I'm trying to learn some basic x86 assembly and so I've begun solving Project Euler problems. I was hoping for some critique of my code that, hopefully, includes either the efficiency of the operations or the readability / style of the code itself. I will provide the Makefile for Linux 64 bit.
The purpose of the code i... |
Extreme script newbie here, so please go easy on me!
I wrote a script to install zsh on a number of different Linux distributions. But since I'm so new at this, I'm piecing a lot of different things together and I doubt it's as efficient and tight as possible. Any suggestions are welcome. Thank you!
#!/bin/bash
export... |
I'm a long-time Java programmer, but recently I decided to give Kotlin a try. So far, I'm loving the language features, it feels much more expressive than what I'm used to. As practice, I wrote this function that produces a repeatable sequence of prime numbers (i.e. the sequence can be iterated multiple times, and wi... |
Banknotes are given specifically 100, 50, 20, 10, 5, 2, 1. Required to check and find out: What is the maximum possibility to keep these individually into the given integer value.
For example:
input: 576
output: 576
5 nota(s) de R$ 100,00
1 nota(s) de R$ 50,00
1 nota(s) de R$ 20,00
0 not... |
I wrote my own Discord Bot which is taking screenshot of a specific website. This scrip is very simple and thought it should work fast, but it isn't. I read a lot, and I think I'm not able to improve it. Today my driver.get(URL) not working fast- i think the website is a little broken. But yesterday I get a result of 1... |
checkIfMultiple x [] = False
checkIfMultiple x (n:ns) = x `mod` n == 0 || checkIfMultiple x ns
findMultiples limit ns = [x | x <- [0..limit], checkIfMultiple x ns]
sumMultiples limit ns = sum (findMultiples limit ns)
sumMultiples 999 [3, 5]
Things I am curious about:
Passing down limit and ns from sumMultiples to f... |
I have been trying to improve my Discord sending webhooks functions where I have multiple dictionaries, as you will see in the code below:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from threading import Thread
from discord_webhook import DiscordEmbed, DiscordWebhook
DISCORD_POSITIVE = {
"hello": {
... |
I've recently started journey with ReactJS and to begin with I wanted to try something a bit more complex - paginated list of elements with back functionality enabled.
Below are two main components that I'd like to get feedback about. Especially PagedListings.
import './App.css';
import PagedListings from './components... |
I am writing color model logic in C++. I ask review in defining limits for the color model, by saying Limits I mean this.
Consider a struct which represents RGB color model.
template<typename T>
struct RGB {
T r,g,b;
};
So I declared a type RGB<T> where T can be any arithmetic type (the assertion is done, don't wo... |
Recently I appeared for an job challenge organised on HackerEarth.
Question:
There are two teams T1 and T2. Power of each player is represented in array. The rules of game are as follow.
There are only N fights.
No player from any team can fight twice.
At any instance, only one fight can occur.
For each fight score is... |
In working on another problem, one component I needed was to calculate the centroid of a collection of complex objects. The well-known way to calculate this is to simply average the real and imaginary parts. To accommodate either std::complex<double> or std::complex<float>, I have created the following code as a temp... |
I have implemented a dictionary with an AVL tree, and here is the code and I need help improving it.
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <string>
#include <vector>
#include <list>
using namespace std;
class NoSuchKeyExeption {};
template<typename k, typename t>
class dictionary
{
privat... |
As described in his paper, Tarjan's algorithm reports only the nodes of the strongly connected components. For my use, I would also like to also have the edge list of the components (so that I can run Karp's minimum mean cycle algorithm on it)
As a side note, it is rather curious why he did it for the biconnected comp... |
I want to ask if there is a better way to arrange this. Main concern is whether the store is set up in a good way and if passing Pointer to ProductRepository is a good idea or there are better ways but criticism towards all of it is welcome. I'm relatively new to Go. I have this folder structure
.
├── Makefile
├── apis... |
I'm currently writing an API for our codebase that allows us to use an Arduino Leonardo for our tests. This code is uploaded to the Arduino, and we read through the analog for work.
As stated in the docstring, this function calls a passed function once a threshold has been met. However, I need there to be a delay betwe... |
Currently I'm working on a way to handle resources in my game engine. It is my first iteration and I would like to expand on it in the future like asynchronous loading of resources. I am looking for some feedback and advice in order to improve it.
The API consists of the following classes.
identifier
Is responsible for... |
This program calculates the sum of all integers in the range \$[1, 1000)\$ which are multiples of either 3 or 5 or both.
Inspired by x86-64 Assembly - Sum of multiples of 3 or 5 the other day, and also drawing from some of what I learned through Calculate the centroid of a collection of complex numbers I decided to try... |
Hello I need help to optimize this code. I have a radar and it gets the enemies from a list and adds an image to their location to track them. I use Update to remove the images and LateUpdate to add the images. Is there any way I can do this without costing performance. I have a list of all the Enemies. I have a pool o... |
There is a web page I visit which I would like to print. However, I only want to print a couple of things on it, not everything.
So, I am making a bookmarklet that I can use whenever I visit the page to hide everything from the printer except what I want to print.
The site already has a class, 'd-print-none', to hide a... |
I built upon a previous beginners' class' hangman game to do graphics with Turtle. It should work with any .txt list of words in whatever location you specify at the top of the code (in my case on Windows, E:/My Documents/Programming/Projects/Hangman/words.txt). Alternatively you can uncomment the commented line contai... |
I'm designing a Matrix class and I feel like what I've come up with requires too many calls to new. I know it's possible that caring about this is premature, but I already know I need this code to be fast, so I'd like to think about streamlining it now.
Here's a test to show how I intend to use the API:
[Fact]
public ... |
Hello everyone and thanks in advance for taking the time to read my post!!
In the process of learning Ruby, I'm writing a video poker machine that analyzes hands represented by arrays of Cards, like so: [ card, card, card, card, card ]
You may know that in draw poker, one can hold certain cards and toss the rest to the... |
We are working on a complicated math problem, very detailed question with description of the problem is here: C++ multi-threaded determination of curling numbers in vectors.
That code is now converted to use 256-bit registers to store the bit sequences. Profiling pointed to one function taking over 85% of the total CPU... |
I know it's bad to even use recursive_mutex because of its poor performance, let alone a recursive shared mutex. However, I'm doing this just to practice. Any suggestion will be appreciated!
recursive_shared_mutex.hpp
#pragma once
#include <optional>
#include <shared_mutex>
#include <thread>
class recursive_shared_... |
input:140153(seconds)
output:38:55:53
I have solved this problem in this way:
#include <stdio.h>
int main(){
int N;
double hour;
double minute;
double seconds;
scanf("%d",&N);
hour=N / 3600.0;
double floating = hour;
double fractional, integer;
//split the floating value(hour) in... |
This is a metaclass for facilitating the concept of "inner classes" (as opposed to simple nested classes) in Python. I define an inner class as a nested class that expects an instance of the outer class as
the first argument to __new__ and __init__.
This metaclass implements the
descriptor protocol (non-data) for the i... |
The code below is my shot at trying to do monte carlo integration of the function sin(x) from 0 to pi in Python 3.
I sample randomly 10000 times a floating number from 0 to pi and do the standard procedure of the monte carlo integration and also take the average of ten results for an even better approximation,i was won... |
I have built a quiz app. It is my first project so the purpose is to learn app development at this stage.
There are two key things which I am wondering how to do better (the app is fully functional).
1: Livedata / flow / room
I have the following data class
@Entity
data class SavedScores(
@PrimaryKey(autoGenerate =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.