instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
I have written a simple binary tree using structures and a couple of functions in order to add, search, find the minimum and maximum values, remove a node as well as destroy the node, the problem is that I have been using recursion and dealing with it in the same way and I am having a hard time trying to comprehend if ... | stackexchange/codereview |
I would value your opinion on the following piece of code. I am rather new to both Python and Monte Carlo analysis, so I was wondering whether the routine makes sense to more experienced and knowledgeable users.
import numpy as np
import scipy.optimize
from scipy.optimize import curve_fit
from scipy.stats import kde
d... | stackexchange/codereview |
This is an iterative review. The next iteration is located here: Utilities for Various Builtins #2
This code puts several builtins (And a few non-builtins) into the base classes.
const XtraUtils = {};
class Utility {
constructor(ofWhat){
this.utils = {};
this.aidsIn = ofWhat;
}
activate() {
... | stackexchange/codereview |
Recently, I added this class to my Spiky engine: its basic purpose is to allocate OpenGL-based objects (such as Textures, Shader, Fonts, ...) and then manage them by giving them an ID so the user can pull objects in and out. Any remarks, suggestions or other comments are welcome.
Resourcemanager.h:
#pragma once
#inclu... | stackexchange/codereview |
This is my first serious shell script, so it is probably horrible.
Problem statement
I decided to improve my profiling skills as so far they were mostly about hand-rolling counters and timers. After trying out better profiling tools and techniques I noticed that previously I was just rolling my face over keyboard until... | stackexchange/codereview |
At the moment I'd like recommendation where I can change and what I can use to improve on simplicity and modularity. If I'm practicing good naming conventions as to provide clean readable code. Any critique is much appreciated.
import time
import re
import requests
from bs4 import BeautifulSoup, SoupStrainer
import pa... | stackexchange/codereview |
I've created a simple hangman solver and although I'd consider myself proficient in webdev I am by no means an expert. The trick with this is that since HTTP is stateless, I can't really think of a better way to look words up than to start from scratch each time (and lookup is performed with ajax EVERY time the input c... | stackexchange/codereview |
I am taking beginner steps into DE and was tinkering with writing an ingestion script which does the following tasks:
Reads data from a source (in this case a remote parquet file)
Writes it to local for now, this can be changed to a remote location like s3 or other any database.
For this task I chose to use NY taxi d... | stackexchange/codereview |
Context:
The following code is used to look up a setting values based on multiple layers of configuration within the application. For any given setting (ie: default printer), the application can be configured at the following levels in order of precedence.
Operation
Material
Workstation & Program Combination
Workstati... | stackexchange/codereview |
I wrote the following hexdump generator function. How can I improve it?
FMT = '{} {} |{}|'
def hexdump_gen(byte_string, _len=16, n=0, sep='-'):
while byte_string[n:]:
col0, col1, col2 = format(n, '08x'), [], ''
for i in bytearray(byte_string[n:n + _len]):
col1 += [format(i, '02x')]
... | stackexchange/codereview |
I wrote a utility class called ObservingCache, which receives a task in the form of Supplier<T> and an interval, computes the task every [interval] millis and allows its result to be queried via the getItems() method.
I'm using for making sure that outside resources (such as configuration files or DB tables) are always... | stackexchange/codereview |
this is a follow up of:Text based game “Hunt the Wumpus” Version 2
this code was used as a base to turn this game into a gui game with fltk: Hunt the Wumpus GUI (FLTK)
I took the suggestions made there and corrected the code. I think now it got a lot more simple.
Please let me know if you still find something smelly i... | stackexchange/codereview |
I'm trying to make a good MVC model using annotations, which I will use it in a large scale GUI project. I want to respect the maximum of rules and guidelines, and be able to decorrelate every parts of the MVC. The code must be beautiful, testable and maintainable. I wrote a sample project to show you my model. What do... | stackexchange/codereview |
I have an use case where I want to see how many slots have been used for a date in a restaurant. The slot can be deducted based either number of diners or per booking.
Also I have to cater a case where a booking is made for multiple dates and then i have to consider those dates as well when checking how many slots have... | stackexchange/codereview |
I have a list of Comment objects comments. Each Comment has several properties, one of which is the date the comment was posted. I've sorted this list by date and there is at least 1 comment per date in a range.
I would like to loop over comments and for every date, create a new list of comments just for that day. Howe... | stackexchange/codereview |
We started programming in school this year. I wasn't expecting to learn much but the pace is really slow so I tried to learn some things myself. I decided to do a little project for a start and that is a simple snake game. I would like to know what I am doing bad ( I know about the lack of consistency in naming ) or if... | stackexchange/codereview |
I build this silly app to get the commenters' information on some PR, mostly for learning how to use API's and for improving my JS dom skills.
Although it is working, it's mostly spaghetti code and very disorganized, so I am sure there is a lot of room for improvement.
I would like to get some feedback on how to better... | stackexchange/codereview |
I am new to C++ and this is my first program. The objective of this program is to fully complete the sequence called the Collatz conjecture.
It concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows: if the previous term is even, the next... | stackexchange/codereview |
I wanted to bind a single hot key to open and close gnome-terminal in a way similar to terminal emulators such as tilda or guake. I use Ubuntu, and have configured this script to be executed when I press the key F1
The script will focus or minimize the first gnome-terminal window that is running.
If no gnome-terminal i... | stackexchange/codereview |
I built a workbook to help me extract data from a MSSQL database into Excel. I realize that this is fairly easy to do with Microsoft SQL Server Management Studio, but I can't easily get that installed on my machine at work, so I first have to remote to the server every time to get any data, which becomes a mission if y... | stackexchange/codereview |
The following code fragment constructs different types of neural networks outputs based on the options supplied. Currently, my code just has a huge note that describes what all the options are supposed to do. I wanted to learn how I can make this code less complex or perhaps break its complexity into simpler pieces. An... | stackexchange/codereview |
Regular timers in JavaScript (setInteval & setTimeout) have two problems:
They aren't as much accuracy as you can get in JS. If you set it like this:
setInterval(fn, 1000);
You can't be sure that it will be called every 1000 ms. It'll be called 1000 + 1-10ms or even more if some heavy tasks were before the tick.
This... | stackexchange/codereview |
Because I don't want to download an entire library for a single function (which I do understand, was made better than I made mine), I decided to implement my own string formatting function.
I am not very proud of it, as I find it pretty ugly and unreadable.
This is only a string formatter with string-only arguments.
... | stackexchange/codereview |
This is my implementation of AVL tree, it works fine. is there any thing that can be improved about addition and deletion procedures specifically when deleting the root,
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct treenode node;
struct treenode
{
int value;
int height;
node *le... | stackexchange/codereview |
Interactive Wandbox example
Inspired by this Stack Oveflow question, I've implemented a function that, when called with a desired arity, a callable object, and a variadic amount of arguments, calls the passed callable object forwarding the passed arguments in groups of the desired arity.
Example:
auto printAll([](auto.... | stackexchange/codereview |
I am by no means proficient at being able to take mathematical concepts and converting them to code. I was wondering if you guys could look at it and make suggestions on how I could fix it or if my thinking is correct on these. I used a combination of the wikipedia pages for each of these as well as http://theory.stanf... | stackexchange/codereview |
I'm new to Java and I want to know if this code is efficient, and if there a shorter and faster way to reverse a string.
package Excercises;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter ... | stackexchange/codereview |
So I created a thread server that creates threads and associates them with a handle so that you can keep specific threads for specific tasks e.g. run all graphics rendering on thread 0, run physics stepping on thread 1 and use thread 2 for downloading a file of the internet etc. Personally I've found it useful in a pro... | stackexchange/codereview |
I am very (very) new to programming, and today I (semi-)successfully wrote my first program that performs very basic things.
My hope is that I can receive some constructive criticism around how I structured it all and if I am doing things in the most efficient and proper way possible for what I am trying to achieve.
#i... | stackexchange/codereview |
This is a Python script I made to download a URL from the clipboard.
When a new URL is copied to a clipboard it adds the URL to a download queue, then on a separate thread it downloads the URL to a file.
I am new to multithreading. Is my script properly using multithreading? It needs to download the data while still ... | stackexchange/codereview |
I have recently discovered that in type theory there is a concept of a "predicate type" which is a type \$A\$ formed out of all members of the underlying type \$U\$ that satisfy a given predicate function pred :: u -> Bool. I wondered if we can do that in Haskell, so I took this library for primes and decided to make a... | stackexchange/codereview |
There are solutions e.g.
list.OrderBy(item => Math.Abs(number - item)).First()
or
list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y);
which are O(N) at best.
The solution bellow should be faster than a sequential scan on a large list. It is more performant to sort the list first (O(NlogN)) and t... | stackexchange/codereview |
The program adds two binary numbers in two' s complement ignoring the overflow for a constant size of bits. I am trying to generalize the program by taking input from the user in a single line without memory wastage. Is there any way to achieve this?
#include<iostream.h>
#include<conio.h>
void main ()
{
const int ... | stackexchange/codereview |
I am a newbie in the scientific computing in python. The function I am trying to calculate is the response of the wave equation for a given source term (For reference, See: Equation 11.67 in https://webhome.phy.duke.edu/~rgb/Class/phy319/phy319/node75.html).
$$\phi(\pmb{x},t) = \int_V G_+(\pmb{x}, t; \pmb{x'}, t)\rho(... | stackexchange/codereview |
Previous: Advent of Code 2020 - Day 1: finding 2 or 3 numbers that add up to 2020
Next: Advent of Code 2020 - Day 3: tobogganing down a slope
Problem statement
I decided to take a shot at Advent of Code 2020 to exercise my Rust knowledge. Here's the task for Day 2:
Day 2: Password Philosophy
[...]
To try to debug the... | stackexchange/codereview |
So I have some code here:
First a simple random # generator and a array-choosing function:
function Rand(min,max)
{
return parseFloat(Math.floor(Math.random()* max-min+1)))+parseFloat(min);
}
function Choose(arr)
{
//Returns an element from an array at random.
return arr[Math.floor(Math.random()*arr.length)... | stackexchange/codereview |
Previous: Advent of Code 2020 - Day 1: finding 2 or 3 numbers that add up to 2020
Next: Advent of Code 2020 - Day 3: tobogganing down a slope
Problem statement
I decided to take a shot at Advent of Code 2020 to exercise my Rust knowledge. Here's the task for Day 2:
Day 2: Password Philosophy
[...]
To try to debug the... | stackexchange/codereview |
Write a Greeter class with greet function that receives a name as input and outputs Hello <name>. The signature of greet should not change throughout the kata. You are allowed to construct Greeter object as you please.
greet trims the input
greet capitalizes the first letter of the name
greet returns Good morning <na... | stackexchange/codereview |
Having a general utility function to see if the input is empty makes sense to me. Empty means different things depends on the type. I just spent ~5 minutes writing this one up, so I'm sure it's missing edge cases, and maybe I'm approaching the whole problem incorrectly.
Function
function isEmpty(input: any) {
switc... | stackexchange/codereview |
I did this library to help me from one of my projects and decided to publish it on GitHub hoping people might find it useful, convenient and easy to use in their projects too.
It's a header-only library. The library design is inspired by some popular Java code conventions, like naming of classes and the popular usage o... | stackexchange/codereview |
I am currently building a web app where I need to randomly switch the font and color of a title (inside the #content div) and the background of the page every time a button is clicked.
I wrote the following code that works perfectly, but I'm wondering if it could be optimized (or at least written in a more elegant way... | stackexchange/codereview |
I'm writing a script that can grep the rows and columns from a text file that match a regex. I have an implementation but I'm looking to make it more elegant.
input.tsv
a b c d
a 2 9 6 1
b 6 4 7 0
c 3 7 2 0
d 5 ... | stackexchange/codereview |
I'm new to Scala and I'm trying to write a generic function to convert from Int to any scalar.
For example:
val res: Float = convertInt[Float](12)
val res: Double = convertInt[Double](12)
//etc
I've achieved the following code:
trait FromIntConverter[T]{
def apply(int: Int): T
}
def convertInt[T](int: Int)(... | stackexchange/codereview |
I wrote a script using Python that gets data from several sources (news sites, Twitter, Yahoo), puts it into a dict and then formats it as a string to be sent through email.
I wonder if there is possibility to write the code more neatly in a shorter way. Maybe I'm doing some steps that are a bit unnecessary and maybe f... | stackexchange/codereview |
I am a jQuery beginner and would like some pointers on whether the following code could be made shorter, or there is a better way to get the same result.
jQuery(document).ready(function(){
var aa=jQuery('#navigation-wrapper');
var bb=jQuery('#top');
jQuery(window).scroll(function(){
if(jQuery("b... | stackexchange/codereview |
I am currently in a challenge with my buddy to see who can code a simple paint program in the least lines. The only requirement, is that the program must include an eraser. How can I possibly shorten this code, while still using proper, beautiful syntax?
import sys, pygame
from pygame.locals import *
pygame.init() #Sta... | stackexchange/codereview |
I am looking to make a generic config file using variables such as:
$PLACEHOLDER_USER
Then after moving the file into the correct position I want to replace every instance of *$PLACEHOLDER_VARIABLE* into the value of $VARIABLE from my settings.sh file.
In the example below *"$PLACEHOLDER_USER"* in log.conf would be re... | stackexchange/codereview |
This question is a spiritual successor to Console class that handles multiple buffers. I was mostly interested in implementing one of the suggestions of using an iterator range and fixing the interface for Terminal. That means most of the code will be absent. Also, while the code above is intended for a freestanding en... | stackexchange/codereview |
I have a table of users, where each user has a group (or multiple groups) he/she is part of.
Currently I'm handling the users group via a Users class:
<?php
/**
*
* User (class) Model: Handles users (not system users).
*
*/
class User{
/*=================================
= Variables =
====... | stackexchange/codereview |
I have a script that alphabetizes the layers in Adobe Illustrator. It does so by sorting the layers in an array (using string names) and then using that to change the item order position (zOrder) of the layers. The script runs fine, however if there is a very large layer (which I deal with a lot) of over 8000+ it gets ... | stackexchange/codereview |
Note: Yes. It's big. I'm not expecting commensurately
long/detailed answers (though if anyone wants to write one, you'll definitely be receiving a substantial bounty). This class is going to be used a lot in my
VBA development so any reviews at all would be immensely helpful.
Even if it's just a typo somewhere o... | stackexchange/codereview |
require([
'jquery',
'underscore',
'backbone'
], function ($, _, Backbone) {
'use strict';
// TODO: Would like to access through define module, but not sure how..
var player = chrome.extension.getBackgroundPage().YouTubePlayer;
var user = chrome.extension.getBackgroundPage().User;
// ... | stackexchange/codereview |
Here's my assignment:
Write a program that takes a filename as its only command line argument and prints the results to std::out formatted as follows:
The first line of the output should be whether or not the checksum passed ("Checksum passed", "Checksum failed")
If the checksum passed, the rest of the file will cont... | stackexchange/codereview |
I am currently working with an app that should load various info on a very specific zip file which contains the XML config file, using the DotNetZip library on C#, here's the code:
public static void InitializeData(string configFilePath)
{
if (File.Exists(configFilePath))
{
using... | stackexchange/codereview |
This is my React component for looping a component i.e. I don't want to use MAP or FOREACH in React Component's HTML.
import React from 'react';
/**
* @param {items} from props
* @description -> Works with array of items and render only one children object inside it, ith data object will be available in children com... | stackexchange/codereview |
Release 1.1 of Rubberduck only had a handful of implemented code inspections, more as a proof of concept than anything else. For release 1.2, we now have 19 implementations of our IInspection interface - here is what happens when the user clicks the refresh button on the Code Inspections toolwindow:
private void Refre... | stackexchange/codereview |
I have recently built a plain old Ruby program using TDD with RSpec to model this. I wanted to get feedback.
Repo
For the company whose application we’re looking at, order processing
looks something like:
If we accept an order over the web, then we have to wait for payment
to arrive, unless it’s a credit-card orde... | stackexchange/codereview |
crustaceans!
This is my attempt at creating an all_pairs operation for rust iterators. The code has to generate a new iterator which, when iterated, produces all pairs of elements from each iterator, so for example:
assert_eq!(
vec![1, 2].iter().all_pairs(vec!['a', 'b'].iter()).collect::<Vec<_>>(),
vec![(&1, &'... | stackexchange/codereview |
This is my first nontrivial multi-threaded program. It recursively searches through a tree (haystack) to find the leaf where needle = true. It implements a thread pool and allows threads to exit early when another thread finds the answer.
It's worth noting that when using more than the main thread the program runs ~30 ... | stackexchange/codereview |
I have successfully placed multiple jquery ui slider on a page and its transalation text too. you can check it live on:
http://outsourcingnepal.com/projects/jQuery%20slider/
I have my jquery code as :
var arrLabel1 = new Array('Not Good', 'OK', 'Average', 'Above Average', 'Excellent', 'Outstanding');
$(function() {
... | stackexchange/codereview |
ERROR: type should be string, got "https://github.com/speedrun-program/load-extender\nThis is the previous post: C++ programs for Windows and Linux which let you lengthen the time it takes to access files REVISED VERSION\nTo compile this, you need to download and include robin_hood.h, and on Windows you also need to install EasyHook.\nI tried to add everything mentioned in the answer there except using an obj / o file because I read that you have to include something twice if it’s used in both files, so it seemed like it would make the size a lot bigger because the file for robin_hood map is big. I also would have had to put some of the functions in their own file because I want them to be compiled without printf calls unless it’s the testing program. And I also couldn’t figure out how to get it to work, the main file couldn’t see the things from the other file. But I’ll try again to get it to work if someone says it would still really be a good idea.\nI made this because it helps us save non-load time in a speedrun.\nI want this to be revised as well as possible because I don’t have Mac OS, so I need to ask someone else to compile it for that OS. So I want it to be written as well as I can get it so I won’t have to ask people to compile it multiple times due to revisions.\nclass_and_functions.h:\n#include <stdint.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <atomic>\n#include <vector>\n#include <exception>\n\nclass delay_sequence\n{\npublic:\n std::atomic<std::size_t> index;\n std::vector<std::chrono::milliseconds> delays;\n bool repeat;\n bool reset_all;\n\n delay_sequence() { index = 0; repeat = false; reset_all = false; }\n delay_sequence(const delay_sequence& copy_sequence)\n {\n index = copy_sequence.index.load();\n delays = copy_sequence.delays;\n repeat = copy_sequence.repeat;\n reset_all = copy_sequence.reset_all;\n }\n delay_sequence& operator=(delay_sequence copy_sequence)\n {\n index = copy_sequence.index.load();\n delays = copy_sequence.delays;\n repeat = copy_sequence.repeat;\n reset_all = copy_sequence.reset_all;\n return *this;\n }\n};\n\n// find out how much space to reserve for delays vector\nstatic std::size_t setup_delay_sequence(delay_sequence& current_sequence, std::wstring& line, std::size_t start_position)\n{\n std::size_t delay_sequence_length = 1;\n for (std::size_t line_position = start_position; line_position < line.length(); line_position++)\n {\n if (line[line_position] == L'/')\n {\n ++delay_sequence_length;\n }\n else if (line[line_position] == L'-') // no more delays past reset point\n {\n --delay_sequence_length; // the last slash was before the reset point, so it won't go in the vector\n if (delay_sequence_length == 0)\n {\n current_sequence.reset_all = true;\n break;\n }\n current_sequence.repeat = true;\n break;\n }\n }\n return delay_sequence_length;\n}\n\n// this will let the user write something like \"1,500\"\nstatic void remove_non_digits(std::wstring& delay_substr)\n{\n std::size_t position_to_write = 0;\n for (std::size_t i = 0; i < delay_substr.length(); i++)\n {\n if (isdigit(delay_substr[i]))\n {\n delay_substr[position_to_write] = delay_substr[i];\n ++position_to_write;\n }\n }\n delay_substr.erase(position_to_write);\n}\n\nstatic void set_delays(std::vector<std::chrono::milliseconds>& delays, std::wstring& line, std::size_t delay_sequence_length, std::size_t slash_position)\n{\n static bool too_big_delay_seen = false; // static so function will remember if it already printed the message in a previous call\n delays.reserve(delay_sequence_length);\n unsigned long long max_delay = std::chrono::milliseconds::max().count();\n while (slash_position != std::wstring::npos && delays.size() != delay_sequence_length)\n {\n std::size_t next_slash_position = line.find(L'/', slash_position + 1);\n std::wstring delay_substr = line.substr(slash_position + 1, next_slash_position - slash_position - 1);\n remove_non_digits(delay_substr);\n if (delay_substr.length() == 0) // no numbers were written\n {\n delays.push_back(std::chrono::milliseconds(0));\n slash_position = next_slash_position;\n continue;\n }\n try\n {\n unsigned long long delay_time = std::stoull(delay_substr);\n if (delay_time > max_delay)\n {\n throw std::out_of_range(NULL);\n }\n delays.push_back(std::chrono::milliseconds(delay_time));\n }\n catch (const std::out_of_range& oor)\n {\n if (!too_big_delay_seen)\n {\n printf(\"delay time can only be %llu milliseconds\\n\", max_delay);\n too_big_delay_seen = true;\n }\n delays.push_back(std::chrono::milliseconds(max_delay));\n }\n slash_position = next_slash_position;\n }\n}\n\nstatic void set_key_and_value(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& line)\n{\n std::size_t slash_position = line.find(L'/');\n if (slash_position == std::wstring::npos) // no slash so no delay sequence so line isn't valid\n {\n return;\n }\n std::size_t position_before_whitespace = line.find_last_not_of(L\" \\t\\f\\v\\r/\", slash_position);\n if (position_before_whitespace == std::wstring::npos) // the entire file name was whitespace\n {\n return;\n }\n std::wstring file_name = line.substr(0, position_before_whitespace + 1);\n delay_sequence current_sequence;\n std::size_t delay_sequence_length = setup_delay_sequence(current_sequence, line, slash_position + 1);\n set_delays(current_sequence.delays, line, delay_sequence_length, slash_position);\n my_rh_map[file_name] = current_sequence;\n}\n\nstatic bool rh_map_setup(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)\n{\n std::size_t line_count = 1;\n std::wstring line;\n std::wifstream my_file;\n my_file.open(\"files_and_delays.txt\");\n if (my_file.fail())\n {\n printf(\"couldn't open files_and_delays.txt\\n\");\n return false;\n }\n while (std::getline(my_file, line) && line_count < SIZE_MAX)\n {\n ++line_count;\n }\n if (line_count == SIZE_MAX)\n {\n printf(\"can't store %zu delays\\n\", SIZE_MAX);\n return false;\n }\n my_rh_map.reserve(line_count); // overestimates slightly due to extra newlines and starting at 1\n my_file.clear();\n if (!my_file.seekg(0, std::ios::beg))\n {\n printf(\"seekg on files_and_delays.txt failed\\n\");\n return false;\n }\n line.clear();\n while (std::getline(my_file, line))\n {\n set_key_and_value(my_rh_map, line);\n line.clear();\n }\n my_file.close();\n return true;\n}\n\nstatic void delay_file(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& file_name)\n{\n rh::unordered_flat_map<std::wstring, delay_sequence>::iterator rh_map_iter = my_rh_map.find(file_name);\n if (rh_map_iter != my_rh_map.end()) // key found\n {\n printf(\"%ls successfully found in hash map\\n\", file_name.c_str());\n delay_sequence& found_sequence = rh_map_iter->second;\n if (found_sequence.reset_all) // reset all delay sequences\n {\n for (auto& it : my_rh_map)\n {\n it.second.index = 0;\n }\n printf(\"all delay sequences reset\\n\");\n }\n else\n {\n if (found_sequence.repeat) // reset delay sequence\n {\n if (found_sequence.index.load() > 0 && found_sequence.index.load() % found_sequence.delays.size() == 0)\n {\n printf(\"%ls delay sequence reset\\n\", file_name.c_str());\n }\n found_sequence.index = found_sequence.index.load() % found_sequence.delays.size();\n }\n if (found_sequence.index.load() < found_sequence.delays.size())\n {\n // this is defined in the main file so it won't sleep if being used with load_extender_test.exe\n #ifdef THIS_IS_NOT_THE_TEST_PROGRAM\n std::this_thread::sleep_for(found_sequence.delays[found_sequence.index.load()]);\n #else\n unsigned long long total_milliseconds = found_sequence.delays[found_sequence.index.load()].count();\n unsigned long long total_seconds = total_milliseconds / 1000;\n short remaining_milliseconds = total_milliseconds % 1000;\n printf(\"sleep for %llu second(s) and %d millisecond(s)\\n\", total_seconds, remaining_milliseconds);\n #endif\n found_sequence.index += 1;\n }\n else // delay sequence already finished\n {\n printf(\"%ls delay sequence already finished\\n\", file_name.c_str());\n }\n }\n }\n else // key not found\n {\n printf(\"%ls not found in hash map\\n\", file_name.c_str());\n }\n}\n\nload_extender_test.cpp:\n#include <chrono>\n#include <thread>\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\nnamespace rh = robin_hood;\n\n#include \"class_and_functions.h\" // included here so robin_hood alias can be used\n\nstatic void print_rh_map(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)\n{\n printf(\"\\n---------- hash map current state ----------\\n\");\n for (auto& it : my_rh_map)\n {\n printf(\"%ls / \", it.first.c_str());\n delay_sequence& sequence_to_print = it.second;\n for (std::size_t i = 0; i < sequence_to_print.delays.size(); i++)\n {\n // casted to unsigned long long to get rid of warning message\n // visual studio on windows wants %lu, but gcc on linux wants %llu\n printf(\"%llu \", (unsigned long long)sequence_to_print.delays[i].count());\n }\n if (sequence_to_print.reset_all)\n {\n printf(\"RESET_ALL \");\n }\n else if (sequence_to_print.repeat)\n {\n printf(\"REPEAT \");\n }\n printf(\": INDEX %zu\", sequence_to_print.index.load());\n printf(\"\\n\");\n }\n printf(\"---------------------------------------------\\n\\n\");\n}\n\nstatic void test_all_inputs()\n{\n #ifdef _WIN32\n std::wstring path_separator = L\"\\\\\";\n #else\n std::wstring path_separator = L\"/\";\n #endif\n std::wstring test_path;\n std::wifstream input_test_file;\n input_test_file.open(\"test_input.txt\");\n if (input_test_file.fail())\n {\n printf(\"couldn't open test_input.txt\\n\");\n return;\n }\n rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n bool setup_succeeded = rh_map_setup(my_rh_map);\n if (setup_succeeded)\n {\n print_rh_map(my_rh_map);\n while (std::getline(input_test_file, test_path))\n {\n printf(\"testing path: %ls\\n\", test_path.c_str());\n // +1 so separator isn't included\n // If separator isn't found, the whole wstring is checked because npos is -1\n std::wstring test_file = test_path.substr(test_path.rfind(path_separator) + 1);\n delay_file(my_rh_map, test_file);\n print_rh_map(my_rh_map);\n test_path.clear();\n }\n }\n else\n {\n printf(\"setup failed\\n\");\n }\n input_test_file.close();\n}\n\nint main(int argc, char* argv[])\n{\n printf(\"\\ntest start\\n\");\n test_all_inputs();\n printf(\"test finished, press Enter to exit\\n\");\n std::wstring input;\n std::getline(std::wcin, input);\n return 0;\n}\n\nload_extender.cpp\n#include <chrono>\n#include <thread>\n#ifdef _WIN32\n #define NOMINMAX // allows std::chrono::milliseconds::max().count();\n #include <Windows.h>\n // easyhook.h installed with NuGet\n // https://easyhook.github.io/documentation.html\n #include <easyhook.h>\n#else\n #ifndef _GNU_SOURCE\n #define _GNU_SOURCE\n #endif\n #include <stdio.h>\n #include <dlfcn.h>\n#endif\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n #define THIS_IS_NOT_THE_TEST_PROGRAM\n#endif\n\n#ifdef THIS_IS_NOT_THE_TEST_PROGRAM\n #define printf(fmt, ...) (0)\n#endif\n\nnamespace rh = robin_hood;\n\n#include \"class_and_functions.h\" // included here so robin_hood alias can be used\n\n#ifdef _WIN32\n static NTSTATUS WINAPI NtCreateFileHook(\n PHANDLE FileHandle,\n ACCESS_MASK DesiredAccess,\n POBJECT_ATTRIBUTES ObjectAttributes,\n PIO_STATUS_BLOCK IoStatusBlock,\n PLARGE_INTEGER AllocationSize,\n ULONG FileAttributes,\n ULONG ShareAccess,\n ULONG CreateDisposition,\n ULONG CreateOptions,\n PVOID EaBuffer,\n ULONG EaLength)\n {\n static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n static bool setup_succeeded = rh_map_setup(my_rh_map);\n if (setup_succeeded)\n {\n std::wstring file_path = ObjectAttributes->ObjectName->Buffer;\n // +1 so '\\' isn't included. If '\\' isn't found, the whole wstring is checked because npos is -1\n std::wstring file_name = file_path.substr(file_path.rfind(L\"\\\\\") + 1);\n delay_file(my_rh_map, file_name);\n }\n return NtCreateFile(\n FileHandle,\n DesiredAccess,\n ObjectAttributes,\n IoStatusBlock,\n AllocationSize,\n FileAttributes,\n ShareAccess,\n CreateDisposition,\n CreateOptions,\n EaBuffer,\n EaLength);\n }\n\n extern \"C\" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo);\n\n void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) {\n HOOK_TRACE_INFO hHook1 = { NULL };\n LhInstallHook(\n GetProcAddress(GetModuleHandle(TEXT(\"ntdll\")), \"NtCreateFile\"),\n NtCreateFileHook,\n NULL,\n &hHook1);\n ULONG ACLEntries[1] = { 0 };\n LhSetExclusiveACL(ACLEntries, 1, &hHook1);\n }\n#else\n FILE* fopen(const char* path, const char* mode)\n {\n static auto original_fopen = reinterpret_cast<FILE * (*)(const char* path, const char* mode)>(dlsym(RTLD_NEXT, \"fopen\"));\n static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n static bool setup_succeeded = rh_map_setup(my_rh_map);\n if (setup_succeeded)\n {\n // finding part of path which shows file name\n std::size_t file_name_index = SIZE_MAX; // overflows to 0 and checks entire path if no slash is found\n std::size_t end_index = 0;\n for (; path[end_index] != '\\0'; end_index++)\n {\n if (path[end_index] == '/')\n {\n file_name_index = end_index;\n }\n }\n std::wstring file_name(&path[file_name_index + 1], &path[end_index]);\n delay_file(my_rh_map, file_name);\n }\n return original_fopen(path, mode);\n }\n#endif\n\nload_extender_injector.cpp (only used on Windows, LD_PRELOAD and DYLD_INSERT_LIBRARIES can be used on Linux and Max OS):\n#include <tchar.h>\n#include <iostream>\n#include <string>\n#include <Windows.h>\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n\nvoid get_exit_input()\n{\n std::wcout << \"Press Enter to exit\";\n std::wstring input;\n std::getline(std::wcin, input);\n std::getline(std::wcin, input);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n WCHAR* dllToInject32 = NULL;\n WCHAR* dllToInject64 = NULL;\n LPCWSTR lpApplicationName = argv[0];\n DWORD lpBinaryType;\n if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))\n {\n std::wcout << \"ERROR: This exe wasn't identified as 32-bit or as 64-bit\";\n get_exit_input();\n return 1;\n }\n else if (lpBinaryType == 0)\n {\n dllToInject32 = (WCHAR*)L\"load_extender_32.dll\";\n }\n else\n {\n dllToInject64 = (WCHAR*)L\"load_extender_64.dll\";\n }\n DWORD processId;\n std::wcout << \"Enter the target process Id: \";\n std::cin >> processId;\n\n wprintf(L\"Attempting to inject dll\\n\\n\");\n\n // Inject dllToInject into the target process Id, passing \n // freqOffset as the pass through data.\n NTSTATUS nt = RhInjectLibrary(\n processId, // The process to inject into\n 0, // ThreadId to wake up upon injection\n EASYHOOK_INJECT_DEFAULT,\n dllToInject32, // 32-bit\n dllToInject64, // 64-bit\n NULL, // data to send to injected DLL entry point\n 0 // size of data to send\n );\n\n if (nt != 0)\n {\n printf(\"RhInjectLibrary failed with error code = %d\\n\", nt);\n PWCHAR err = RtlGetLastErrorString();\n std::wcout << err << \"\\n\";\n get_exit_input();\n return 1;\n }\n else\n {\n std::wcout << L\"Library injected successfully.\\n\";\n }\n\n get_exit_input();\n return 0;\n}\n\n" | stackexchange/codereview |
This takes in an array of data built from a source workbook, builds a set of "flags" based on the data in each row of the array. Then it creates a new finalRng array that will, based on a set of logic from the business, create new rows based on the data.
I think there are a ton of ways to accomplish what I am looking ... | stackexchange/codereview |
The goal is to find \$f(n,r)\mod(m)\$ for the given values of \$n\$, \$r\$, \$m\$, where \$m\$ is a prime number.
$$f(n,r) = \dfrac{F(n)}{F(n-r) \cdot F(r)}$$
where
$$F(n) = 1^1 \cdot 2^2 \cdot 3^3 \cdot \ldots \cdot n^n$$
Here is the Python code snippet I've written:
n_r = n - r
num = 1
den = 1
if ... | stackexchange/codereview |
This class is for calculating the shortest path in a 2D World (without minding obstacles).
I'm using the A* algorithm and 2D Vectors (from the SFML Framework).
It is working but takes (a lot of) time for higher amount of coordinates.
It takes 4 seconds to calculate the path from one edge of the map to the other.
Exampl... | stackexchange/codereview |
I was given a this problem at a technical interview and failed miserably in the time given. Afterwards, I sat down and worked out what I think is a good solution. The task was actually to build an AngularJS app to do this, which I did, but the guts of my solution is in JavaScript. I wanted to ask if there is a better w... | stackexchange/codereview |
Our company needs a localization/translation behavior which allows incomplete (ResX) resources.
If a String
isn't available in italian
fall back to the next roman language, like french
fall back to our invariant (in this case: german)
The easiest approach was a custom CultureInfo.
/// <summary>
/// A <see cref="Cultu... | stackexchange/codereview |
I've created a code that works but takes time to run.
Is there any way of making this code work in a more efficient way?
In short terms I want to:
make a new copy of sheet 1 and 2
Select the row with the lowest value in sheet 1
Paste this row in sheet 3, and select item-number, rownumber and OP-number from this row
De... | stackexchange/codereview |
So I have decided to learn Kivy Framework. Did two small apps containing mainly just labels (so that doesn't count) and decided I am going to do a simple music player. Nothing fancy just to learn basics. Right now after learning a few things I already know I should do it a different way. Nevertheless, I kindly ask abou... | stackexchange/codereview |
I have written the following function to be a general "error logging" solution for my Windows API projects. Basically, given a Windows system error code (a la GetLastError()), it will log the error message into a file:
#include <Windows.h>
#include <strsafe.h>
// MAX_PATH for file name, 12 for max signed int in base 1... | stackexchange/codereview |
using Microsoft.AspNetCore.WebUtilities;
using System.Security.Cryptography;
namespace UserManager.Cryptography
{
public class UrlToken
{
private const int BYTE_LENGTH = 32;
/// <summary>
/// Generate a fixed length token that can be used in url without endcoding it
/// </summ... | stackexchange/codereview |
I am trying to convert a SQL Server stored procedure to Pyspark code.
This is my SQL Server query:
WITH A (ID, CHILDMSF, PARENTMSF, TOPPARENT, TYPE, QUANTITY) AS
(
-- Base case: Select distinct rows from #BO satisfying the condition
SELECT DISTINCT
ID,
CAST(CHILDMSF AS ... | stackexchange/codereview |
Created the following method:
public static int max(int[] array) {
int max = Integer.MIN_VALUE;
for (int value : array) {
if (value > max) {
max = value;
}
}
return max;
}
Question(s):
I believe the Big O Notation for this implementation is O(n), am I right?
Since this is ... | stackexchange/codereview |
Inspired by a SO post, just as an exercise, I tried to implement a way of notifying a consumer of a class about whether a property on an object has changed or not. I'm not attempting to use this in anyway, but I would like to learn from it.
interface INotifyPropertyChanged
{
function PropertyChanged($name);
fu... | stackexchange/codereview |
Note: I do know that Python libraries provide Binary Search Tree. This implementation has been done to practice python, and data structures and Algorithms.
This is a implemented Binary Search Tree, feel free to make any suggestions about syntax, logic, or simply anything that you think i should become aware of.
Methods... | stackexchange/codereview |
I've created a private function called _successResponse to handle successful responses from my promise.
The challenge was passing the dispatch function to the _successResponse which is being passed to the .then method as a callback.
I accomplished this by currying using .bind. I would love to get feedback on this appro... | stackexchange/codereview |
I'm having trouble to implement the following requirement in a functional way in scala. Given a predefined number of boolean flags, I want to build up a collection of numbers. For each (true) flag, a hardcoded number should be included in the collection.
This is the unsatifying solution I have so far:
def createCodeA... | stackexchange/codereview |
See this this question for background. This is a live filter where results are filtered as you type. I've taken into account Kerri's answer and expanded on her recommendation. I've added a message that appears if no results are found, and a display for how many results are being displayed out of the original set. You c... | stackexchange/codereview |
It's a simple bash script but I'm hoping for feedback, advice and examples on how to improve the script and code. Can you guide me how to put more checks in the code and more if possible?
This code:
Sets IFS variable and backs it up
Sets a trap for signals that can kill the script and a trap for exit to do run a clean... | stackexchange/codereview |
I have been working on a project for several days. It is a command line program for viewing files in hexadecimal. It is usually very fast, but is there any way I could make it more efficient?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
if(argc == 2){
FILE *in = fopen(argv[1], "... | stackexchange/codereview |
I have an entity with opening and closing times and I have to list timetable in HTML label.
Times can be empty.
Ugly attribute names getHorarioMIni or getHorarioTFin cannot be changed due external DB relations and the auto-populating methods.
How to optimize this function:
public String getTimetable() {
final St... | stackexchange/codereview |
I was writing a game in Swift and Sprite Kit and it is very simple. It works perfectly other than the fact that it gets a bit laggy sometimes. I'd like to use this experience as both a learning tool, and to get the 'lagginess' resolved. My code is relatively short, actually:
import SpriteKit
import UIKit
import Foundat... | stackexchange/codereview |
We were asked to implement a program that calculates the number of Fermat witnesses and liars for odd numbers greater 1. This involves Fermat’s little theorem.
Fermat’s little is used to identify whether a possible prime number is composite. It’ll find a number/numbers called Fermat witness then. The other numbers are ... | stackexchange/codereview |
I am refactoring my existing product's webapi part of the solution. Current Repo pattern does not allow me to add custom functions to a specific repository. In result, most of the functions directly use the Db context in the controller.
I read various articles and come up a good way of implementation to achieve my targ... | stackexchange/codereview |
I have written an EmailSession class to connect and get (unread) mail messages. It is all working, but I would like to see your opinions on any enhancements or improvements, as I understood there are lots of bad examples on the Internet and I copy-pasted most of it together.
One issue I already noticed:
If there is no... | stackexchange/codereview |
I have this piece of code in my service layer and registers and student for a course.
As you can see if have alot of if statements and i was wondering if any could suggest a nicer way of writing this code?
public async Task<bool> RegisterStudentForCourseAsync(RegisterStudentForCourseRequest registerStudent)
{
... | stackexchange/codereview |
I would like to have this code reviewed. I am learning C++ from a C background. How would I improve this code to make it more C++ like? This is a simple program that I wrote, which is a stripped down version of the actual full program I'm writing.
#include <iostream>
using namespace std;
class Doge{
public:
Doge(... | stackexchange/codereview |
I'm a very inexperienced VBA user, I've just created my first "For Each" loop but it's very slow. I'm happy that it works but eager to know if there is a alternative method that is quicker. Any advice would be appreciated but please bear in mind my inexperience!
My routine takes two variables "UserSelectionMin" and "... | stackexchange/codereview |
After the last post had some minor improvements for me and the beta release was actually used for some things, I decided that the GUI was too ugly to continue like this and rewrote the whole GUI in JavaFX.
The Matrjoshka - Usage
This posed some challenges for MVC / MVP, because of some peculiarities with JavaFX Views a... | stackexchange/codereview |
I'm just starting to learn using both dependent types and proof assistants, and as an exercise I'm trying to write a provably correct merge sort. As a first step, I'm writing a function that merges two non-decreasing lists (this is easy) along with a proof that it produces a non-decreasing list (this is the hard part I... | stackexchange/codereview |
Still learning JS and I made the following function to convert degrees into cardinal directions respectively. My first iteration of the code was over 50 lines and I was able to get it down to 13 using a for loop.
Is there a way to optimize or simplify the code down even more? Is my logic and implementation ideal?
https... | stackexchange/codereview |
What
Beam search is a best-first search algorithm that does not necessary find an optimal path, yet has smaller memory-footprint. In this program, I attempted to answer a question how does it compare to A* and whether bidirectional beam search provides any improvement over unidirectional variant what comes to running t... | stackexchange/codereview |
Just wanted to seek some advice on how can I speed up this PHP form. My batch file that calls this form is for every 1 second but it seems something in my code does the slowing.
Is there any way to speed up the process of this PHP file?
<?php
// Connect to the database (host, username, password)
$con = mssql_connect('M... | stackexchange/codereview |
According to this question, I have made an agreement with Peter Cordes to create such a question here.
I think that I should prepare the tutorial using the modern technologies as the Continuous Integration (hereinafter referred to as "CI").
Here is the public repo (branch tests) and here is the successful CI-build wit... | stackexchange/codereview |
I've wrote some simple code to load a JSON file from the Twitter Streaming API, parse the data, and create relationships between users based on who mentions or retweets who. My ultimate goal is to have a file that I can load into a network analysis program to analyze.
I wrote the code to first look for a retweet, and ... | stackexchange/codereview |
I've created some methods to help me convert PDF to text and then text to a JSON object. I've never done this before and I'm using this exercise as a way to improve my knowledge of Ruby.
The following code does what I want, it works. It just returns a very ugly object. Right now I'm trying to craft some regular expres... | stackexchange/codereview |
I'm looking for some JavaScript code improvement and optimization. Is it possible to optimize this block of code (for example, remove double array loop)?
replace: function(ex, str) {
var arr = str.match(/{add_([A-Z]+)}/gi);
if (arr && arr.length) {
arr.each(function(e){
var id = e.r... | stackexchange/codereview |
Let's say you want to increment the cells around the position (x,y) in a square matrix m of size T.
I've written the same code in a few languages. Here's the JS syntax version :
if (x>0) {
if (y>0) m[x-1][y-1]++;
m[x-1][y]++;
if (y<T-1) m[x-1][y+1]++;
}
if (y>0) m[x][y-1]++;
if (y<T-1) m[x][y+1]++;
if (x<T-... | stackexchange/codereview |
I have to create a modularized program that can find out the diameter, circumference, and area of a circle's radius. I'm sure many of you can notice I kind of winged this from a example given from my teacher. Instead of people pointing out the fact that I coded this wrong, could you please give me reasons for what I sh... | stackexchange/codereview |
I'm trying to do some basic math comparing some course groupings to completed courses. The original code shown below seems huge and maybe not pythonic?
I'm trying to write better view code then what I currently have. The reason? I want to improve and secondly, I'm checking manually for each and every course. There has ... | stackexchange/codereview |
I am parsing an XML file and trying to get the guid of a node where it has an attribute "name" and a value of "Name" like so:
<property name="Name" guid="7eca00b3-38e0-f0e8-9b72-2b822b21de6b" />
string propertyGuid = propertyList.Where(x => x.name == "Name").FirstOrDefault()?.ToString();
if (propertyGuid == (object)nu... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.