instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
Wrapper: internal static class Cache { private static ObjectCache InternalCache { get { return MemoryCache.Default; } } private static T CacheOrGetExisting<T>(string key, Func<T> valueFactory) { T value; object uncastedValue = InternalCache.Get(ke...
stackexchange/codereview
In Swift I have a string where a dash needs to be inserted after every 3 characters, if there are 4 characters or 2 characters at the end of the string they should be shown as "-xx-xx" or "-xx" respectively. E.g "203940399345" to "203-940-399-345" "2039403993454" to "203-940-399-34-54" "20394039934546" to "203-...
stackexchange/codereview
After a lot of back and forth on various sites, reading articles, watching videos etc i still can not figure out the best way to secure my admin section. The session id is regenerated every page reload / action to make session hijacking / fixation more difficult. Let me know in the comments if you need any more details...
stackexchange/codereview
I made a program which simulates taking an order for 3 meals and a dessert. It's like those packaged food companies you see on Instagram. It asks for a name, and then goes on to ask what they want for each mealtime and stores their orders in a dictionary. I defined two functions; they help out a lot and make it much ea...
stackexchange/codereview
I've written this simple code, that is possible to find on my github profile (it simply downloads some twitter data and store in an excel file). It is one of my first experiments of using OOP in python: the code works (does its tasks as intended) but maybe an OOP implementation is not explicitly needed in this case. ...
stackexchange/codereview
I am in the process of learning Java and going through the Euler problems. For Problem 4 I decided to also implement a TDD approach with JUnit. My questions are: Is there a better TDD approach to this problem? I wrote out all these test cases initially. Some obviously pass and some fail initially because I'm checking...
stackexchange/codereview
I've been recently fooling around with Go(lang) and ended up doing a (very) simple pig Latin parser. I'm pretty sure this is not the best solution out there (no punctuation and only lowercase letters) but it does its job. However, I'd be delighted to learn how this could be improved, as I'm still pretty new to Go. Here...
stackexchange/codereview
For me as a complete newbie to the world of C++, getters and setters are a rather confusing topic. There seems to be a wide range of opinions on what constitutes a sound use of getters and setters. In this particular post I'm most interested in finding a good way of using getters and setters in a memory-safe way. I hac...
stackexchange/codereview
I'm in the process of improving my coding style and performance hence I decided to delve into bit manipulation on Hackerrank. I thought the question was straight forward but on large input, my solution's performance declines. How do I improve it? Any smart tricks to solve the below question is welcome as well. Below is...
stackexchange/codereview
I'm a beginner developer, and it's my very first project: a simple math operations calculator in Python 3 using Tkinter for GUI. Obs: This code is an evolution of my previous code of the same project: initial code. This calculator, in despite of only process the four basic math operations (add, subtraction, multiplicat...
stackexchange/codereview
So I have tried to implement a doubly-linked list in C++. My implementation includes some basic methods (although I know there could be many more), an iterator class and an overwritten << operator. I know the code is quite big, but I would really appreciate any comments on functionality, style or anything else you thin...
stackexchange/codereview
I am new to programming and I would like some feedback. This is my first ruby program that simply adds a + b. I know it's probably more complicated than it needs to be, but I wanted to implement ideas that I was learning. Is there anything that I should do that I didn't or did that I shouldn't? puts "<<<-----ADDITI...
stackexchange/codereview
I am unsure if my use of Monitor.Wait and Monitor.Pulse is correct. It seems to work alright, but there is a nagging doubt I am doing something wrong. Am I dealing with a timeout OK, or is there a better way to do it? All examples I have seen use Monitor.Wait with a while loop, and not with an if to re-check the blocki...
stackexchange/codereview
This searches within three search engines. I would like if you could tell me any ways to make this better: function google() { var good = document.getElementById("theStuff").value; window.location.href = 'http://www.google.com/search?q=' + good; } function yahoo() { var good = document.getElementById("theStuff...
stackexchange/codereview
This is a Python script I wrote to reboot the router every 600 seconds. Why did I do it? Well, in case you don't know, I live in China, and I use VPNs to browse the international internet. My ISP frequently interrupts my VPN connection, don't ask me why, they really have no better things to do. So I have to constantly ...
stackexchange/codereview
I implemented a generic Deque<T> data structure. Please, review this implementation. Deque.java: import java.util.Iterator; import java.util.NoSuchElementException; class Deque<T> implements Iterable<T> { private class Node<T> { public Node<T> left, right; private final T item; public Node(T item) { ...
stackexchange/codereview
It's taking 2.4 MB of memory and 20 ms. It's my solution for Two Sum problem on LeetCode. How can I make it better using closures and other stuff? Kindly review the code. use std::convert::TryInto; impl Solution { pub fn two_sum(nums: Vec<i32>, target: i32) ->Vec<i32> { let mut status:bool = false; ...
stackexchange/codereview
For my rags-to-riches submission, I've decided to improve this code: Text-based RPG game using classes However, I've decided to start off with something different. The original code is more interactive, but mine just runs automatically. I may consider making my code the same, but I wanted to try this first. I think ...
stackexchange/codereview
Problem I keep trying to use various todo lists. But I keep coming back to the same situation; not having an active todo list. This can come in two forms: I don't have a habit to open bespoke software. I've tried using Excel, notes and calendars as they're close to my current work flows. But I tend to always forget ab...
stackexchange/codereview
I wrote the following prototype: import xlsxwriter import numpy as np import pandas as pd import random import uuid workbook = xlsxwriter.Workbook('test.xlsx') worksheet = workbook.add_worksheet() companyissuearray = ['3001', 'Test1', 'TestCat1', 'TesSubtCat1'], ['3002', 'Test2', 'TestCat1', 'TesSubtCat1'], ['3003', ...
stackexchange/codereview
I have been working on a script for almost a month now, which takes in an XML file and uses it to either download or upload files from an ftp site. It also copies the files to a history directory for historical purposes. This thing has to be flawless so any suggestions to make the script more stable, reliable, error fr...
stackexchange/codereview
Type a number \$n\$. Then calculate \$f(n)\$, where $$ f(n) = \begin{cases} n-10 & \text{if}~ n > 100\\[1.5ex] f(f(n + 11)) & \text{otherwise} \end{cases} $$ The output must show all the computations, such as $$f(99) = f(f(110)) = f(100) = f(f(111)) = f(101) = 91$$ Is there a shorter and better way I can solve this? #...
stackexchange/codereview
I use ImageMagick to crop image, encapsulate the related code to functions. Here is the code: convertc2(){ convert $1 -crop $2 "two.png" } converto3(){ Delimeter="placeHolder" if [[ $2 == *"x"* ]]; then Delimeter="x" else Delimeter="X" fi First="${2%$Delimeter*}" Fourth="${2##*+}" Lhs="${2...
stackexchange/codereview
I have a method, that checks win conditions on a "Torus" board, which is a board without any borders. This means that if you place 4 diagonal stones on the top left, and 2 diagonal stones in the bottom right, if they are in the same diagonal and would connect if you ignored the border, which then would lead to a win. ...
stackexchange/codereview
I am very much a beginner (only if/else, for, while, slice etc) and I wrote Hangman game. I needed to put in there code saying "let’s transform the player's guess to lowercase one every time he inputs an uppercase letter". What do you think of my code? var words = ["fish", "monkey", "pioni", "agreable"]; var randomWo...
stackexchange/codereview
I tried my hands on Rock-Paper-Scissors. But the twist is that the game has a brain that aims to learns your behaviour. The brain is a simple counter that updates the player's current choice based on players previous choices. The level determines the number of previous choices cpu will remember. In any event the player...
stackexchange/codereview
What this code is basically supposed to do is find how many even divisors a number has. For example the number 100 has the divisors 1, 2, 4, 5, 10, 20, 25, 50, 100 of which 6 (2, 4, 10, 20, 50 and 100) are even. So we output 6. The first line of input is supposed to be the number of test cases (t). And for each of th...
stackexchange/codereview
My code below returns a JSON data based on user's input or query in my HTML page or template. However, I need to modify or do some tweaking with my JSON data in order for me to use it in my datatables plugin. I am using underscore.js to reconstruct the JSON data. def brgy_info(request): if request.method == "GET": ...
stackexchange/codereview
This URL shortener is just for my own use and it runs on my local machine. I created this for fun and I doubt if I would ever use it in production. Is my script any good? shortener.php <?php require_once 'lib/db.php'; function random_string($length, $charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234...
stackexchange/codereview
This is the controller I created for my MVC framework, and I think I finally got it right. Anything I can do to make the code more efficient? Is this how a MVC controller is supposed to look like? abstract class Controller { protected $requestHandler; public function __construct(RequestHandler $rh, $action) ...
stackexchange/codereview
Currently, I am interested in programming. I have programmed a calculator in C. Everything works, but I do not feel completely confident in my solution. Are there any logic or efficiency issues with my code? Supported operations: \$+\$, \$-\$, \$*\$, and \$/\$. Algorithm: Flowchart main.c #include "practice.h" int ma...
stackexchange/codereview
This is my implementation of recursive merge sort, using sentinels: #include<stdio.h> #include<stdlib.h> #include<limits.h> void merge(int a[], int p, int q, int r) { int n1,n2; int i,j,k; int *l,*m; n1 = q - p + 1; n2 = r - q; l = (int*)malloc(sizeof(int)*(n1+1)); m = (int*)ma...
stackexchange/codereview
I'm currently creating a small server back-end. My goal is to write an (efficient) packet parser in C++17 using the command pattern. The packets are given by: type: value in {0, 1, 255} size: value in {0, 1, 65535} data: array[size] Each packet is processed by a packet_operator. The packet_registry is a packet_operato...
stackexchange/codereview
This code is meant to sort a list of integers in place using quick sort. I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview. def quicksort(l): quicksort_helper(l, 0, len(l)-1) def quicksort_helper(l, lo, hi): if lo >= hi: ...
stackexchange/codereview
This program opens a file and prints the text out to the terminal 1 character at a time and at a predetermined speed using time.sleep() Simple and maybe, if you think like me, pretty cool.. GitHub from time import sleep import sys BLINK = 0.2 chars_in_line = 50 def open_file(fn): with open(fn, "r") as f: ...
stackexchange/codereview
I've two working ways to do so, but which one should I use? Common part: var textarea = document.getElementById("textarea"); First way: function updateStatusBar() { var text = textarea.value; statusBar.value = "Words: " + (text ? text.match(/\b\S+\b/g).length : "0") + " Characters: " + text.replace(/\s/g...
stackexchange/codereview
I'm trying to achieve, for lack of a better term, a "view" pattern in C++. It's probably most comparable to "views" in the Database world, where one can make a query, and then perhaps aggregate the data, or turn otherwise interact with it without actually duplicating the data. I've tried to reduce it down to a simple e...
stackexchange/codereview
Challenge from LeetCode: Array Partition I Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the max...
stackexchange/codereview
I was helping someone on SO with an assignment to create a macro that accepts an SQL-like syntax, and optionally sorts and filters a collection. I realized that while their instructor is insisting on them using macros, macros aren't actually required at all. I decided to try my hand at creating a function that solves t...
stackexchange/codereview
Expression trees are the bread and butter of functional programming but when it comes to adding additional information to an established tree it can be difficult to incorporate such changes without breaking the existing interface. I have attempted to solve the problem with this example which demonstrates two different ...
stackexchange/codereview
Imagine I have connection in which I have to write numbers, represented by this contract: interface ISocket { Task WriteAsync(Byte[], Int32 offset, Int32 count, CancellationToken cancel); } There is one single thread calling this WriteAsync method. Till now each caller to ISocket was buffering independently and kn...
stackexchange/codereview
I'm a beginner-intermediate C++ programmer, and I never used or understood C input & validation. I just always used C++ streams. Anyway, I just want code critique, as I have never used the C input functions (I admit, I have used and like printf()! I even made my own sprintf(), compatible with the C++ string class.) I ...
stackexchange/codereview
I wrote the below method to list out the elements of an array, as well as adding the Oxford comma to the list if desired. However, my for-loop looks, perhaps, a little convoluted. Is there a better way to handle clearly both the Oxford comma and the ability to add a conjunction? function listOut($array = array(), $oxf...
stackexchange/codereview
<?php /** *session.php *danutz0501 *@copyright 2013 **/ //defined('BASE_PATH')||(header("HTTP/1.1 403 Forbidden")&die('403 - Acces direct interzis.')); class session{ private $db, $table_name = 'session_data', $session_name = 'PDOSESSID', $session_litetime = 1440; private static $instance = null; public ...
stackexchange/codereview
I'm working on a Winform project. We currently have a modular design (shown in the image) in our project. Where on every user action (button clicked or selection changed etc), first we set the Model accordingly (through the controller) then the controller raises an event which is associated with a UI (View) that listen...
stackexchange/codereview
I'm learning CUDA (and C to some extent), and one of the algorithms that I am learning is the Hillis-Steele scan algorithm. I wrote a program that performs a simple scan with adding. After seeding the random number generator and doing some allocation/initialization, the program fills an array with random numbers 0-9 an...
stackexchange/codereview
In my current project there is a lot inter dependency between different structs, so instead of having Arc<Struct> as members for each of the dependent Structs. I thought of using Singleton Design Pattern to get the instance of that Struct in the impl block. This is a sample code that I've written. I would like to know ...
stackexchange/codereview
I have made a small game just for my own practicing. While making it I wrote an asset loader, which (as the name says) loads assets. But my main knowledge and effort was on the game, so now I am wondering how I could improve the asset loader. On the bright side: It does the job quite well, no matter what changes I put ...
stackexchange/codereview
I have been programming a maths quiz that can be used for teachers an I have have been trying to make the code as short as possible so it is easier to understand. If you have seen my previous post you maybe be wondering why I am re-posting as I already have received feedback, when trying to act on this feedback I seeme...
stackexchange/codereview
My current query: select `t1`.* from `product_variant_values` as t1 inner join ( select `t1`.* from `product_variant_values` as t1 where ( (t1.`option_id` = 1 and t1.`value_id` = 1) or (t1.`option_id` = 2 and t1.`value_id` = 4) or (t1.`option_id` = 3 and t1.`value_id` = 7) ) group by t1.varia...
stackexchange/codereview
I have the following class designs, and I'm looking for the best practices, aligned to the OOP design principles/patterns. The ParameterParser will be used inside a foreach block through 10 items approximately. Any comments regarding the method body will also be appreciated, though the focus of the question is on the c...
stackexchange/codereview
I figure that someone here probably knows a much better way to do this. I'm still figuring out AJAX and jQuery, so I consider that I still need to master quite a bit of knowledge. My function extends Foundation 4 Reveal's functionality in a few ways: Uses WordPress AJAX to dynamically pull in content to populate a mo...
stackexchange/codereview
Just wondering if anyone can see a way to optimize this piece of code. It is a key piece of my program and needs to run as quickly as possible. The part of the code I am unsure of is the while loop for finding the nearest key -- but any assistance with optimizing the code would be appreciated. // TODO: Move to snippet...
stackexchange/codereview
I have this method that takes a list of my individuals (class has public field fitnessValue). I sum all fitnessValue and then draw a random value between 0 and sum of fitnessValue. In the end, I check for each individual where cumulative sum of fitnessValue passes the point I counted before and return the one which pas...
stackexchange/codereview
I have created a Master Mind BoardSolver. To apply the BoardSolver I have created an app (MasterMind) in which I create a Board with ColorPins and CheckPins. ColorPins and CheckPins are associated within a PinRow. A Board represents a given PinRow (code) and a List of PinRows as attempts. Please can you review this co...
stackexchange/codereview
I coded stuff for an embedded device where int is 24bits. I wanted to port uint24_t and int24_t to windows, so I made a header file to handle it. The goal was to have uint24_t and int24_t work as it did when I coded for the embedded device, and for it to be 3 bytes long and unpadded. My current implementation uses 3 by...
stackexchange/codereview
I have programmed a Tic Tac Toe game using Object Oriented JavaScript and ES6 Classes. The program works as planned, but I wonder if some parts of the code can be made cleaner or more efficient. I'm mostly concerned with the JS parts, not the HTML or CSS. Here is the code: index.html <html> <head> <meta name="vi...
stackexchange/codereview
A student was having problems with memory management so I put together an overload of global operator new and global operator delete to explicitly check for memory leaks and freeing invalid memory. This uses boost/stacktrace.hpp to point out exactly where you messed up. It is just for educational and possibly debugging...
stackexchange/codereview
I'm new to this PDO PHP and I have coded this spaghetti style. I hope you can give me idea how to improve using prepared statements. I'm not a lazy person, but I really need your help to improve my coding style. try { $select = "SELECT users.id, users.users_id, username, firstname, lastname, passwo...
stackexchange/codereview
I have 2 functions used for parsing a house number and I think these can both be improved. Any suggestions? input: 45a - 47b or 45a bis 47b output: 45,a,47,b public static string[] HausnummerAufteilen(string hausNummer) { string[] result = new string[4]; string[] resultVon = new string[2]; ...
stackexchange/codereview
This is a follow up to the questions: PyDOS shell simulation and PyDOS: Version 2.0 Introducing PyDOS 3.0! With brand new features and improved code, this will blow your mind! New Features (This list will be updated with PyWrite soon) Dialogs are now in a window like design. New start-screen, easier to use. Create you...
stackexchange/codereview
I've been working on a small "frame" for a text adventure in Python. So it's less of a real adventure and more of a small testing location for all the commands. I pretty much just started learning Python after completing the Codecademy tutorial and don't want to pick up any bad habits. #Text Adventure import shlex ...
stackexchange/codereview
I implemented a library which, amongst other things, implements a JSON-serializable ORM model based on the peewee framework. Here's the relevant excerpt: from base64 import b64encode, b64decode from contextlib import suppress from timelib import strpdatetime, strpdate, strptime import peewee TIME_FIELDS = (peewee.Da...
stackexchange/codereview
I am trying to implement a tiny image tagger with customized tag options in C#. The main window is as follows. The left block is a picture box MainPictureBox and there are two buttons, PreviousButton and NextButton. Furthermore, there are some tags in a group box AttributeGroupBox. A save button SaveButton is used for...
stackexchange/codereview
I have been trying for so long to code an encryption/decryption algorithm using the modulus operator. Basically my code does a basic mathematical operation on given text and key then do a modulus 255 as in 255 ASCII characters. But I was never able to successfully reverse a modulus operator. I have finally programmed s...
stackexchange/codereview
I have a FileAsset class. I have a set of 'filters' with which I determine if a FileAsset should be written to my database. Below is a telescoped version of how the filters work now. My big question is this: Is there a better way? Any advice would be awesome! (By the way, the Attribute key in the filters allows me ...
stackexchange/codereview
This is a prepared statement (I think). Have I done this well? function wyswietl($rekord, $tabela) { $lacz = lacz_bd(); if (!$zap_preparowane = $lacz->prepare("SELECT {$rekord} FROM {$tabela} where email = ?")) {echo "Prepare nieudane: (" . $zap_preparowane->errno . ") " . $zap_preparowane->er...
stackexchange/codereview
I am solving a problem on SPOJ and am currently unsatisfied with my submission time, given that my fastest time is 0.28s (which ranks me 123/5037) and the leading submission is 0.04s. The problem is pretty simple: Given a list of bank account numbers, print the bank account number along with the frequency at which it i...
stackexchange/codereview
I'm working on requirement that involves creating a N x N table of blocks, with each block having a weight. Consider the following classes Block - The fundamental unit of the table, having a weight RowBlock - A set of blocks that join together one row BlockTable - A set of rows that join together to form the table Th...
stackexchange/codereview
As a 'trying to learn Python' project, I am using ffmpy to stitch together a timelapse from a series of still images. I'd like the script to output a couple of formats for web use. This is what I have: #!/usr/bin/env python3 import datetime import ffmpy import os now = datetime.datetime.now() ydr = now.strftime('%Y')...
stackexchange/codereview
This code implements an FTPManager class and is designed to be a place to insert file data to be sent later, without having the program wait for a potentially very slow file operation to finish. This code is designed to work around some issues that I've been noticing when having multiple threads use FTPWebRequest simu...
stackexchange/codereview
I would like to transform the input elems = [a, b, c] terms = [t1, t2] @spec contains?(term, elem) :: boolean def contains?(term, elem), do: #implementation to either of %{t1 => [a, b], t2 => [c]} or %{t1 => [a], t2 => [b, c]} where t1 |> contains?(a) #=> true t1 |> contains?(b) #=> true t1 |> contains?(c) #=> fals...
stackexchange/codereview
I'm packing several values from a struct into a buffer to send them over Bluetooth. I don't want to send the whole struct and I also don't want to deal with padding, so I'm copying just the values I need. I also don't want to use anything that requires external tooling like Protobuf. This is what I came up with. (Short...
stackexchange/codereview
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...
stackexchange/codereview
So, I just managed to finish a problem that was proposed to me, and I find it very difficult since I started learning looping with for and using lists recently, I thought about sharing the problem and my solution with you guys so you could give me some advice on how I should make my code better or different ways to sol...
stackexchange/codereview
I'm planning to make a small game for learning purposes. So far, I've got the hang of the canvas element and using the context to draw things on it, as well as object notation and classes in JavaScript. But before moving on to making the rest of the game, I'd like you to please take a look at my code and see if there'...
stackexchange/codereview
I would like a review of a Scala validation library I am writing. For now we can focus on the regular expression component. The usage is described in RegexExample.scala There is an outline of the interface in RegexRuntime.scala But the macro and most of the craziness lives in RegexValidator.scala The idea being, if ...
stackexchange/codereview
So I have my own library to organize advanced critical sections at GitHub. It's based on the ResourceDataStorage class which is responsible for creating, storing and clearing resource records. I've tried to minimize synchronization blocks hits and I've used rehash function that differs from ConcurrentHashMap rehash to ...
stackexchange/codereview
My program contains some very large integers and uses the GMP library. The output contains integers (probably small enough to fit into int). I would like to make the output easy to read by adding commas between every three digits with any left overs on the left side. Examples: 1234 => 1,234 12345 => 12,345 123456 => 12...
stackexchange/codereview
I have implemented the following MCMC algorithm for the german tank puzzle found here I just want to make sure everything is legit and that I am not getting the right answer by chance. from scipy.stats import norm import numpy as np import math import scipy as sp import matplotlib.pyplot as plt from scipy.stats impor...
stackexchange/codereview
I have a node project. My scripts section of package.json looks like this: "scripts": { "postinstall": "gulp", "start": "node index.js", "test": "node ./node_modules/mocha/bin/mocha test" }, My Dockerfile looks like this FROM node:6.11-alpine RUN mkdir -p /code ADD . /code WORKDIR /code VOLUME /code RUN npm in...
stackexchange/codereview
code review friends/teachers! This is a trivial(no dfs/permutations/backtrace required) n queen problem from codeforces: B. 8 Queens, Again!! input 2 A1 B5 C8 D6 E3 F7 G2 H4 C3 E4 C4 E1 C4 F4 A8 G6 output Valid Invalid Here is my solution: queen.h #ifndef QUEEN #define QUEEN #include <array> constexpr int N = 8; ...
stackexchange/codereview
This method randomly increments or decrements (with equal probability) until either -3 or 3 are reached. I'd like to maintain printing the value of pos on each iteration, and printing the largest positive number max reached at the end of the loop. How can I improve this method using the Random() function? I know this s...
stackexchange/codereview
This is a program I have been working on in python. It is meant to be a quiz to some secondary school pupils on two subjects/topics which are maths and history. So far, it allows a user to try the quiz on one of the subjects and gives them a grade, percentage and score according to what they have answered correctly in...
stackexchange/codereview
I encountered the concurrency-zip project in OSTEP By Remzi Arpaci-Dusseau. So basically, I've built a simple compression program that uses Run-length Encoding, and multi-threading in C. But I couldn't find any correct solution so I think I can use this forum for code review. Essentially, the idea is based on Producer-...
stackexchange/codereview
I wrote a simple C++ lexer in python. Although it already works but I kinda feel I didn't follow the pythonic way. Any suggestion for improvements? Sample C++ Code Sample output Here's my code: mysrc.py: def keywords(): keywords = [ "auto", "bool", "break", "case", "catch", "char", "word...
stackexchange/codereview
The Question What is the percentage of customers who increase their closing balance by more than 5%? Source Code The database and all details can be found here. ERD My Proposed Solution Select TOP 1 Format(Cast(Count(Distinct Y.customer_id) AS Decimal) / (Select Count(Distinct customer_id) F...
stackexchange/codereview
I need to show article's content based on this logic: if article's content has to be truncated (e.g for preview) if there's [read more] substring in the content replace first [read more] with link to the article truncate content to the first occurence of [read more] else truncate content to the first 500 chara...
stackexchange/codereview
Can you review the following Python code? import random class Point3D: SEED = 1 def __init__(self, x, y, z): self.X = x self.Y = y self.Z = z def __hash__(self): hash_value = 0 # Number of hash functions to use num_hashes = 5 # Random vectors for ...
stackexchange/codereview
I am making a 2d minecraft clone for a hobby. Here is my code: 2D_MC.py: import pygame import world TITLE = "2d_MC" SIZE = (1365, 705) MOVEMENT_SPEED = 5 def handle_events(): for event in pygame.event.get(): if event.type == pygame.QUIT: return 1 keys = pygame.key.get_pressed() if k...
stackexchange/codereview
I'm trying declare a string in ANSI C and am not sure of the best way to do it. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> char *InitStr(char *ReturnStr){ ReturnStr = NULL; ReturnStr = realloc( ReturnStr, strlen("") +1 ); strcpy( ReturnStr , ""); return Return...
stackexchange/codereview
I want to organize mapping for my Angular app so that code structure would clear for other developers and I want to have as less code as possible. I have an api service that is responsible for communicating with API. I create separate data services, which utilize the api service, to get backend data. The same data can ...
stackexchange/codereview
Here is a snippet from my python script where I am performing: a dictionary lookup a cartesian multiplication of a list of len=500 against a list of len=60, calculating a cumulative addition for each multiplcation combination repeat this down a 20,000 rows This is slowing things way down and making it hard to debug w...
stackexchange/codereview
After doing some research on google i didn't find any good info on how to implement timeout with fetch (looks like there are multiple proposals but that's about it so nothing has implemented it). For what i'm doing i absolutely need i though. So i came up with simple solution that i would like a code review on. ...
stackexchange/codereview
I've just written a validation routine for a UPC-A, which ensures the check digit matches the given UPC number (according to rules I found on Wikipedia). Below is the code, what do you think? function valid_upc_a($value) { $odd_sum = $even_sum = 0; if(strlen($value) != 12) return FALSE; $chars = str_split($...
stackexchange/codereview
The following is a solution to Project Euler problem number 12: which is to find the first triangular number with more than 500 divisors. The code takes far too long to complete (over 10 minutes). Is there any way to optimize the run-time and to make it more elegant? #include <iostream> #include <chrono> #include <ctim...
stackexchange/codereview
I have a file with mostly 0 and 1. For each line I would like to compare it against all others (without the redundancy) and count the different combinations. It is slightly more complicated as there are also "N" in the matrix when there is missing data. For example if the two lines are: line1 = "0 0 1 0 1" line2 = "0 1...
stackexchange/codereview
I am trying to get better at Powershell and was wondering if I could get some advice on how to make this code more efficient/cleaner/anything. This code is intended to launch three batch windows running robocopy at the same time with unique log names. I looked into using a foreach loop but wasn't sure how I could do th...
stackexchange/codereview
I've written the following as a code assignment (Python 2.7). The task is to aggregate the loans csv file from the accounts department by (Network, Product, Month) with the total currency amounts, and counts, without using standard Python aggregate or group functions. I would like advice and suggestions on my current s...
stackexchange/codereview
I'm working on a small isometric drawing system in JavaScript. After much help from the Gamedev section, reading old questions, I've got something working. However, it's still a little hacky. I need to fix the culling to be more straightforward and it still isn't quite getting edge tiles down correctly. I want to impro...
stackexchange/codereview