instruction stringlengths 71 95.1k |
|---|
I have this class to generate unique ids and random ids from those unique ids.
For the unique ids, it's a sequence of numbers between (start number = given number [start_seed]/or random number (0:1000000), and end number = start number + number of desired unique id -1) converted to string and hashed using md5 and conv... |
I recently wrote the following Java 1.8 snippet to generate a CLABE control digit based on the following subheading on the CLABE page on Wikipedia and I was curious on how it could be improved.
private void generateCLABEControlDigit() {
final int[] expectedResults = {0,1,2,3,6,0,0,0,0,3,7,8,9,5,9,1,7};
final St... |
I was playing around with ASP.NET Core 3.1 and tried to implement Dependency Injection flavor called Pure DI, i.e. without dependency container (even the built in one) to instantiate Controllers. You can see entire code here, but here's the rundown: I know I have to replace the default IControllerActivator but the main... |
I am writing a function inside of a React component to hide/show columns in a table. The table is generated from an imported config object containing objects which model the column data. We render by simply mapping over the table content and rendering cells based on the columns. The method I'm writing exists in the tab... |
I have been programming for a while, but I've only made games and less serious stuff. I want to get more serious. I would like some feedback on this class that defines a person. Structure, readability, use of static variables, etc. Please point out everything that can be improved.
public class Person {
private Str... |
This code maps a function over a dataset in parallel in a monitored fashion, and returns the result in the variable out.
import pandas as pd
import numpy as np
from tqdm import tqdm, trange
from joblib import Parallel, delayed
import multiprocessing
import math
n_jobs = multiprocessing.cpu_count()
df = pd.DataFrame(np... |
I am trying to build a generic query handler using the MediatR (v8) library. Let's jump to the code:
First of all I have an abstract query class like this:
public abstract class Query<TQueryResult> : IRequest<TQueryResult>
{
public Guid Id { get; } = Guid.NewGuid();
public DateTime Timestamp { get; }
prot... |
I recently worked on this problem that converts numbers to words. I was wondering if there is a better way to do it than mine, And I will really appreciate any reviews to my version of the solution and on how to make it better
/**
* Converts a given number into words
* @param {integer} , num, the number to be convert... |
I have designed a basic interface for a smart mirror I made. I coded it to include the time, date, and several phrases that refresh every 24 hours. The phrases are just some random quotes as examples.
I was wondering if there were anyways I could streamline this code or even improve the layout of the interface.
import... |
I've been building this program for around a week or two on my spare time because I'm slowly starting to figure out how to code better. This program generates a yearly 5/3/1 cycle that is exported to a CSV file so you can easily print it off if you want.
Below is my code:
/**
*
*/
package main;
import java.util.Sc... |
This code is used to select K for a K-nearest neighbor graph [KNNG] from a dataset with an unknown number of centroids (which is not the same as K-means clustering).
Suppose that you have a dataset of observations stored in a data matrix X[n_samples, n_features] with each row being an observation or feature vector and ... |
I have created a Modal, at the bottom of my CV to show various different resources and content creators that I have used to learn how to code, I have nearly finished this project and will be sending it out to companies maybe in the next few months. This modal animates in and out of the page by sliding down and blurring... |
Based on this article
And this question posted on the power bi forums
Objectives:
Resolve a hierarchy (parent - child relationship) in Power Query adding levels and their corresponding sorting columns.
The final result can be used in a Power Pivot table and use it to generate a dynamic P&L.
Key point was to add the sor... |
I created this console app that gets some JSON strings from a web request using a Parallel.For loop,
class Program
{
private static readonly object ConsoleLock = new object();
static void Main(string[] args)
{
//DECLARATION
var link = "http://www.mytestrequest.com/id="
int start = ... |
I am very new to PHP coding, hence just wanted to know if my coding is prone to any SQL injection attack or any other kind of threat. Below is the code for adding client to the database:
<?php
$response = array();
include 'db/db_connect.php';
include 'functions.php';
//Get the input request parameters
$inputJSON = fil... |
I'm currently trying to learn the basics of the Rust programming language, to do this my first piece of code after the classic 'Hello World' was a simple recursive Factorial function.
This is the code:
use std::io;
fn factorial(num: i64) -> i64 {
return if num == 1 {
1
}else{
num * factorial(n... |
I have just migrated from Python 2 to Python 3. I have written the following script to fetch all records of a table, ir_attachment, from PostgreSQL. After fetching all the records I check following points:
If an attachment record has no value for one of related_model, related_model_id or saved_file_name, then I append... |
I want my input to be any random numbers in any number of elements.
Examples:
Input: 1 2 3 4 1
Output: 2 3 4
Input: 4 3 5 2 5 1 3 5
Output: 4 2 1
Input: 5 5 2 6 7 7 9 9 3 3 4 1
Output: 2 6 4 1
from collections import defaultdict
n = int(input(""))
print("")
array = 0
def single_element(array, n):
table = def... |
My aim is to assign a color to each workday in a week. So if a user enters a day as a str, then I can know which color it should have.
Because colors and workdays are fixed, I make them as enum.Enum instance.
Is enum.Enum a proper choice for colors and workdays?
To link day and color, I choose dictionary for weekday_c... |
I made the following wrapper for the mediainfo command line. I did this mainly because mediainfo gives me more information than os.stat, specifically it gives me the Encoded date for .wma files, while the dates in os.stat don't represent the time the files were made, but rather the date the files were compressed (they ... |
I'd like feedback on my solution to the outlined (medium level) programming challenge. What might be a more efficient or Pythonic solution?
The challenge as outlined by Coderbyte:
[Run Length] (https://www.coderbyte.com/solution/Run%20Length?tblang=german)
Have the function RunLength(str) take the str parameter being ... |
I want to make a camera class with help of the Eigen library. The camera will be used to perform certain calculations or rather the values used to setup the camera will be used later on in multiple matrix calculations. The camera can be defined by the 9D vector and the near/far plane and width/height values alone.
Redu... |
The code below looks at different range values and then populates specific cells on a worksheet called GeneralInfo in the Worksheet_Activate event.The below code does work as expected, but its time to clean it up a little bit, so I am looking for some ideas. I have tried to split up the code with using smaller procedu... |
I'm trying to add error handling and response logging for API calls. The way I have my application (chatbot) set up is that a helper function is called from the main dialog, and that helper function calls the API. I believe this is standard practice. What I'm not sure on is how I should be catching errors in the proces... |
i need to improve the performance of ConcurrentDictionary.
for that i created 2 classes for check if the more efficiencies than the original.
public class FixedConcurrentDictionary<TKey, TValue>
{
readonly ConcurrentDictionary<TKey, TValue> _dictionary = new ConcurrentDictionary<TKey, TValue>();
public bool IsE... |
I am starting my adventure with Python and object oriented programming.
I wrote a script for salting and hashing password. My main goal is practice with OOP, not cryptography.
I know there is no error handling.
Wonder how improve my code it and make more object oriented.
It would be nice if someone more experienced c... |
I wanted to write my own code for md5 in javascript and learn its inner mechanics. (I know it is not trusted anymore, deprecated, ... but I'm just learning).
I didn't want to just copy the code that uses these like 60 repeated lines and over-complicated functions (like here), so I started writing my own implementation:... |
Well, I'm working with Selenium to scrape a webpage that has obfuscated class names (example <div class="example-gHJkLM">...)...
So I needed to create an extension method to get
public static ReadOnlyCollection<IWebElement> Descendants(this IWebElement element, bool hasChildren = false, int index = -1, string postAppen... |
I wrote this quick (lots of googling) and dirty (I hope not too dirty) script to download a URL list with a win32 wget port and save them as files with the url as the name to use as a "poor man's url cache" for another program.
It works (tested ~200k links), but I wonder if I did progress management right (it was a pow... |
I was tasked with writing a python script to check if a passed ID number exists within a file. The file I was give contains roughly 25,000 unique ID numbers. An ID number is a unique 9 digit number.
I have a couple specific things for you to comment on if you decide to review this:
As it stands, I convert the user_id... |
I am looking for a better way to minimize nested if statements in my MessageHandler.handleMessage method. I am looking to adhere to SRP and a function should do one thing and one thing well!
Any input would be greatly appreciated.
class MessageHandler():
""" MessageHandler - Handles twitch IRC messages and emits e... |
I am working on a simple personal project to build a Hoffman Tree. In my constructor, shown below, I am reading in a file, creating HoffmanNodes that represent each char in the file then I got through the file to encode it. I need to create a Scanner to go through the file once to find all the chars and their frequency... |
I'm attempting to speed up some python code that is supposed to automatically pick the minimum samples argument in DBSCAN. Currently the execution time grows exponentially as the number of training samples increases:
0.128999948502 seconds for 100 training examples
0.281999826431 seconds for 1000 training examples
11... |
I know that multiple functions are already available. However, I thought of writing my own because I wanted to learn the logic (and also because I thought there wasn't enough confusion :P). Please review the function I wrote and suggest me efficient changes.
Without further ado, here I go:
scan(string,size)
char** stri... |
What would be the "correct" way of transforming an array of objects into an object that contains an array?
Suppose I have this array that contains objects:
const paintings = [
{ painting: "Mona Lisa" },
{ painting: "The Starry Night" },
{ painting: "The Last Supper" },
{ painting: "Girl with a Pearl Earring" },... |
First I fetch an instance from the database. The three functions getSwitches, getSingle and getLinears need the return value instance.
When all requests are finished I want to fill the array barFrequencyData with the data.
How do I correctly refactor the code? Should I use async/await or promises in this case?
barFre... |
A few days ago someone asked this question. But they quickly deleted the post offering no solution.
Given:
a = ['COP' , '\t\t\t', 'Basis', 'Notl', 'dv01', '6m', '9m', '1y',
'18m', '2y', '3y', "15.6", 'mm', '4.6', '4y', '5y', '10', 'mm',
'4.6', '6y', '7y', '8y', '9y', '10y', '20y', 'TOTAL', '\t\t9.2' ]
They n... |
categories = [{id: "761601bc-4daf-4db2-a0cf-fe7f443fcb94", name: "Shoes"},{id: "601ebcfe-fcbd-4075-a4b4-a42e356c5747", name: "Hats"},{id: "238933cf-77a5-4443-b290-7d7c836f80ff", name: "Eyewear"}];
voucher = {id:1,categories:["761601bc-4daf-4db2-a0cf-fe7f443fcb94","601ebcfe-fcbd-4075-a4b4-a42e356c5747"]};
filterCatego... |
I am currently building cache for my application, and I would like to have my redis cache client work the same way you would dependency inject a DbContext.
I am using StackExchange.Redis to manage my redis cache:
https://github.com/StackExchange/StackExchange.Redis
I have made it work, but I am not very confident in th... |
I am learning programming with Python. I am not sure if I can write a try/except block like this.
import os
import shutil
try:
shutil.rmtree('c:/guna/newCAT1')
print("dir newCAT1 deleted")
except:
os.mkdir('c:/guna/newCAT1')
print("dir newCAT1 created")
fileIN=open('c:/guna/newCAT1/secretMSG.txt','... |
I'm taking on a project from a previous programmer. My goal is to make it a bit smaller and hopefully better. Originally the code has a bunch of length checks and Booleans as shown below.
C#
string[] splitStrArray = SNString.Split('-');
string part1 = splitStrArray[0];
string part2 = splitStrArray[1];
string part3 = sp... |
I have written a palindrome program. And I was just wondering if it correct? I checked using the words racecar and madam, and it says they are palindromes. I have also tested nonpalindrome words and it worked correctly.
Is my implementation correct? If it's not could you correct it for me. It it works correct, is there... |
Just looking for advice/thoughts on the overall AccountModal and how its written. looking to achieve better written, more legible, less repetitive code, more concise, cleaner etc...
AccountScreen.js:
import React from 'react';
import { StyleSheet, ScrollView, View, Dimensions, Image } from 'react-native';
import * as C... |
I'm trying to construct a simple database for use by 2 persons only (myself and other guy), right now, we're using excel table with 4 fields "requisition, origin date, request date and authorized date", but I want to take it to the next level :D. So, I'm building this small database app to emulate that, the file will b... |
Hi so like in my question,
i wrote some part of code for shopify to get recent orders for past 30 day
and i wondering if it is really readable, or maybe i schould change something?
I mean maybe there is a better way to achive same result.
Or maybe i schould use different names? change position for function?
$(document... |
I've designed a single-file safe integer library in C++. It catches undefined behavior prior to integer overflows or underflows and throws the respective exceptions. I intend this to be portable, to not rely on undefined behavior, and to rely as little on implementation-defined behavior as possible.
safe_integer.hpp:
/... |
Will you review the syntax, structure, and logic of my code. It can be tested using the main.
using iTextSharp.text.pdf;
using iTextSharp.text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AddCopyRightPDF
{
class Prog... |
This is a simple poker counter.
It lets players decide their actions and makes the currency calculations for them.
While adding a bit of console animation.
Can I achieve the same results with simpler code??
from string import ascii_lowercase
def get_player_names():
'''
Returns a List Of Playrer
Names Got ... |
With some effort I've managed to build a very simple (maybe too simple haha) navigation bar for a website.
Is it possible to make a transition on the dropwdown list from height:0 to some suitable height? I've tried and it seems not to be possible. No javascript for now
Any advice or extra tweak I could add? All is gre... |
I'm timing out on Codewars' Prime Streaming kata. Below is my code:
"use strict";
let _base = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71];
let _bufferSize = 1000
class Primes {
static get base() {
return _base;
}
static get bufferSize() {
return _bufferSize;
}... |
I'm very new to Haskell and I was trying to implement a DFT which is very imperative into Haskell and I wanted to get a feedback. More specially how can I avoid so many helper functions and I avoid limiting to Double everywhere. Thank you.
My DFT algorithm:
void dft(double[] inreal , double[] inimag, double[] outreal,... |
I'm new here and also into programming, I've made this small paper-scissors-rock project, and I would like to get it reviewed and know, how can I maybe:
simplify my code
make it perform better
using System;
using System.Threading;
namespace PaperScissorsStoneGame
{
class Program
{
static void Main(s... |
I'm in the process of implementing a fully generic service to filter out entries (of any type), which are contained in a ICollection.
As it is generic, without any constraints, the properties must be accessed through reflection.
I'm not fully happy with the performance, even though it respects the minimum response time... |
I use a change of groupbox locations depending on the number of weeks in the month. Is there any possibility for me to improve the functionality of this code a little bit, is it slow to load on this part?
Thank you all for your help.
FormWindowState LastWindowState = FormWindowState.Minimized;
private void ... |
I am a new python programmer.
I have created the code to put API data from pipedrive to Snowflake database.
Here are the steps in my code.
Delete the csv file if it exists.
Make an API call put all the paginated data in a list.
Create a csv file from the list.
Truncate the table in Snowflake.
Remove data from Snowfla... |
This method splits up two comma separated items, if they exist, and increments the amount if the are already in the list; otherwise add the item to the list
I want to know if this code can be optimized some more. Any suggestions?
The method below works 100% fine but I feel like it is not neatly done.
private void Seper... |
Could the aggregate functions after using grouping functions like groupby() and resample() be looped for cleaner code
____DateTime.____ | Steps | day_segment
2017-10-25 00:00:00| 4 | night
2017-10-25 00:01:00| 7 | night
2017-10-25 00:02:00| 10 | night
2017-10-25 00:03:00| 26 | night
.
.
.
2017-10-25 10:04:00| 80... |
Background
Apologies for "burying the lead." The questions are in the next section.
In my application, the purpose of inheritance is to abstract away complicated logic in the base class template, so that the writer of a derived class template doesn't need to worry about it. This logic, however, will depend on these sim... |
This if for a school project that is all about getting the most performance possible out of a relatively weak computer.
For this project we have received a weather station report generator that generates 8000 weather measurements per second. These measurements are split into groups of 10 stations resulting in 800 clust... |
I have an XML Parser in Java using WoodStox that I wrote. This parser is going to be parsing through extremely large files, could be 5+GB. The goal of the parser is to convert a nest XML file into a CSV. The XML file is going to be formatted in such a way where there will be a 'rowTag' that has the actual information t... |
What I have tried to accomplish with the code is to make some sort of partner budget where 2 people can have 2 separate budgets with separate expenses but which are still intertwined with eachother in some instances.
The code refers to the range A36:H160 and K36:R76. The first range being Fixed expenses and the 2. ra... |
Recently I was receiving Error 2015 when trying to use Application.Evaluate, then I realized it was because my formula was greater than 255 characters. As a workaround, I came up with this UDF:
Function AdvancedEvaluate(eformula As String)
ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Formula = eformu... |
Please could we examine the below code for anyway to put all console output in one statements?
#include <iostream>
using namespace std;
int main( )
{ //print("") in Python
cout<<"Hello " "everybody!"<<endl;
cout<<"My name is AK."<<endl;
cout<<"Goodbye."<<endl;
cout<<""<<endl;
//Poem
cout<<"Twin... |
I'd like feedback on my solution to the outlined programming challenge (medium level). I've tried it fast in any way I know how to, but, what might be a more efficient and/or pythonic solution?
[Letter Count II]
Have the function LetterCount(str) take the str parameter being passed and
return the first word with t... |
ERROR: type should be string, got "https://jsfiddle.net/0a7tcv2g/\nI know I could locally store the data, write in es6, and all that, but I wanted to learn to work with APIs, and really understand JS through ES5, before brushing up my ES6+ skills. I haven't finished adding all the small details yet, but thats trivial at this point. Just looking for feedback on my JS, and responsiveness of my site. (I know I used some es6, and could use const in some places instead of let).\nHTML:\n<!DOCTYPE html>\n<html>\n<head>\n<title>Pokedex</title>\n<link rel=\"stylesheet\" type=\"text/css\" \nhref=\"styles.css\">\n</head>\n<body>\n<h1 id=\"main-header\">Pokedex</h1>\n<div id=\"main-container\">\n\n</div>\n<script src=\"index.js\" \ntype=\"text/javascript\"></script>\n</body>\n</html>\n\nCSS:\n*{\nfont-family: Arial, Helvetica, San-serrif;\nmargin:0;\npadding: 0;\n}\n\nh1 {\nbackground: red;\ncolor: white;\nfont-size: 3em;\ntext-align: center;\n\n}\n\n#main-container {\nposition: absolute;\ndisplay: flex;\nflex-wrap: wrap;\nperspective: 625em;\n}\n\n.card-container {\nposition: relative;\ndisplay: flex;\ntransform-style: preserve-3d;\nflex-wrap: wrap;\njustify-content: center;\nalign-content: center;\nflex-basis: 31%;\nheight: 25em;\nwidth:18.75em;\nbox-shadow: 0.07em 0.07em 0.4em 0.13em \nrgb(40, 40, 40, 0.6);\nmargin: 0.4em;\ntransition: 1000ms;\nbackground: #0000ff;\nborder: 0.63em solid gold;\n}\n\n.frontFace, .backFace {\ndisplay: flex;\nflex-wrap: wrap; \nflex-basis: 31%;\nposition: absolute; \nheight: 100%;\nwidth: 100%;\nbackface-visibility: hidden;\ncolor: white;\n/*Temporary*/\ntext-shadow: -0.13em 0 red, 0 0.13em red, \n0.13em 0 red, 0 -0.13em red;\n}\n\n.backFace {\ntransform: rotateY(180deg);\nheight: 100%\nwidth: 100%;\n\n}\n\n.frontFace img, .backFace img {\nposition: absolute;\nmargin-top: 18%;\nmargin-left: 20%;\nbackground: white;\nborder: gold 0.19em solid;\nwidth: 60%;\nheight: auto;\n}\n\n\n\n.name{\nwidth: 100%;\ntext-align: center;\nfont-size: 1.5em;\noverflow:auto;\n}\n\n.frontName {\nfont-size: 1.5em;\ntext-align: center;\nmargin-top: 2%;\nwidth: 100%;\nmax-width: 100%;\n\n}\n\n.type {\nmargin-top: 70%;\nmargin-left: 66%;\n}\n\n.id {\nposition: absolute;\nmargin-left: 4%;\nmargin-top: 4%;\nheight: auto;\n}\n\nJS:\nconst container = document.getElementById('main-container');\n\nfunction getPokemon(callback) {\n const xhr = new XMLHttpRequest();\n const url = 'https://pokeapi.co/api/v2/pokemon/';\n\n xhr.onload = function() {\n if(xhr.status === 200) {\n const pokemon = JSON.parse(xhr.responseText);\n pokemon.results.forEach((poke, index)=>{\n\n let cardContainer = document.createElement('div');\n cardContainer.className = 'card-container';\n container.appendChild(cardContainer);\n let frontFace = document.createElement('div');\n frontFace.className = 'frontFace';\n cardContainer.appendChild(frontFace);\n let sprite = document.createElement('img')\n sprite.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(index + 1).toString()}.png`\n frontFace.appendChild(sprite);\n let backName = document.createElement('h4');\n backName.className = 'name';\n function capitalName(string) {\n backName.innerText = string.charAt(0).toUpperCase() + string.slice(1);\n }\n capitalName(poke.name)\n frontFace.appendChild(backName); \n })\n\n callback();\n }\n }\n xhr.open('GET', url, true);\n xhr.send();\n}\n\nfunction cardBack() {\n const endPoint = this.innerText.charAt(0).toLowerCase() + this.innerText.slice(1);\n const card = this.parentElement;\n const xhr = new XMLHttpRequest();\n\n xhr.onload = function() {\n if(xhr.status === 200) {\n if(card.childNodes.length === 2) {\n card.style.transform = 'rotateY(180deg)';\n }\n else {\n const details = JSON.parse(xhr.responseText); \n let backFace = document.createElement('div');\n backFace.className = 'backFace';\n backFace.addEventListener('click', ()=>{\n card.style.transform = ''\n })\n card.appendChild(backFace);\n let sprite = document.createElement('img')\n sprite.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${(details.id).toString()}.png`\n backFace.appendChild(sprite);\n let name = document.createElement('h4');\n name.className = 'frontName';\n name.innerHTML = details.name;\n let type = document.createElement('h4');\n type.className = 'type';\n type.innerHTML = details.types[0].type.name;\n backFace.appendChild(name);\n backFace.appendChild(type);\n let ids = document.createElement('h4');\n ids.className = 'id';\n ids.innerHTML = `#${details.id}`;\n backFace.appendChild(ids);\n card.style.transform = 'rotateY(180deg)';\n }\n }\n }\n xhr.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + endPoint, true);\n xhr.send();\n}\n\ngetPokemon(()=>{\n const cardFront = document.querySelectorAll('.frontFace');\n cardFront.forEach((card)=> {\n card.addEventListener('click', cardBack);\n })\n});\n\n" |
This is my first go at Django, so I'm looking first to learn how to make this more idiomatic. Also, is there a better way to set up my tests? To my HTTP status codes make sense?
chores/tests.py
import datetime
import json
from django.test import TestCase, Client
from django.urls import reverse
from rest_framework impo... |
Background
I was looking for a simple Event Broker or EventBus (whatever else keyword you can come up with) to use in a small(-ish) WinForms application. In Java I was using org.greenrobot.EventBus for a long time, but couldn't find a comparably established and simple solution in C# - everything looks to be enterprise ... |
Inspired by Wrapping IndexDB with RxJs.
(Edit - Added a Stackblitz example).
My use case is a simple, on-disk temporary cache. No errors are propagated, null values are returned instead. All errors are logged.
import { Injectable } from '@angular/core';
import { Observable, Observer, ReplaySubject, Subject } from 'rx... |
I'm creating a simple registration form for a Linux installation party I'm organizing.
Although I'm a decent programmer, I rarely create HTML files. I want to know if this form is safe for my users and if it will work on most devices. Am I following all the good web development practices? Is my code pure HTML5?
<!DOCTY... |
I have a common style (common.scss) and a text direction (RTL, LTR) option file (option-document-direction-rtl.scss, option-document-direction-ltr.scss). And by switching the reading of these files, the css file with RTL / LTR changed is output by method like gulp.js.
_common.scss
body {
max-width: 1120px;
backgrou... |
I was tasked to write process that initially seemed like a straight forward thing. "Fetch data from database, create a cache object, and assign this data to it. Use existing class to model this after." That's it in a nutshell. The 'existing' class did not do any caching, just an async call across layers to the database... |
I am brand new to writing hooks and I am having a little trouble getting my head wrapped around it. Initially, I wanted to write this with one event listener that passed the event and a separate param to distinguish itself from the other incoming arguments.
With hooks, I was confused as to how I should pass a separate... |
I'm implementing the following function for signed integer numbers: given endpoints of a closed interval lo and hi, and inputs x (in [lo..hi]) and dx, I'd like to compute the "reflected sum":
if x + dx is still in [lo..hi] then that's it; otherwise the underhanging or overhanging portion is "folded back" onto the resu... |
I have a dictionary where for each key, a single value is stored. Say
import pandas as pd
dd = {'Alice': 40,
'Bob': 50,
'Charlie': 35}
Now, I want to cast this dictionary to a pd.Dataframe with two columns. The first column contains the keys of the dictionary, the second column the values and give the colu... |
My program looks for the area of the figures, depending on the value of the variable а.
area -> triangle
area -> triangle2
area -> square
area -> rhombus
I want to get constructive criticism about the structure of the code and what can be redone. The program is written in the Python programming language.
while ... |
I have time-series data (t) that I want to loop through each t and take the difference of the previous five lags t-1 ... t-5.
This code works, but is inefficient. I'm not sure how to increase the performance and efficiency of the code.
Sample data
import pandas as pd
import numpy.random as nr
dat = pd.DataFrame({'t... |
Wrote some code to install bootstrap (latest) in a newly created rails application.
update: fixed a typo
yarn add bootstrap jquery popper.js expose-loader
yarn install --check-files
perl -pi.bak -e "s/extract_css: false/extract_css: true/" config/webpacker.yml
s1=$'\n\nimport "bootstrap/dist/js/bootstrap";'
echo "$s1" ... |
Let's take the famous fibonacci problem as an example but this is a generic problem. Also, taking scala as the language as it's rather feature-rich. I want to know which solution you'd prefer.
we all know that the following implementation is evil as it's not stack-safe:
//bad!
def naiveFib(n: Int): BigInt = {
if (n ... |
I wanted to get feedback on the correctness and efficiency of this post order traversal routine that my wife and I find really easy to grasp.
def postOrderTraversal(root: TreeNode):
curr = root
stack = []
while stack or curr:
if curr is None:
if stack[-1].right is None or popped == stack[-1].right:
... |
I made a preg_match to get my results and it works fine but I think it can be done with simple lines instead of repeating the code
$input = array('http://example.com/blue-bloods-s10e13-more-text/','http://example.com/charmed-2018-s02e11-more-text/','http://example.com/dynasty-2017-s03e11-more-text/','http://example.com... |
here is my first project : I have made a double pendulum animation with tkinter on Python. Can you give me some feedback on what can be improved ?
Thanks !
Code :
# General imports
import tkinter as tk
import random
import math as m
# Parameters
G = 9.81
class Pendulum():
def __init__(self, theta: float, theta_... |
I have the following piece of code:
$Page = str_replace('-&-', '-[+]-', $Page);
$Page = str_replace('&', '-[+]-', $Page);
$Page = str_replace('-and-', '-[+]-', $Page);
$Page = str_replace('-et-', '-[+]-', $Page);
$Page = str_replace('-und-', '-[+]-', $Page);
$Page = str_replace('-y-', '-[+]-', $Page);
$Page = s... |
So I'm writing a big server and I've made a simple start on console commands. I'm not sure if the way I'm doing it in is correct so I'd like to have it reviewed.
I have a class called ServiceCollectionExtensions where extension methods are defined that can be used on ServiceCollection. In there I have a function to reg... |
I'm basically wondering what the optimal method for returning to the top of src/main.rs::main() is?
Maybe something like this:
mod main;
pub fn main() {
crate::main();
}
Or maybe there's a keyword built in?
I want to handle certain kinds of errors by 'restarting the program'.
|
I am currently learning JAVA. I barely have any coding experience. I wrote a program which asks a user for a sentence. It then swaps the words of the sentence (first with last, second with second to last, etc.). Program will then output the new sentence.
I know that this is not the most optimal way this task could be ... |
The Task
A task I've been given recently is to design a data entry form which transfers data from the form to a table on a worksheet.
Depending on the answers given to various questions, other questions are displayed or hidden. For the most part I've achieved this by using different forms.
There is one route that requi... |
I would like to know if this is a good approach to finding out all the expressions within brackets. (I was actually asked to find out the smallest bracket expression, I have omitted the function to check for the smallest string and spaces within the expression).
s = "((a+b*d)*(x/2))*(1+(y+(x-2)/10))"
b = []
j = 0
b.app... |
I'm a novice in C++. I want to do three things:
Get the number of lines in the file
Get the number of total words in the file
Get each frequency of each "unique word".
Here, "unique word" is simply the same set of characters delimited by whitespace; different punctuation and casing are considered different.
I am usi... |
I wrote a Mandelbrot renderer in C++ that uses AVX intrinsics to calculate 8 pixels per thread in parallel. It can compute 1080p frames with 256 max iterations in about 40 milliseconds on a 2 core 4 thread i5-6200U laptop. Any advice on performance, code style etc would be appreciated.
https://github.com/voldemoriarty... |
I am practicing python, and in order to brush up my skill, I am trying the programming contest site AtCoder's past problems.
Daydream
Basically, you are given an input string and have to output YES if the string is constructed with choices of 4 different words ('dream', 'dreamer', 'erase', 'eraser'), otherwise NO.
I im... |
I am trying to solve the following problem:
Given three numbers, a, b, and c, return their product, but if one of the numbers is the same as another, it does not count. If two numbers are similar, return the lonely number. If all numbers are same, return 1.
I have the following solution:
def solve(a, b, c):
produ... |
This is the second iteration of this question
A note to start with: the first iteration of this question can be found here:
Editing system files in Linux (as root) with GUI and CLI text editors
As stated in there:
My intention is to POSIX-ly write one generalized function for running various text editors I use for di... |
I've been reading about thread pools in C++ for a few days now and decided to roll out my own. I mainly intend to use it to learn how to implement parallel algorithms at some point in the future but before that I have to know if there's something I can do to make it more efficient.
These are all the variables I'm using... |
hello guys i made a file watcher in rust using notify crate that watches a directory and if it detects file changes it will copy all of the files within the directory to another directory,i wanted you guys to do a code review, im a beginner in rust here is the code.
use notify::DebouncedEvent::{
Chmod, Create, Erro... |
Below is my attempt at bitmap in bitmap searching using 1bpp bitmaps.
Any suggestions on how I can reduce complexity and improve speed? Any comment is appreciated.
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Linq;
using System.Collections.Generic;
using System.... |
I have implemented the kaprekar's constant algorithm in c#, and I want your feedback.
Here is how the algorithm works:
it takes a number of 4 digits (e.g: 5823)
we order that number in ascendent and descendent order, which gives as two numbers (e.g: 8532 and 2358).
we subtract the larger number from the smaller numbe... |
I've written a little calculator in C++ for complex numbers:
#include <iostream>
using namespace std;
class ComplexNumber {
public:
double real;
double imaginary;
void add(ComplexNumber a, ComplexNumber b) {
//Just add real- and imaginary-parts
double real = a.rea... |
I have this piece of code written as a function to handle a button-toggle for sorting a list in ascending and descending order. Below is the code which is working as expected, but I would appreciate if someone knows a better, shorter and cleaner way of writing it.
// method called every time the button is clicked
/... |
As a learning exercise, I am writing a library to evaluate the complexity of an algorithm. I do this by seeing how long the alorgorithm takes for given inputs N, and then do a polynomial regression to see if the algorithm is best fitted by N, N^2, log(N), etc. I wrote Unit Test cases and they seem to work for N^2 and ... |
This is a follow up to this question and this question
Objective:
Manage what happens when users interact with Excel Tables (ListObjects)
Code incorporates:
Mathieu's suggestions:
ITables: Refactored interface and it's implementation
Tables: Hide SheetTables collection and exposed as a SheetTable(item) property
Tables... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.