instruction stringlengths 71 95.1k |
|---|
For something I'm working on, I need a function that takes in a one-dimensional array vec of integers and returns a boolean array of the same shape indicating where the n largest entries of vec are located.
For example,
nlargest([0, 1, 3, 5], 2) should yield [0, 0, 1, 1].
nlargest([0, 0, 4, 0, 3, 6], 2) should yield [... |
This is a challenge on Codewars I took years ago. Task is to find all prime numbers that are also a prime number when reversed, i.e. 13 -> 31 is such a number.
This is still the answer with the most upvotes in the categories 'Best practice' as well as in 'Clever'.
Any improvements or thoughts about this piece of code? ... |
I have a complex nested object with an array of objects coming from an API. But the grid tool best works with flattened data. So I came up with this logic that will build the correct object for the grid tool.
To achieve this, it heavily relies on foreach loops and adding object to list object.
Please review the followi... |
I made a calculator in C without #include. Now, I want to make my code shorter and better. But I don't know how.
Here is my code:
int printf(const char *format, ...);
extern int scanf(const char *format, ...);
double pow(double x, double y);
int main()
{
do
{
double num1;
double a, b = 1;
... |
Program description:
You are given a set of two functions: $$f=x^3-6x^2+x+5; g=(x-2)^2-6$$
Plot them using Matprolib on a user input segment [a; b].
My solution:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interpolate # for smoothing
def func(x):
return [pow(x, 3) - 6 * pow(x... |
I would like to get feedback on my code for Stack implementation written in scala. What can be improved to make it more like scala code. What important helper functions am i missing?
class StackDS[A] {
private var list: List[A] = List[A]()
def push(ele: A) =
list = ele :: list
def pop = {
val pop = lis... |
I need to intersect lots of arrays with each other. Those arrays are like:
$a = array(4 => true, 10 => true, 18 => true...);
$b = array(6 => true, 10 => true, 73 => true...);
$c = array(106 => true, 293 => true, 297 => true...);
In PHP there is a function array_intersect_key, which intersects keys; it works fine but i... |
I'm very new to C++ and am trying to code simple programs to test my knowledge on the very basics of this language. Yesterday, I created a very simple calculator script which allows you to add, subtract, multiply, and divide and set of two numbers. While it is still very basic (e.g. only calculating two numbers), I pla... |
Part of the project I am working on is to maintain the time-of-day, at the sub-millisecond accuracy, while not overwhelming CPU.
The controller has a pretty standard timer, with two registers, COUNTER and PRELOAD. On each system tick COUNTER is decremented; once it reaches 0, the timer posts an interrupt, and reloads C... |
Link to the Problem
Here is my code to compute the length of the longest common subsequence of two integer arrays arr[] and brr[]:
#include <bits/stdc++.h>
using namespace std;
//Dynamic programm solution
int mem[10004][10004];//mem[i][j] stores length of the longest common subsequence, up to index i of arr and index ... |
I made a calculator in JavaScript. Now, I want to rename my functions, variables, and input names. But I don't know how.
Here is my codes:
function Calc() {
var num1 = +txt1.value;
var num2 = +txt2.value;
var ch = +optxt.value;
var result;
if (ch == 1) {
result = num1 + num2;
}
if ... |
I made a statically allocated memory pool for embedded systems. I think it needs a little work but it works fine so far.
How it works: An array of size MEMORY_POOL_SIZE is first reserved in memory and that's actually the space and the whole program uses to get memory from.
The number of allocations that can happen at t... |
I'm new to PowerShell (started yesterday) and was wondering if there is a way of exporting Shell bags, Jump lists, and LNK files from the Reg to a local computer's desktop using PowerShell? I have tried a few things and can export them as CSVs... but I'm not sure if that's going to have any forensic merit (dabbling in ... |
I am trying to implement a thread-safe LFU cache algorithm, please review my code and would really appreciate some criticism or suggestion. (on naming, design, data structures used, anything)
Some assumptions:
capacity will be larger than 0.
If the cache is full and multiple keys have the same frequency, the least rec... |
I have implemented basic max heap insertion and deletion functions without recursion
# insertion
arr: [6,5,4,3,2,1]
# insert 7
arr: [7,5,6,3,2,1,4]
tree:
7
5 6
3 2 1 4
# delete 7
arr: [6,5,4,3,2,1]
tree:
6
5 4
3 2 1
My implementation
def insert(arr,ele):
... |
This is a follow-up question for A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++, An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++, A non-nested test_vectors_generator Function for arithmetic_mean Function Testing in C++ and Non-nested st... |
I have a weather station with a data logger which accepts commands (specified in user manual) and sends back the respective data over a serial interface. In my case, I want to read the current data from the different sensors of the weather station in a specified interval and then publish them on a MQTT topic.
For this ... |
I have the following array, and I want to convert it to an array without duplicates.
const a = [
{
items: [
{ outerKey: { innerKey: 1 } },
{ outerKey: { innerKey: 2 } },
{ outerKey: { innerKey: 3 } },
],
},
{
items: [
{ outerKey: { in... |
This is a simple bash script that I use to compile and run single C++ files for coding competitions.
Features:
Detects if there is a corresponding .in file next to it, and if so uses that as stdin
e.g. if the file problem1.cpp and problem1.in are in the same directory, the script will redirect stdin from problem1.in
... |
I've made a major update to my Noughts & Crosses program, this ISN'T a duplicate! I know it's not good to use system("pause") and system("cls"), however, I just wanted to make the console screen more readable so resorted to these methods to achieve this. I would like feedback on how well I've used std::shared_ptr, the ... |
I've been messing around with merge sort. Instead of doing a recursive division of the array I chose to keep keep track of the middle index of every three numbers. Using the index of the middle number, it sorts the numbers directly around it and then merges the consecutive portions of the array.I'm having trouble figur... |
I have attempted to do Model View Controller in Python for learning. First, I am not sure if dictionaries are faster than lists for about N = 30 (20 to 40) items. Second, how maintainable is this design since I got abstraction but not very much encapsulation? The abstraction comes from abstracting towards to the domain... |
This is a Clojurescript solution to parts 1 and 2 of Day 1 of Advent of Code 2020.
This code is written in Clojurescript to run on Node.js. It can be run simply using lumo and this command: lumo filename.cljs.
Here's a short version of the problem statement:
Part 1. Given a list of numbers, find the two entries that su... |
My goal
I am parsing from a string which contains token:value pairs into a type.
Example:
mutable struct Foo
bar
baz
qux
end
function parse(str::AbstractString)::Foo
f = Foo()
bar_pattern = r"bar:(\w*)"
baz_pattern = r"baz:(\d*)"
qux_pattern = r"qux:(\w*)"
f.bar = match(bar_pattern, s... |
When I first got the idea for creating a tiny mandelbrot renderer I knew It would be possible
since people having creating tiny demos for a while and that I would probably use a shader. However at that point I had no idea for how to even begin so for a while it was just something that in the back of my head untill rece... |
I'm the maintainer of https://github.com/servian/aws-auto-cleanup. I'm by no means a Python expert and hence I'd say I'm way off creating code that would be considered Pythonic. I do however love to tweak and improve code quality where I can.
I'd love for someone to check over a single class of mine and provide some ti... |
Trying to improve my HTML and CSS.
Creating a Basic Table using CSS grid, to match as closely to this image:
Please ignore the color red and green in the rows and Some rows are missing since it was used with data inside a react application and since I only care about the HTML and CSS I copied only what was relevant.
H... |
I have been working on this question in particular. I'm a bit of a python beginner myself, having re-learnt functions just a few days back.
Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For examp... |
I have created a Python & Node JS encryption/decryption AES 256-CFB. The point of this little project is that I will encrypt a special URL with Python covered with base64 & URL encoding and then the Node JS will decrypt it.
For now the Node JS is working perfectly fine that can starts by decoding the URL, decoding the ... |
Dear Python VIS community.
Imagine the following situation:
You ran an experiment in an earth system model (ESM) where you altered some input parameters relative to a control run of the same ESM. Now you look at the surface air temperature and since you have this information for both your experiment and your control ru... |
I made this project to practice object-oriented programming. I have implemented operator+ and operator+=. The rationale behind struct cache are
I don't necessarily need to traverse the entire container to display the value.
Using a struct cache makes it possible to modify its value even in a const method
I also consi... |
I am on the way implementing my own STL-like library in C language. The main reasons are learning DS&A better, as well as the C language itself. Here I am trying to implement Vector (a.k.a. array-list) data structure. Would really appreciate to hear constructive criticism. Please, kindly give your thoughts on how the c... |
A codepoint in UTF-8 can be represented by one to four bytes. Given a codepoint, I need to determine the length (in bytes) of the codepoint if it were represented in UTF-8. For this, I've written the following function:
char utf8_char_size(uint32_t ch) {
if (ch < 0x80) return 1;
if (ch < 0x800) return 2;
if... |
I am learning JavaScript. Please review my code. Just created this Celsius & Fahrenheit Converter. Any suggestions to improve my code will be really helpful.
const celsiusToFahrenheit = document.getElementById('celsiusToFarhenhite');
const fahrenheitToCelsius = document.getElementById('farhenhiteToCelsius');
const conv... |
I had to create this method GetModelFormat and wanted to see if there is a better way to format the view model that is being return. I would be happy for any kind of feedback since this is quite critical a part of my application.
static void Main(string[] args)
{
try
{
List<carmake> ... |
I created a typing test app. I would love some feedback from you guys about my code so I can improve.
Here is github repo and hosted preview.
'use strict';
const block = document.querySelector('.words');
const inputBox = document.querySelector('.input');
let wordIds;
let wordsBlock = [];
let currentWord;
let wpm = ... |
Is there a better way of creating a nested dictionary than what I'm doing below? The result for the setdefault is because I don't know whether that particular key exists yet or not.
def record_execution_log_action(
execution_log, region, service, resource, resource_id, resource_action
):
execution_l... |
I've written some code which features Eric Elliot's javascript factory function mixin composition (https://medium.com/javascript-scene/javascript-factory-functions-with-es6-4d224591a8b1), but since there's no object field name associated with the class it doesn't seem like most other forms of composition I see. What wo... |
Problem: IPython's autoreload and superreload may reload modules such that obj=Obj() -> edit file & save -> isinstance(obj, Obj) == False. Sometimes even imp.reload of all involved modules doesn't absolve it.
Goal: a method with a 'fallback' on looser criterion that are as close to isinstance as possible.
Attempt:
def ... |
I wrote this code for a home task, and received some negative feedback. Though I really appreciated the reviewer, but I disagree when he said I use auto disorderly, and the algorithm is not optimal (I know it's not optimal, but comparing to the code that they expected which runs about 5 times slower than mine, it's rea... |
Solved one of the easiest problems from acm.timus.ru.
1001. Reverse Root
The input stream contains a set of integer numbers Aᵢ (0 ≤ Aᵢ ≤ 10¹⁸).
The numbers are separated by any number of spaces and line breaks.
A size of the input stream does not exceed 256 KB.
For each number Aᵢ from the last one till the first one y... |
I'm using a NodeJS script to do some geo calculations using the h3.js library by Uber. the concept of getting a nodejs script result back into php is new to me. I found the following example online, which I'm not following.
$output = [];
$arg = escapeshellcmd('some variable to pass on');
$command = 'node /var/www/hex/s... |
I have a set of template functions that have itrator types as template parameters, so can be used with any kind of iterators. std::find can be a good example.
Also I have a class that uses this function in its implementation and I don't want to expose my algorithms' header. Regarding the template function, inside my cl... |
It's me again, talented programming beginner fast-learner, so I have overcomed yet another self-imposed programming challenge, I have developped two algorithms to calculate occurrences of Friday the 13th between two given years(including the two inputed years) as said in title using PowerShell, one with built-in, the o... |
Required to splice specific element value in an array based on the condition.
Both the below code does the same job and yields the correct results. But couldn't figure out how to reduce coding structure with ECMAScript and which is performance oriented considering an array would have atleast 1.5k or even larger
This is... |
Spoiler: Advent of Code 2020 Day 8
Your flight to the major airline hub reaches cruising altitude without incident. While you consider checking the in-flight menu for one of those drinks that come with a little umbrella, you are interrupted by the kid sitting next to you.
Their handheld game console won't turn on! The... |
I'm working on a school project where I need to implement the pathfinding algorithm. The requirements are that it needs to find the path in at most a few seconds and ideally in less than 1 second. I've been trying to optimize my code to make the algorithm faster but it keeps taking a few minutes to find the path and I ... |
Simple code for getting documents that have a creationDate between two values in mongodb.
If the user provides only one of the values the code should still work and get the documents that have either a creationDate less than or bigger than the given value.
I'm mainly looking for more readability and simplicity.
interfa... |
The code determines if a number is prime or not, and there are some initial checks to rule out some values.
I would like feedback on how to speed up this program. I am really new to threads - might that be useful? I really don't know where to begin multithreading this code.
import java.io.*;
import java.math.BigInteger... |
I implemented a Stack in C++ using a dynamic C-style array. I tried sticking to the most important functions a Stack has to have to be usable. This is meant to only be for integers. I appreciate any suggestions on how to improve this. Here is my code:
Stack.h
#ifndef STACK_H
#define STACK_H
#include <cstdint>
#include ... |
About
This is a follow-up of a previous question Private VBA Class Initializer called from Factory. I've decided to create a new question instead of answering my old question because I would like the community to review and possibly suggest improvements on the new improved code.
VBA Class methods are always called with... |
As a beginner this is my first code. Any comments?
import numpy as np
import math
import matplotlib.pylab as plt
x=np.linspace(-360,360,45)*np.pi/180
plt.subplot(111)
_sin=plt.plot(x, np.sin(x),label="Sine Curve")
_cos=plt.plot(x,np.cos(x),label="Cos Curve")
#_tan=plt.plot(x,np.tan(x),label="Tan Curve")
plt.legend(['s... |
So I am using the latest version of Dapper and it works great for mapping my POCO classes but there are some scenarios where I need to return a DataSet instead of strongly typed classes back to my service.
Is this correct approach for repository pattern with Unit of work using ADO.NET in C# to authenticate user from da... |
I am fairly new to Python. I wrote a program to take the user inputs which are service, the top-up time, the top-up amount, and exit or stay on the program.
Please review my code. And, can my code be organized? I think it looks a bit messy, maybe it can be shorter?
First, I wrote everything under function, so I can re... |
I am a self-learned programmer and this is my first program. I would really appreciate any critique on my approach.
The program should automatically download the who data file to the folder these files are in.
file: who_report.py
# https://covid19.who.int/
# https://covid19.who.int/WHO-COVID-19-global-data.csv
# https:... |
I am sick of File Explorer's super slow deletion speed, so I tried to write a PowerShell script to make deletion faster, and while it does its job, its speed isn't as high as what I intended it to be.
I have written this:
Function Fast-Delete {
Param(
[Parameter(Valuefrompipeline=$True, Mandatory=$True)] [Strin... |
The following is a trimmed-down example of my actual code, but it suffices to show the algorithmic problem I'm trying to solve.
Given is a DataFrame with events, each with a user ID and a timestamp.
val events = Seq(
("1001", 1),
("1001", 2),
("1001", 3),
("1001", 5),
("1001", 6),
("1002", 1),
("1002", 3)... |
This is a solution for part 1 & 2 of Advent of Code 2020 Day 9.
Given the example input sample.txt:
35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576
Part 1: find the first number in the list (after the preamble) which is not the sum of two of the n numbers before it. n is the preamble.
For example... |
My aim was to provide functionality for a Flutter app on Windows to accept drag-and-dropped files.
Flutter apps are written in Dart and compiled to native code, but since this is a cross-platform framework there needs to be a native part - the runner app - which kickstarts the Dart part of the app.
So I changed the C++... |
I am currently working through the C# Yellow Book, as a first step in self directed learning. I'm supplementing that with C#8 In a Nutshell, and general searches of the Microsoft C# language references, StackOverflow etc. Working from multiple sources, however, results in sometimes conflicting coding best practices.
I ... |
Django implements a System Check framework that enables apps to perform checks on settings, runtime, etc. When creating an app, one can plug checks with the framework by following some requirements, one of them being how errors are reported.
The integrations are actually ok, but the error management system is a bit too... |
This is a follow-up question for A population_variance Function For Various Type Arbitrary Nested Iterable Implementation in C++. Thanks to G. Sliepen's answer, I am trying to implement the mentioned recursive_transform_reduce function here.
The usage description
Similar to std::transform_reduce, the purpose of recursi... |
I am new to Python, the script below provides the desired output and completes the task as required. I would like to know if there is any better ways of completing what I have written and any ways of speeding up the process?
Thank you for looking.
from netmiko import ConnectHandler
import sys
# **********************... |
Problem description: You are given a segment [568023; 569230]. Find integer within given range that has the most natural dividers. If 2 or more integers are found, return the lowest integer among them.
Solution:
def allnums(k):
cnt = 0
for i in range(2, k // 2):
if k % i == 0:
cnt += 1
r... |
I implemented the solution to the classic Matching Brackets problem:
Given a string containing brackets [], braces {}, parentheses (), or any combination thereof, verify that any pairs are matched and nested correctly.
The code should be correct since it passes several test cases.
I would like to know if:
the usage of... |
I made this project in my free time to try to crack a 4x hashed md5 with a couple of hints but I'm looking for ways I can optimize this algo because it's pretty slow and I know you could probs use threading or some other ways to increase speed.
If you can even point out some minor ways to increase performance I would b... |
I recently learned about classes in python. I only have a brief understanding of them, but I think it's good enough for me to write a tic tac toe program (been working on this for the last week or so). My title may be a little misleading (again, because I only have a brief understanding...) but I think you'll get the p... |
I wrote my first web app. Please let me know what I should improve. I want to write as clean code as possible.
App is about adding and removing tasks from list. Backend is written in Django, frontend in Sass and JavaScript.
Below my code for items view. Whole project can be seen in link:
Link to my code on GitHub
Demo:... |
Problem Statement:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except th... |
Follow up question from here.
I am working on a project where I need to do below things in Python:
Take few input parameters like - environmentName, instanceName, configName from command line.
Get JSON string as the response by calling service url. For example - Below is the JSON I will get:
{"flag":false, "configNam... |
Here I have a list which is months = ["Jan", "May", "Jul", "Aug", "Oct", "Dec"]
I want to do the following with this list
append months that are missing --->
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Delete months at index [2,5,9] from the list --->
months = ['Jan',... |
Check for Expiry
Expiry can go from 1 to 299
Expiry can be 1 digit, 2 digits or 3 digits
This will be the Input I check my regExp against.
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp276
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2] i0 exp82
Rewritet 192.168.3.99, 57714, 192.168.3.3, 22) [*0 2... |
I'm a beginner and I wonder if Is what I have created a good practice as a structure and way of working for input data processing?
Is the way I wrote the index.php file a correct and secure way of manipulation?
The majority of my programming experience (and I do mainly do it for fun) comes from following tutorials on g... |
I am trying to get my head around how MVVM pattern works. Would like to hear some reviews if I am implementing it correctly.
View
<Window x:Class="Login_App.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:... |
This is wrapper for POP3, POP3_SSL, IMAP4, IMAP4_SSL, SMTP and SMTP_SSL classes which let them work through proxies. For creating socket with proxy I've used PySocks.
Code:
from imaplib import IMAP4, IMAP4_SSL, IMAP4_PORT, IMAP4_SSL_PORT
from poplib import POP3, POP3_SSL, POP3_PORT, POP3_SSL_PORT
from smtplib import SM... |
I am a beginner in Python, and I made a Morse translator that converts letters to Morse, and Morse to letters (where a decimal point is 'dot' and underscore is 'dash'). Is there any way I could make my code shorter and more efficient? For reference, here's the translation of Morse to letter characters.
dot = '.'
dash =... |
My Code
import shutil
import os
from pathlib import Path
from datetime import datetime
DOWNLOAD_DIR = Path("/Users/my_name/Desktop/Zip Test/g_2020-12-10_3/")
ZIPPED_DIR = Path("/Users/my_name/Desktop/Zip Test/g_2020-12-10_3.zip")
ZIPPED_DIR.mkdir(exist_ok=True)
def make_archive(source, destination):
delivery_fi... |
Created a validation form in vanilla JS. Due to my little experience, I have a bunch of "if" here, I can not transfer the coordinates of Yandex.Maps to another function for validation, and it is still unknown what. With the coordinates, I "crutch" by saving them to an invisible div :-) I deleted my Api key, so I won't ... |
Hey I have the following code written in VBA. It simulates trajectory of asset price (BS_trajektoria_2 function) and calculate payoff from option, This procedure is repeated num_of_sim times to get better ressult (because asset price is random so payoff is random).I use it like this: barrier_MC(100;100;1;0,05;0,02;0,2;... |
I am trying to improve my code that involves a thread (threadA) handling some UDP communication and another thread (threadB) that works with the output of that communication.
My basic idea is to .push() new data into a std::queue within threadA.
threadB is looking for new data periodically - if it gets new data it proc... |
Problem Description
We are given 2 arrays: 1 array representing the image and containing the patterns to be match and another one representing the pattern. Each image is represented as an vector strings, where each element represents a line of pixels in the image, and each character represents a pixel.
The objective i... |
This question is about swapping bytes of an uint64_t value, or in other words, about converting between endianness of an integer value:
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
uint64_t& swapBytes1(uint64_t& num) {
using std::swap;
union {
uint8_t bytes[8];
... |
Presentation
Here is an implementation of some pre processing logic. The real use case is to apply online augmentation in a neural network context, that applies a chain of transforms on a pair (feature, ground_truth). I simplified in that example to chain transforms on a pair (a,b) Tuple[int,float], but the idea is si... |
I would really like feedback on this Loan System Calculator. My goal is to get better at OOP design and would like to know if I've done a good job in making this scenario OOP? Could I have structured it better? Should I have separated each loan type as a separate class using inheritance? I would like to know what I've ... |
Overview
Below is a simple program to estimate pi to the full precision of the provided type. It uses
Machin's formula, but this question is about coding style / choices. It compares the result to M_PI from <cmath> - best we have in C++17.
Questions
Is my use of enable_if_t appropriate and idiomatic?
Is the use of sta... |
This is my version of mergesort.
# mergesort
def merge(items, low, mid, high):
left = [items[i] for i in range(low, mid + 1)]
right = [items[i] for i in range(mid + 1, high + 1)]
left.append(4444444444444444444444)
right.append(4444444444444444444444)
i = 0
j = 0
for k in range(low, high +... |
This is a personal hobby project, I'm in control of all decisions made regarding my bot, but I can't change anything about the physics of the game (offline-only, and it's approved by the game devs - so don't worry!) I have a car, and the car is facing its target. All it needs to do is drive forwards, however, this is m... |
Introduction
1) Problem description:
Suppose you are managing files. You are given a text file, where in the first line are storage's volume of the server and the amount of users in total that is in the text file. Each line from the second to the end shows volume of individual user's storage. Based on the server's vol... |
This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. My code also includes a loop for the user to create their list.
def add... |
I wanted to save the a reddit thread to a .org file. I noticed that it is easier to use pandoc to convert .md to .org (esp when it comes to list items).
My code prints the output to the screen which can be redirected to the required file.
Process is as follows.
python reddit_download.py -u <url_to_download> > myfile.md... |
Some applications from vendors are allowed to be installed on multiple computers per user with specific
restrictions. In our scenario, each copy of the application (ID 374) allows the user to install the
application on to two computers if at least one of them is a laptop. Given the provided data, create a C#
utility th... |
So I'm supposed to calculate variance based on this forumula through functional programming:
$$\sigma^2 = \frac{\sum\limits_{i=0}^{n-1} (X -\mu)^2}{n-1}$$
This is the code that works:
public static double variance1(int[] array)
{
double mean=mean(array);
double summation=DoubleStream.iterate(0,idx->idx+1)
... |
I just finished a challenge (noted above) and I was wondering how good is this approach or is there some simpler solution that I am not aware of?
If you have a different solution, try to explain the code for people less experienced than myself rather just than pasting a solution.
Here is an example text file to be read... |
This is a follow-up question for A recursive_transform_reduce Function for Various Type Arbitrary Nested Iterable Implementation in C++, A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++, A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in... |
I'm trying to implement method chaining with classes, but struggle to make it without inner classes.
Specifically, I have three classes:
a class for different data loading
a class for computation of mathematical properties
I'm not sure how to implement exactly, but I have an intuitive structure in mind:
obj = Object(... |
I've following sqlite code using C api within Swift having a read and a delete operation for review.
For those not familiar with Swift, defer will execute after the end of the function.
Since I'm not closing the database connection and keeping it alive, I'm calling sqlite3_db_cacheflush(database) to flush out the chang... |
Inspired by Mike Boyd's 'Dopamine Box' video: link, I decided it would be a good project to pursue by myself in swift. The end goal is to make it look like the box in the video, with switches and a chrome exterior as well as being able to add custom icons underneath the switches.
My main question is: Have I laid out my... |
So I have made this Duplicate image scanner using powershell. It will operate using the SHA256 hashes of the files.
Any tips or suggestions on making this more dynamic/robust/efficient or adding new features would be greatly appreciatied!
$sig=@'
public static void ShowConsoleWindow(int state)
{
var handle = GetConso... |
So, I have made a BIG prank in VBScript.
First part is to prank with a Dummy HTA splash screen using an encoded PNG image inside it (Not included) and kill all windowed processes+explorer and keep it for a few seconds.
Then launch a internet explorer window in kiosk mode and launch fakeupdate.net according to windows v... |
Since I have just started Javascript, I am trying to solve a few problems and improve myself. I encountered such a question. I tried to do everything step by step from the question, but I do not think that my code is efficient. Can someone help me develop it?
Please code for a JavaScript function that accepts two argu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.