instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
I recently created an extension which detects the type of credit card based on the numbers entered in and formats it. I am using Luhn Algorithm for validating credit card numbers and I am using jQuery masking for formatting the credit card numbers (for reference: jquery.maskedinput-1.3.min).
You can play with the demo ... | stackexchange/codereview |
I have a function that will calculate the sum of a list of integer, however if any of the number is negative, it will should an error instead (not throwing exception).
The following is a working Haskell code (Glasgow Haskell Compiler, Version 7.10.3):
addAll :: [Int] -> Either String Int ... | stackexchange/codereview |
need to rewrite some code I already have. It insert columns where a 'Standard Deviation' column is missing. To do that it checks if the preceding column is a "variable" column, and if there already is a "Standard Deviation" column after it.
Right now I'm using a while loop that iterates through the columns checking df.... | stackexchange/codereview |
I am using the fputs() function to write a string to a file. I want to handle the case in which the string has been successfully written to the file. Here is my code:
#include <stdio.h>
main() {
FILE *fp;
int rets; //to keep fputs return value
fp = fopen("test.txt", "w");
rets = fputs("\nThis is testing fo... | stackexchange/codereview |
When I read other people's code, it's sometimes difficult to understand the import structure. I thought making a graph of the import structure of a given python program would be a fun programming task, and maybe would result in a cool visualization. Currently the program included only works for modules with a .__file_ ... | stackexchange/codereview |
Can someone review my code which I put on exercism.io for the word-count exercise (found here)?
class Phrase:
def __init__(self, phrase):
self.phrase = phrase.strip().lower().split()
def word_count(self):
word_dict = {}
for word in self.phrase:
word_input = ''.join(e for e i... | stackexchange/codereview |
This is a simple LISP program to read in three sides of a triangle and report what kind of triangle it is (or isn't). Any feedback would be much appreciated.
(defun read-side (side) (format t "Enter a value for side ~d: ~%" side) (read))
(defun is-a-triangle (a b c) (if (and (< a (+ b c)) (< b (+ a c)) (< c (+ a b)))... | stackexchange/codereview |
This is roughly what my data file looks like:
# Monid U B V R I u g r i J Jerr H Herr K Kerr IRAC1 I1err IRAC2 I2err IRAC3 I3err IRAC4 I4err MIPS24 M24err SpT HaEW mem comp
Mon-000001 99.999 99.999 21.427... | stackexchange/codereview |
Inspired by the recent surge of questions dealing with changing numbers to their English equivalents (See here, here, and here), I decided to write my own version in Python.
zero_to_nineteen = (
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"... | stackexchange/codereview |
My below code is working fine but I want to make it more Pythonic. Furthermore, I want to get rid of nested ifs and make the code more compact and readable. Any suggestions? Here project_id and status_change_to are string objects. This code updates the status of certificate.
def execute(self, project_id, cert_obj_j... | stackexchange/codereview |
Here is a little widget that I've made. I'm looking to refactor the way that I'm doing hit detection. Currently, every square on the screen finds the distance between itself and the cursor.
Because there are quite a few of these squares, and that they are all being rendered 60 times per second. It's quite inefficient.
... | stackexchange/codereview |
When looking at people you may know on LinkedIn (requires you to be logged in) there are sometimes some annoying boxes that are for people who are email contacts but not on LinkedIn. I don't want to see these. If I wanted to connect with them and invite them to LinkedIn, I would have. So I wrote a userscript! I wro... | stackexchange/codereview |
I have a python script that downloads, unzip and parses an XML file published by a Canadian institution. Only some very specific tags are extracted and then all put into a pandas dataframe for later processing.
Everything works well. I just wonder if there is room for improvement here, specially in the parsing part. I... | stackexchange/codereview |
I've written a simple JS that takes care to animate an icon.
At first I wrote it quickly and without paying attention to any kind of optimization:
import '../js/core/sidenav.js';
const SIDENAV_ITEM_USER = document.getElementById('sidenav-item-user');
const SIDENAV_ITEM_SEARCH = document.getElementById('sidenav-item-se... | stackexchange/codereview |
I created a timer library called PHPBenchTime a few years ago, and decided to rewrite it last week.
This new version is meant to add in missing functionality (pause/unpause) as well as expand on the reporting system (so now everything is a lap and has finer details). Additionally, the rewrite was aimed at cleaning the ... | stackexchange/codereview |
I'm not familiar with how data transmission works, but I gave my best shot trying to code a server and client-side JSON packet transmitter via Python. Essentially client.py generates random JSON packets and sends them to server.py which binds a port using a socket and listens for a JSON packet, which then stores the JS... | stackexchange/codereview |
Code in Java but should be readable also for c#...
Let's assume I have a class with some reference types. Example:
class MyClass {
private int uniqueId;
private double doubleValue;
private MyReferenceType refType1;
// ...
public MyClass(int id, double doubleValue, MyReferenceType refType){
this.id... | stackexchange/codereview |
I wrote some code to determine the additions and deletions that happened to a sorted slice after each (sorted) update.
Git repository (includes some tests)
Godoc
// Package slicediff is a utility to determine the additions and deletions that happened to a sorted slice after each update.
//
// All the slices are assumed... | stackexchange/codereview |
You're given an array containing integer values. You need to print the
fraction of count of positive numbers, negative numbers and zeroes to
the total numbers. Print the value of the fractions correct to 3
decimal places.
Input Format
First line contains \$N\$, which is the size of the array. Next line
contai... | stackexchange/codereview |
I recently implemented a thread pool using std::functions. I only supported functions taking no arguments on the assumption that there would be no need to have them - one could just bind the argument to the std::function or capture it in a lambda.
I quickly realised the limitation with this approach - std::function req... | stackexchange/codereview |
Which version is more efficient in calculating the square root ?
There are 2 versions I have written to calculate square root programatically. Note reqs strictly state not using library functions ?
This is puzzling, the first method takes one extra iteration over the 2nd one but returns the more accurate answer of 3.... | stackexchange/codereview |
I am trying to create a filter string according to the fields available with the following code, how could i improve the following with a switch case or better way?
if ((this.selectedCity === 'City') && this.selectedCategory === 'Category' && this.fromDate === '') {
this.filter = `{}`;
} else if... | stackexchange/codereview |
I have such input:
[ { name: 'timezone', value: 'EST' },
{ name: 'interval', value: 'day' },
{ name: 'metrics[]', value: 1},
{ name: 'metrics[]', value: 2} ]
As you may already notice - these are parameters from POST request.
What I need to do is to get such output:
[ { name: 'timezone', value: 'EST' },
{ name... | stackexchange/codereview |
I will design a list with a Font-Awesome design arrows.
My code already works fine, but I will improve it.
ul.long_arrow_right_red,ul.long_arrow_right_gold {list-style: none;}
ul.long_arrow_right_gold li:before {content:"\f178"; font-family: FontAwesome;display: block;float: left;width: 1.5em;color:gold;}
ul.long... | stackexchange/codereview |
Method
Frequently input for problems is given as a 1D or 2D array in a text file.
Have knocked out a method to do so, but believe something shorter, clearer and cheaper can be written:
def read_array_from_txt(path, dim, typ, sep):
'''
@time: O(n)
@space: O(n)
'''
txt_file_object = open(path,"r")
... | stackexchange/codereview |
I have made my first little project using C#/WPF - a simple rock, paper, scissors game. I am happy with the functionality and look but I would love to know how a more experienced programmer would refactor the code I have to bring the size down and make it more readable. Many thanks.
MainWindow.xaml
<Window x:Class="Roc... | stackexchange/codereview |
As I am a totally self-taught 'person writing code', I decided to learn algorithms with one online course that taught them using Java for demonstrative purposes. The first topic I covered is the graph data structure and API.
I undertook to rewrite Java examples into PHP for training purposes. I would be really grateful... | stackexchange/codereview |
So I'm almost 100% certain I've done something wrong simply due to the inefficiency of what I've written, I'm entirely a novice to coding and am working on an assignment for my introductory programming course. The only way I could think to display the input from 4 check boxes was to go down 16 different branches to cov... | stackexchange/codereview |
I often find myself writing LINQ queries like this. I end up testing for Null and zero-counts pretty often, and the code sprawls out to be something like the following:
// GET: api/CustomBehaviours
public IEnumerable<CustomBehaviour> Get(int? orgID = null, long? userID = null)
{
using (PAMDatabase db = new PAMData... | stackexchange/codereview |
I'm taking an online course in website development and we're going over JavaScript ES6, but my professors lecture and notes I've taken we're not very helpful more resourceful with the assignment I was given.
Using proper ES6 methods, I was asked to create a class for Vehicles and two Subclasses for a bus that inclues t... | stackexchange/codereview |
For a script, I came up with a shell function that might be generally useful. Before I add it to the code base, I’d like to hear someone’s opinion on this.
I don’t write shell scripts often and had to look up a lot of things.
The idea of this function is to copy stuff from a source folder to a destination folder with t... | stackexchange/codereview |
I'm creating a town plugin for the game Minecraft using the Bukkit API. It works fine and all, however I'm not satisfied with the quality of the code and I'd like to know how I can improve. I've been programming in Java for about a year and a half now, any advice is appreciated.
I have a few concerns
I'm not sure if I... | stackexchange/codereview |
Got this question in a test.
Display the following number pattern using Java.
User inputs number of rows. For example 3
1112
3222
3334
For 5
111112
322222
333334
544444
555556
and so on.
This is the solution I came up with:
public static void NumberPattern(int n) {
int myarray[][] = new int[n][n + 1];
i... | stackexchange/codereview |
I wrote a Java program with a Swing UI that calculates prime numbers. The primes are displayed into a listbox. I used a few optimizations to generate the primes faster. I’m using the NetBeans IDE, so there’s a lot of generated Swing code.
Currently, the program finds as many primes as the user has input into a spinner ... | stackexchange/codereview |
I'm new to socket programming and c++. I have a the following method that sends an array to server and receives sum of the array, I tried to make it async.
std::future<void> AsyncClient::ReqSum(const std::vector<double>& numbers)
{
return std::async(
std::launch::async,
[&, numbers]()
{
... | stackexchange/codereview |
Got this design for getting rid of checking network availability and informing user of errors. Is it good at all? Please, help.
Overall point is to fire server call as short as possible:
new DefaultServerCallTask<LoginResponse>(){
@Override
protected void onSuccess(LoginResponse response){
//go to nextA... | stackexchange/codereview |
This is my first time posting so hopefully I manage to get my question across in a clear and concise manner. I'm not sure this is the right place but someone on StackOverflow suggested I ask here.
I am running a cross-validation experiment which involves training a model on a subset of a data set and then validating it... | stackexchange/codereview |
I am refactoring a legacy codebase to use spring. I am newish to spring and was wondering if you have any suggestions for the following code I refactored. Specifically about providing the ExpeditionEntitiesService.
Here is a REST service which uploads a file:
public class myRestService {
@POST
public Response... | stackexchange/codereview |
This is a console app I wrote for an end-of-chapter assignment in Jumping into C++. The parameters were for it to have a basic password system, and if you are eager, a multiple password / username system. I am going through this book completely on my own free will. It's not through a school assignment or whatnot.
It ... | stackexchange/codereview |
This morning I decided to write this question: https://stackoverflow.com/questions/11727571/are-there-problems-if-i-have-a-verbose-datatype/11727723#11727723
I don't really explain my scenario about how am I accesing through the nested dictionaries. I decided to have the default alias (IDictionary<string, IDictionary<L... | stackexchange/codereview |
I have a function initialize_path_statistics(). I have used openMP to make it parallel. I am not sure where certain lines such as
float length_enclosed = Nodes::get_length_enclosed(i);
need additional pragma like #pragma omp atomic.
void Path_Statistics :: initialize_Path_statistics()
{
path_match_score.resiz... | stackexchange/codereview |
I wrote this script for gaining experience, this script takes in a website link (NSFW) and download the video on that site. It uses regular expressions to parse the website source code to extract urls for downloading.
I'd appreciate it if anyone could take a look and told me the all thing I did wrong, as I'm sure I hav... | stackexchange/codereview |
The code works well but before I added sections (13) and (14), it ran in 6 minutes and now runs in 16 minutes. If there is a way to streamline this to cut down the runtime, that would be extraordinary.
Main part of code grabs values from under the header 'CUTTING TOOL' in various opening files in a designated folder. T... | stackexchange/codereview |
I'm making a wrapper for querying the database so that I can more easily control the flow of database management and to make it easier for me to write data beans around my database. This code is going to be used a ton so I'm looking to make it as clean as possible.
/**
* Query the database.
*
* @param sql
* ... | stackexchange/codereview |
I am a bit worried about this small PHP base as it has been running a bit slow. Can anyone notice anything majorly wrong with it?
root/Index.php:
define('START', microtime(true));
define('RAM', memory_get_usage(true));
define('ROOT', dirname(__FILE__) . '/');
define("SECURE", true);
ini_set('date.timezone', 'Europe/Lo... | stackexchange/codereview |
Dependencies:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.13</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.13</version>
</depende... | stackexchange/codereview |
I have written a python script using regex to extrapolate a poorly formatted text file data table into an actual data table. I am currently printing the output using . C:\my file location\file.csv in the command prompt. Is there a better way to cause my script to run for an entire directory of files and programmaticall... | stackexchange/codereview |
Background
(these are the bits technically not for review, but feel free to point out any minor points)
An Entity class can be identified by a name and at least one alias:
public final class Entity {
private final String name;
private final Set<String> aliases;
public Entity(String name) {
this(na... | stackexchange/codereview |
I am trying to create a simple NodeJS program that monitors few provided servers or machines and provides output in JSON.
// @file name : watch.js
// author : Abhinav Gauniyal
// requires
var os = require('os');
var http = require('http');
var net = require('net');
var diskspace = require('diskspace');
var s = net... | stackexchange/codereview |
The AsyncWorkerQueue class uses TPL Data Flow and Rx to async process and cancel work in a queue. It takes in a worker factory (Func) and executes it when its turn (or not if its scheduled to be canceled).
public class AsyncWorkerQueue : IDisposable
{
private TransformBlock<TaskFactory, TaskFactory> Worker { get; s... | stackexchange/codereview |
I've been working on this login screen logic.
It checks for the parameters in the JSON response to decide which action to follow. It works but it's kinda ugly and verbose. Any suggestions to refactor to make it look more elegant and simple?
Alamofire.request(apiLink, method: .post, parameters: parameters, encoding: ... | stackexchange/codereview |
[NOTE] This question can be depreciated in favor of version 0.2.
This code works well.
This my first attempt at creating a robust, computationally lean K-Means Cluster analyzer. I first saw this algorithm in an intermediate programming course, and it was bloated to the max: it created clusters object into which points ... | stackexchange/codereview |
Problem Statement
James got hold of a love letter that his friend Harry has written for
his girlfriend. Being the prankster that James is, he decides to
meddle with it. He changes all the words in the letter into
palindromes.
While modifying the letters of the word, he follows 2 rules:
(a) He always reduces the ... | stackexchange/codereview |
I have some duplicate code using LINQ & XML. I'm sure there is a way to refactor it, but I'm not sure how to go about doing it. Would someone help, please?
var fileInfo = dataXL.Worksheet("data")
.Where(t => t["F2"].Equals(company))
.Select(t => new
{
... | stackexchange/codereview |
Preface
At some point I was tired of writing & supporting __repr__ methods, so I've decided to write it once and reuse everywhere in my classes.
Since I'm trying to write classes as simple as possible, most of them ends in something like
class MyClass:
def __init__(self, param, other_param, ...):
self.par... | stackexchange/codereview |
I needed a task scheduler that could be used somehow like this:
#include <iostream>
// To compile and run this example, include here the code listed in the second code block
void Task2()
{
std::cout << "OK2 ! now is " << std::chrono::system_clock::now().time_since_epoch().count() << std::endl;
}
void Task3()
{
... | stackexchange/codereview |
Hacker News recently released an official API. Unfortunately, it cannot be used to get the newest posts submitted. I wrote a script to provide a faux streaming-api like method (like praw reddit's submission_stream) so that I can simply put it in a loop and do something like make a gtk-notification when title contains t... | stackexchange/codereview |
Project Euler problem 54 asks:
The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters... | stackexchange/codereview |
I have been working on my own form of validation for XML other then xpath, as a toy project.
First off, I use this class to add Validations to the graph to check for and validate they exist.
public class GraphValidation
{
public string Target { get; set; } = "";
public bool Result = false;
}
Next I use this c... | stackexchange/codereview |
I have written a code for basic array creation and printing it's values in C. I would appreciate comments on how it can be improved, and the industry standards.
One issue I'm encountering is having no way to tell printArr() what the size of the array is.
Some questions:
Can I use arr[i] anywhere in the functions inst... | stackexchange/codereview |
This is a follow-up to my ex-posted Blackjack game that uses a MySQL database to store the accounts and user's money. I tried splitting display_info() a bit, I also added a check for validating the Email address and the passwords are now hashed.
from random import shuffle
import os
import cymysql
from getpass import ge... | stackexchange/codereview |
I have done my first PHP-MySQL project with MySQLi connection. Please review this and inform me about security and performance issues.
dbconnect.php
$DBhost = "localhost";
$DBuser = "root";
$DBpass = "";
$DBname = "mysqli_login1";
$DBcon = new MySQLi($DBhost,$DBuser,$DBpass,$DBname);
if ($DBc... | stackexchange/codereview |
I have these two methods on a class that differ only in one method call. Obviously, this is very un-DRY, especially as both use the same formula. Could anyone give me advice on how to tidy this up?
public class PlayerCharacter {
int level;
public int getAttack() {
int attack = 1 + level;
for(Equ... | stackexchange/codereview |
Given an unsorted array. The task is to find all the star and super
star elements in the array. Star are those elements which are strictly
greater than all the elements on its right side. Super star are those
elements which are strictly greater than all the elements on its left
and right side.
Note: Assume fir... | stackexchange/codereview |
This is a still incomplete file manager for X11. It can only navigate
through directories, select files (and do nothing with them), call a
script to open files, and call a script to produce and cache thumbnails (it uses the imlib2 library to render images).
Here is the git repository: https://github.com/phillbush/xfil... | stackexchange/codereview |
The general problem I'm trying to solve is that I have a code base that has zero documentation so I'm trying to automatically generate some diagrams of classes in package that I'm analyzing using erdantic.
Trying to make this as reusable as possible, so I have a generate_diagrams() function that should take in one argu... | stackexchange/codereview |
I wrote a commit message validator + CLI in NodeJS.
Notes:
My greatest concern is that the patten I use to represent the results of a validation is inadequate. Options:
Use adhoc enums
Create a ValidationResult class (?)
Extend Error and return an array of those. In this case, how would the --verbose option, which sh... | stackexchange/codereview |
I want to utilize namespaces and make the code on this file uploading script more secure, and cleaner looking, here is what i have so far
it uploads an image and inserts it into a database.
I want to be able to use namespaces within view files, without it looking messy.
i know i can use laravel blade etc, but for the s... | stackexchange/codereview |
I've implemented Many-To-Many relationship and wonder if this is the optimal way for it. Since I do not have extensive EF Core experience I would love if someone with more experience could check it out.
Scenario:
Many users
Many organizations
User can belong to multiple organizations
Organization can hold multiple use... | stackexchange/codereview |
I wrote a basic command prompt Tic Tac Toe Game. I want to know what can be improved in terms of modeling and what mistakes I've made (if any).
void Main()
{
TicTacToeBoard board = new TicTacToeBoard();
while(!board.GameOver())
{
var i = int.Parse(Console.ReadLine());
board.MakeMove(i);
... | stackexchange/codereview |
Linq to Object GroupBy extension method allows grouping by projection:
IEnumerable<Product> products = …
var groups = products.GroupBy(p => new { p.Price, p.Category });
Here is the solution to specify field names at runtime in a way like this:
IEnumerable<IGrouping<Product, Product>> groups =
products.GroupBy("... | stackexchange/codereview |
I try to block all websites in Hebrew because I want to give more time on websites in other languages.
Given that many webmasters don't add <meta name="language" content="Hebrew"> meta attribute to all webpages of their websites I can't use it to block websites which appear in a certain language.
According to one work ... | stackexchange/codereview |
Why is my code lagging? It gets those lagspikes that will ruin the whole game. I know JavaScript in the browser maybe isn't the best for games, but it doesn't have to lag?
var canvas;
var gameInterval = false;
var gameSpeed = 250;
var xTiles = 200;
var yTiles = 200;
var xScale = 40;
var yScale = 40;
var tiles = [];
... | stackexchange/codereview |
I've created a program that will create work notes for me, however, I've been under the impression since I started writing in Ruby that while loops are bad. How can I write this differently in order to gain the same effect or an even better effect?
def prompt(input)
print "[#{Time.now.strftime('%T')}] #{input}: "
S... | stackexchange/codereview |
Below is my code
import pandas as pd
import math
import csv
fund = 10000
print("investment",fund)
pval = 0
oldportfolio = []
dts = ["06 Feb 2017", "07 Feb 2017", "08 Feb 2017", "09 Feb 2017", "10 Feb 2017", "13 Feb 2017", "14 Feb 2017", "15 Feb 2017", "16 Feb 2017", "17 Feb 2017",
"20 Feb 2017", "21 Feb 2017... | stackexchange/codereview |
I have a need for a container that behaves like an unordered_map, but has a fixed capacity, and an eviction policy where the least recently inserted key-value pair is chosen to be evicted when an insertion is performed at capacity.
I've implemented this by creating a container which combines a regular unordered_map wit... | stackexchange/codereview |
After seeing this post on StackOverflow, I thought I'd try it out. What I have now is a diamond shape with numbers like this:
1
212
32123
4321234
543212345
4321234
32123
212
1
My code looks like this:
int i, j, k, n = 6, l = 3, o = 2;
for (i = 1; i <= 5; i++)
{
for (k = n; k >= 1; k--)
{
... | stackexchange/codereview |
Coming from high-level languages like PHP and JavaScript, I'm doing an Assembly course on Udemy.
Yesterday I tried to implement the following task:
Write a program that takes a number m as input, and prints back 1 to the
console if m is a prime number. Otherwise, it prints 0.
Original text can be found here (Exerc... | stackexchange/codereview |
Below is the unsorted array and sorted array implementation of priority queue.
Code directory structure:
./code$ ls -LR
.:
pqClient.exe pqClient.c list PriorityQueue type.h
./list:
arrayImpl.c linkedListImpl.c list.h
./PriorityQueue:
arrayImpl.c heapImpl.c PQ.h sortedArrayImpl.c
type.h
/********* type.h *****... | stackexchange/codereview |
I'm currently in the process of coding a QuadTree. The QuadTree seperates into four quadrants, with 1 being the top right and 4 being the bottom right. I have this code to determine which quadrant the AABB fits into:
int getIndex(AABB aabb) {
int index = -1;
double vertMid = bounds.getX() + (bounds.getWidth... | stackexchange/codereview |
I'm trying to "optimize" the command below. In other words, to make it suit my needs using best practices. I found a lot of posts regarding the "upsert" operation and there were a lot of solutions and in the end, I'm not sure which one is best.
The term upsert is a combination of the words “update” and “insert.” In th... | stackexchange/codereview |
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Could someone point out if there is something wrong with the code; where I should optimize/modify it?
import java.util.Scanner;
p... | stackexchange/codereview |
I have a part of my code I want to optimize.
I use if statement to skip the analyze if the values are not the one I want.
Just to help the comprehension, in my data, R1 is between range(6,15); mis in range(0,1); spacer in range (0,10).
My code is working, but it would be better if it will run faster according to the a... | stackexchange/codereview |
I'm new to react and am building a basic react app and have just built a basic area where navigation links render on a page but wonder whether my current start could be optimised - for example, I wonder whether an area like this:
render() {
return (
<Root navLinks={this.state.navLinks}></Root>
);
}
... | stackexchange/codereview |
I'm working on creating a queue to hold variable sized data buffers up to 256 bytes in length, however most often the buffers will be much smaller (typically around 10-15 bytes).
To avoid the wasted memory I attempted to create a queue based on a linked list with variable sized dynamically allocated items the size of ... | stackexchange/codereview |
The previous failed attempt
This question derives from this other question I made.
In the previous question I tried to use a Monte Carlo algorithm;
sadly it did not work.
I am doing an hardcoded AI
I therefore decided to try an hardcoded AI, but not for 21 game because it would have been too trivial, for a more general... | stackexchange/codereview |
My task is that of caching. If the folder exists then load the cache from disk, if it doesnt create new cache. This is trivial, what bothers me is if I want to create third mode of noop (don't do anything relating to cache).
Currently I have this:
class HeavyCalculationClass:
def __init__(self, cache_dir=None)
... | stackexchange/codereview |
I'm currently learning programming and Python from Python Programming for the Absolute Beginner, Third Edition. I've been doing the challenges set out at the end of each chapter but I'm never sure if I'm doing what the author wanted or if I'm doing them the best way or worst way.
The task is to:
Create a Critter Farm ... | stackexchange/codereview |
I have this simple Rust program, which creates a file called numbers.txt and writes the numbers 1 to N (N is here 10000000) to it, separated with newlines:
use std::fs::File;
use std::io::Write;
const N: i32 = 1e7 as i32;
fn main() {
let mut data = String::new();
for i in 1..=N {
data.push_str(&form... | stackexchange/codereview |
I have a code similar to this:
public class PlayerRound {
private final List<Strip> playerStrips = new ArrayList<>();
public boolean addStrip(final Strip aStrip) {
// ...
if (playerStrips.contains(aStrip)) {
playerStrips.set(playerStrips.indexOf(aStrip), aStrip); // DOES THIS LINE C... | stackexchange/codereview |
I am into building functional prototypes, but also for outputting CSS and JS, which means we have 2 times we build out our code, once as a demo with HTML files (we are using assemble.io) and another, where we are building out the files to be uploaded to production (an Enterprise CMS).
Most things about the build are th... | stackexchange/codereview |
There's another exercise from Thinking in C++.
This time it asks this:
Write a program that uses two nested for loops and the
modulus operator (%) to detect and print prime numbers
(integral numbers that are not evenly divisible by any
other numbers except for themselves and 1).
And this is what I think:
//... | stackexchange/codereview |
So my task was to make a lottery function, but the instructor only provides half the code when explaining and going through my resources i was unable to find proper examples on how to complete it aside from this part.
import random
def user(startval, endval, numberpicked):
somelist = []
while len(somelist) < n... | stackexchange/codereview |
The code is not for any project, I just want to know the best coding practices. The code is also on GitHub.
#include <iostream>
#include <new>
#include <typeinfo>
using namespace std;
/****************************************************************
* Exceptions
****************************************************... | stackexchange/codereview |
For several months I'm working with JavaScript and THREE.JS library. Firstly I dislike the prototype-based programming because I have to work a lot of with class-oriented languages, where any class is represented as the type and there is a strict separation between declaration and behavior of program design.
But, I und... | stackexchange/codereview |
I have put together this small application that uses the JSONPlaceholder API and Vue.js.
The application crosses users and posts and displays the posts by user (author):
var app = new Vue({
el: "#app",
data: {
base_url: "https://jsonplaceholder.typicode.com",
uid: 1,
currentUser: null,
userData: n... | stackexchange/codereview |
The task is to write a class system that implements figures on the plane (point, segment, square, rectangle, triangle). Also, it is needed to provide encapsulation. There should be constructors and several methods that determine the size. Use the Has-a relationship.
Would you please review my code and say what is not c... | stackexchange/codereview |
I am trying to program a solution generator for the Countdown numbers game in Python, following some guidance from DataGenetics -- those unfamiliar with the rules, you can review them here as well -- but I wrote the code myself.
Code
def postfix_to_infix(postfix):
"""
:param postfix: tuple containing solution i... | stackexchange/codereview |
I'm a beginner in Java and want to improve and learn.
This is a followup of my previous post.
This is a game called "Acey Ducey":
The dealer shows you two cards. You decide whether you want the dealer to pick a third card or not. If the third card is between the two cards, then you win, otherwise you lose.
The full sou... | stackexchange/codereview |
The problem my code solves is listed below. I know my code can be improved, it takes a while to run when bigger arrays are entered as input.
"Problem - Given an array of integers, sum consecutive even numbers and consecutive odd numbers. Repeat the process while it can be done and return the length of the final array."... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.