instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have written my own one time pad algorithm for encryption and decryption, but I would like to listen to your opinions about its correctness and eventually how could I improve it. My idea was to keep it readable, but not so bad in terms of performance. I have also written some tests. Here's the code: from random impor...
stackexchange/codereview
In the code below I will replace all consecutive equal elements in a list with a new element. In this case I have chosen the new element to simply be the concatenation of all the equal elements, but I want the code to remain adaptable to other situations. I have the following example: Input: ["a", "a", "b", "c", "d", ...
stackexchange/codereview
I am trying to implement a recursive count of inversions in a list of integers by using merge sort and counting the number of split inversions on each recursion. My code works but runs painfully slowly above a list of about 100 integers, and I need to count for ~3 orders of magnitude greater. Can anyone see what I'm do...
stackexchange/codereview
I have a C# application which needs to encrypt string and save the key as a hash. The key is saved as a hash to check the right key has been input before trying to decrypt the message. First, I have these method to generate the hash string - hopefully "off the shelf" and ready to go public static byte[] GetHash...
stackexchange/codereview
Recently I started learning programming and I created this program. I've added something to it with every new lesson. How is my code-writing? Do I make mistakes I shouldn't make? The program itself static void Main() { { Console.WriteLine("Select language:\n"); Console.WriteLine("1....
stackexchange/codereview
I am learning algorithms and trying to implement them in c++, I have chosen to try to implement a red-black tree due to its self-balancing properties and its ability to stop the worst case of O(n) when searching for a value. I also needed to allow duplicates to have a vector to hold duplicates in node objects, and a ke...
stackexchange/codereview
I wrote this map function, that should loop a very nested array of objects and find and exchange an item. To make my life easier, I also pass a path array: [1, 4, 7, 23] that shows in which id-s my nesting happens. The last id is the item I need to swap. Here is my function: () => { const { id, parentPath, question ...
stackexchange/codereview
Problem: Write a function to convert Integer to String, using only pointers, without array indexes, string must be dynamically allocated. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> // move each character in array one place to the right // we need to make place for new character on the left void...
stackexchange/codereview
I recently asked this question on Stack Overflow, but now that I have a working example, I would like to have it checked. I set up the layout like this: I am going off the idea that parents can talk directly to their children, but children should use an interface to talk to parents (docs). The docs where not clear, th...
stackexchange/codereview
Is it a good or bad practice to use closures for asserting the method was called in such a way? The method set a shim and return an Action wich both capture local mutable variable: private static Action<bool> ShimCopy(FileInfo source, FileInfo destination) { var wasCalled = false; ShimFileInfo.AllInstances.Copy...
stackexchange/codereview
I'm using two category filters from this demo. I give the filters two different sets of classes so they won't affect each other. Since I'm very new to jQuery, all I can come up with is repeating the same code with a different set of classes. I wonder if there's a shorter way to write this: $(function(){ /* filter1...
stackexchange/codereview
I wrote some code which searches parts of a split-archive backup (it's an Android backup, I used flashfire to backup) and rejoins them. As you can easily see, I've achieved this by if statements and the maximal number of archive parts is hardcoded (although NOT limited to 4 parts). As I'm very new to "programming" (if ...
stackexchange/codereview
What is this: This is a simple function, part of a basic Monte Carlo simulation. It takes sample size and probability as parameters. It returns the simulation result (positive answers) plus the input parameters in a tuple. What I'm asking: I'm trying to avoid using temporary variables, I have two questions. Do I reall...
stackexchange/codereview
The task Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrom...
stackexchange/codereview
I am trying to write a graph implementation in Java. I would appreciate it if someone can please review the code for me and give constructive feedback. import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; public class Graph { private int V; // Number of vertices private int E; // ...
stackexchange/codereview
I have been unable to find any other way to update a user config file than the following method. public class SettingServices : ISettingServices { public UserSetting GetUserSetting() { XmlSerializer reader = new XmlSerializer(typeof(UserSetting)); StreamReader file = new StreamReader(UserConfig...
stackexchange/codereview
I'm didn't use java for a long time(5 years ± ) and in the following code the user should provide yaml file and it converting it to json file. The code is working as expected but since I didn't use java for a long time I want to see if I can write this code better and learn new things :-) in the latest java (currentl...
stackexchange/codereview
I'm learning PHP now, and I'm trying to find out whether or not the following code structure has any faults: $loggedIn = false; if (isset($_GET["userpass"])){ if (strcmp($_GET["userpass"], $correctPassword) == 0) { $loggedIn = true; } } To me, it seems pretty bullet-proof. If the password isn't set, th...
stackexchange/codereview
I'm trying to implement a simple automation solution in a restricted environment. I have actually implemented something but it took a bit longer than I wanted. I want to improve the solution and I'll probably have to extend it in the future so I'm asking for code review - my boss will probably be happier if I can deliv...
stackexchange/codereview
I have been learning AngularJS and have written my first app. It's a Hangman AI which learns words and guesses the solution based on the words it knows. Please look over my code and provide some pointers towards better practices, techniques and overall criticism. Here is a CodePen demo, as the Stack Snippet may have cr...
stackexchange/codereview
I have a few Python codes like this: workflow = [] conf = {} result = [] prepare_A(workflow, conf) prepare_B(workflow, conf) prepare_C(workflow, conf) result.append(prepare_D_result(workflow, conf)) prepare_E(workflow, conf) #.... about 100 prepare functions has the same parameter list I was wondering that w...
stackexchange/codereview
Write a method to compute the difference between two ranges. A range is defined by an integer low and an integer high. A - B (A “minus” B) is “everything in A that is not in B”. This is an interview question and here is my code: void findDiff(int a1,int a2, int a3, int a4) { cout<<"("<<a1<<","<<a2<<") - ("<<a3<<","...
stackexchange/codereview
In general, I'd love some comments on this basic queue using dynamic allocation. In particular, I want comments about whether this queue is good in embedded systems, for example say a a sensor network gateway, which has to queue up packets to be forwarded on say a UART. I hear normally that mallocs are a bad idea for e...
stackexchange/codereview
I have started to create a console app, which I am testing locally on my mac. The idea is to generate an ssh key and structure the storage of these keys within the .ssh folder. My thought behind this is for my digital ocean ssh keys, and so I am using a folder structure dictated by the droplet name and user. i.e /users...
stackexchange/codereview
I'm relatively new to Go, which is why I decided to post some code here. My goal is to en-/decode a TCP stream. The individual data packets length-based. The first two bytes are the unsigned size in little-endian byte order. The size includes the size field itself. The methods I wrote seem to en-/decode the packets as ...
stackexchange/codereview
I find myself following this pattern a lot in my core data code, which works, but I'm wondering if it is needed... let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) privateContext.parent = mainThreadContext /// Do some stuff on the private context privateContext.save() /// Sa...
stackexchange/codereview
I am not really having any problems with this. I'm just wondering if anybody has any ideas for a path for me to look down for bettering this little FF turn-based style of game in my free time. I know somebody is going to complain about my global variables and the fact that I am not using object-oriented programming, b...
stackexchange/codereview
Problem statement A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate ar...
stackexchange/codereview
I was practicing python on codewars.com with this question: Create a function that takes a positive integer and returns the next bigger number that can be formed by rearranging its digits. For example: 12 ==> 21 513 ==> 531 2017 ==> 2071 But when I attempted my solution it said it was not optimized enough Can someone s...
stackexchange/codereview
So I needed to represent by objects in terms in ini format and change their values from the ini as well, so I thought why don't implement a property system for this. I want it to be bit fast so I would really like if anyone can remove the std::function if possible but its not necessary. The target application is GUI so...
stackexchange/codereview
I have written some code that scrapes data on asteroids, but the problem is that is super slow! I understand that it has a lot to scrape, but as of now it has been running for 5 days and is bot even a tenth of the way through. Here is my code, the part I'm talking about is under GET-EPHEMERIDES: from mechanize import B...
stackexchange/codereview
I have network printers which have different attributes (e.g. supported network protocols, languages, status, print modes). public abstract class PrinterAttribute { protected PrinterAttribute(int value, string dsc) { this.Value = value; this.Dsc = dsc; } protected PrinterAttribute(int value, string dsc...
stackexchange/codereview
I wrote a function that basically works like sprintf, but instead returns the formatted string (std::string). I haven't worked on this long, and I'm aware there are tons of improvements that could be made (alloc/realloc perhaps?). I was just looking for some advice before taking the next step. GLOBAL string format(cons...
stackexchange/codereview
class session{ //variabile folosite private static $_sessionStarted = false; private static $_crypt = 'qwerty347658@$%AdfSV045*&erT2Erb%6w!07&[.?;ru'; private static $_salt = 'qwertyAF347658@$%AdfSV045*&erTyUsdfYtrLmncBGhu'; private static $_rand = 'abcdefghijklmnoqprstuvxwz0123456789!@#$%^&*()_-=;:<>,.'; private...
stackexchange/codereview
Self explanatory, and all the functions contain descriptions of their specific problem statements. Since this is project Euler, I would be particularly interested in any analysis of the functions' computational efficiency. Option Explicit Public Function ProjectEuler1() As Long '/ Problem statement: sum all m...
stackexchange/codereview
I wanted to do some exercise and came up with the idea of a good challenge (for my level of course). I tried to implement Laplace's algorithm for computing the determinant, recursively. #include <math.h> #include <stdlib.h> #include <vector> #include <iostream> using namespace std; int getMinimoCount = 0; //ignore the...
stackexchange/codereview
So I've written a function which parses a fairly simple key-value pair syntax. Each pair can span across multiple lines, as long as the value does not have a colon in it. If it does, then any new line must be preceded by three spaces. For each pair, I create an object with the key, the value, and the offset at which th...
stackexchange/codereview
I'm a 16-year-old so I never studied programming, although I do try to adopt the best practices I can when given the chance. I would like to clean up the code posted below by making it comply with SOLID principle, and any other general improvements that are offered. The class in question is the core entry point of my w...
stackexchange/codereview
I have a 'read more' angular directive copied from: https://github.com/doukasd/AngularJS-Components/blob/master/dd-text-collapse/dd-text-collapse.js Some of my text can already have <br> tags in it (I ONLY allow just <br>) so I just needed to handle that...below is only the extra code I wrote for this purpose. Does it ...
stackexchange/codereview
I wanted to practice OOP when writing a program so I decided to make a simple test/quiz. I would appreciate any corrections and improvements to make my code cleaner/shorter/more extensible/more efficient/better naming/more loosely coupled, because right now I feel like my program works but it's tightly coupled and fran...
stackexchange/codereview
The code uses SQLAlchemy Core. However, what I want to know is if writing code in this pattern is recommendable. def saveUser(self, user): """ Inserts or updates a user in database. The method first checks if the provided user's id already exists. If no, then the user will be inserted. Otherwise, the stored...
stackexchange/codereview
I'm new to using python and wanted to know how I could improve my program. I'm using the Luhn algorithm, the beginning numbers of the credit cards, and the number of digits in the credit card. from cs50 import get_string import re import sys number = get_string("NUMBER: ") check = [] if (len(number)) not in (13,15,16...
stackexchange/codereview
I am learning Python for a few weeks. Last time I started object-oriented programming and I feel like it is really hard for me to write the relation between methods and attributes for different objects. I tried to write simpler version BlackJack card game only with Hit or Stand option. Could you have a look at my co...
stackexchange/codereview
I've been learning python for some time and I've come up with the idea to practice it a little. I created a script that removes files by their extension .html and .srt and also empty directories. It works good, but I've got a feeling that it could be improved. Can someone help me improve the code? Also I know it is not...
stackexchange/codereview
I would like to calculate the average for the same days (e.g. Monday, Tuesday, etc) in a selected period: $data = array( '2016-05-01' => 100, '2016-05-02' => 150, // monday '2016-05-03' => 5, '2016-05-04' => 5, '2016-05-05' => 25, '2016-05-06' => 25, '2016-05-07' => 25, '2016-05-08' => ...
stackexchange/codereview
The purpose of this was to practice web scraping, regex and GUI. I use a popular bitcoin website to scrape the names and prices of the top 16 cryptocurrencies. I then create a data frame and make a GUI to display the information based on the user's selection. I am looking for any and all input on how to improve this co...
stackexchange/codereview
I've recently made an attempt at creating a binary search tree class that allows for duplicate elements. I've included as many functions as I can think of so that I can use it later on. I've tested the code and it works well, without any memory leaks when using -fsanitize=address. I was wondering how my code looks over...
stackexchange/codereview
I am working on an angular stack that has n amount of services that hold data in stores of this type: fooStore$ = BehaviorSubject<FooStoreType>({}) accessing properties in these have generally been done like this: export wantedPropSelector$ = fooStore$.pipe( map(store => store.wantedProp) ); Now I'm working on impr...
stackexchange/codereview
In one of my recent projects I faced the problem of transforming an abstract class into another abstract class. The classes were structured like this and are part of an api for questionnaires: abstract class AnswerConstraint { /* shared implementation for all entities */ } class LengthConstraint extends AnswerConstrai...
stackexchange/codereview
I have written a piece of code where I have a simple GUI with an Tkinter Canvas. On this canvas I draw an Matplot. The Matplot is updated every second with fake sensor data i simulate in an SQLite DB (just for testing at the moment). I reached most of my Goals for this test case. But a few Things i would like to have r...
stackexchange/codereview
Task I was asked to write a function, which can determine (return a bool) whether 2 given strings are anagrams of each other? That function should have the following constraints: Upper and lowercase letters are considered the same Non-letters (so numbers, punctuation, whitespace) should be ignored My implementations:...
stackexchange/codereview
This is a follow-up to this question. While discussing some details about the code I posted there, I came upon a problem with thread-safety. After searching and trying different things, I reached a potential solution that I now present here. This worked without any problems during my tests, though since thread-safety i...
stackexchange/codereview
Often I need to clean a file name using Path.GetInvalidFileNameChars(), however I do not know of a way to search for any of the invalid letters (except by using Regex) in one pass. public string LoopMethod() { StringBuilder sb = new StringBuilder(fileName); foreach(var invalidChar in Path.GetInvalidFileNameChar...
stackexchange/codereview
I followed the Beej's Guide to Network Programming. The program acts like a multi-user chat server. One connects and sends a message to the server, which is forwarded to all that are connected. There's a simple makefile below; also Valgrind output. Review Goals: I have specific questions: Is my code POSIX compliant? D...
stackexchange/codereview
In the following contrived example, I have a collection of PropertyManagers that each contains selector and assigner delegates to read from and write to a property on the generic type. It feels clunky for lots of reasons, not least of which is that both delegates are basically there to serve the same purpose: To identi...
stackexchange/codereview
Is there a more natural way to do this in rust? I'm having a lot of difficulty trying to make this look clean. Type mismatches and borrowing have me stumped. What are some refactors that I could make? Input Take in list of space-separated, command-line arguments Output Book (join all arguments except the last) Ref...
stackexchange/codereview
It was written in Emacs Lisp and requires Common Lisp loop facility. Can this code be improved? Did I hit any anti-patterns along the way? (defun combos (list) (let* ((a (car list)) (d (cdr list)) (s (and d (combos d))) (v (loop for c in s collect (cons a c)))) (cons (list a) (append s ...
stackexchange/codereview
I have a solution to the following problem that I'd like to know if there's a way I could decrease runtime complexity for. The directions are: reorder the letters of the first string to match the order of the letters in the second string. If a letter in the first string is not present in the second string, add it to th...
stackexchange/codereview
so as a beginner in Python, I've been utilizing CodeWars to practice everyday alongside my courses, been happy by the results so far, however, what I really am focusing on is the logical thinking side of things and "Thinking like a programmer". I got a question today on codewars that brought me here to ask. Although th...
stackexchange/codereview
This is used to display an accordion with a list of connections using JavaFX. Can you help me to optimize the code to make it much simpler? package sqlbrowser.navigation; import java.util.ArrayList; import java.util.List; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javaf...
stackexchange/codereview
I'm working on a script where I want to create one dataframe from a series of files with annual baseball data in them. I'm relatively new to R and I feel like the way I wrote get_seasons_range() is probably more like writing C# in R, rather than doing it the idiomatic R way. Is there a cleaner way to do this? read_seas...
stackexchange/codereview
The #traverse_until method is a helper function that traverses the linked list and returns the node and index of the node once a condition (in a block) is met or until the end of the list. I would greatly appreciate feedback about verbosity, efficiency, readability, etc. module DataStructures class Node attr_acc...
stackexchange/codereview
I have some classes with properties, wich could only have numeric values in a given range (e.g. 0 to 8). This should be validated and wrong values prevented with an exception. The given behavior may be implemented without duplicating the given code. There are some ValidatorAttributes in C# but I can't get them to runni...
stackexchange/codereview
I have a Minimum Difference algorithm, and I wanted to expand on it by printing the actual elements that were subtracted. I'm just wanting to know if this is the best way to do it. public static int findMinimumDifference(int[] arr) { int minuend = 0; //initialize them here int subtrahend = 0; Arrays.sort(...
stackexchange/codereview
I want to extend the Closeable-Interface so that I can add Listeners, that get notificated when the resource is closed. The CloseListener-API is rather simple and straight forward: public interface CloseListener { public void objectWillBeClosed(CloseableObservable closeable); public void objectClosed(CloseableObse...
stackexchange/codereview
This is a partial update of this question. An implementation of these interfaces is in this question. To summarize, the class is a generic container similar to MaxHeap, but only needs to support the following operations. create from an existing collection or finite IEnumerable (constructor / factory) with arbitrary co...
stackexchange/codereview
I have a piece of code where I compare two arrays for similar values, then remove the similar values from one of the arrays. Is there a better way of writing this piece of code? UpdateAddedTasksAfterDelete() { var tasksToRemove = []; var updatedTasks = []; for (var i = 0; i < this.deletedTasks.length; i++)...
stackexchange/codereview
I have a Playlist object which contains many PlaylistItem children. If I have 10,000 children then the UI gets blocked from rendering until all 10,000 children have been processed. To avoid this, I've created a recursive function wrapped in a setTimeout. This allows a chunk of the playlist to be rendered, allow the UI ...
stackexchange/codereview
The algorithm bellow is meant to allow a user to roll a die as many times as he would like, then print how many times each side was rolled and how many rolls there were total. import java.util.Random; import java.util.Scanner; public class DieRoll { public static void main(String[] args) { // TODO Au...
stackexchange/codereview
I'm iterating through two lists to find matching objects. The objects have two string properties, Id1 and Id2 below. If Id1 is not null, empty or whitespace, I want to use it to find a matching object in the other list. Otherwise I want to make use of Id2. If both Id1 and Id2 are set to null by the extension method on ...
stackexchange/codereview
start: try { oleDbDataAdapter1.Fill(myDataTable); } catch (Exception ex) { DialogResult res = MessageBox.Show("Can't load data:\n" + ex.Message, "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); if (res == DialogResult.Retry) { goto start; } } Is it ok to use goto oper...
stackexchange/codereview
I want to pass errors in errors in order to know exactly the chain of causes, but without augmenting or even reading any stack until this becomes really necessary. And this is how I would achieve this: class RError extends Error { constructor(options = {}) { super(); this.name = options.name; ...
stackexchange/codereview
I have a script and I need to optimize it to reduce the execution time of this, currently, 6000 lines takes 1 minute and 38 seconds, I would like to reduce the time to take much less and I do not know how to optimize it anymore, I paste the script: #! /bin/bash function charge_files () { database="test.db" file="Pr...
stackexchange/codereview
I was recently solving a question on LeetCode platform to delete a node from a Binary Search Tree, I wrote the given below iterative solution, I was wondering if it was a good practice to add a return statement within every if else block, that way the control would never reach the end of the function, however doing tha...
stackexchange/codereview
I wrote a tiny command line tool that converts ADF audio files from the Grand Theft Auto - Vice City game to MP3 files that can be played outside the game. The ADF file format stores the game soundtracks and radio stations. These in turn are just MP3 files that had every byte XORed with the decimal constant 34. My appl...
stackexchange/codereview
The program was to turn an integer into exact change and uses a bunch of if statements. Are there steps a beginner like me can do to remove some or is it just how it will be? I can't find anything on it. At least I'm not sure as I'm still in the basic course. The program is turned in and was fine and this would be fo...
stackexchange/codereview
I am wondering if this is a safe and/or sensible way of going about doing the following task: My problem is that I have a folder with loads of directories with names of form YYYY-MM-DD. They are from my camera. Each directory contains picture files. The problem is that the picture files are designated by just 4 digits ...
stackexchange/codereview
I have developed an implementation of a logger in Python. I know that Python already has a built-in logger, my goal with this is to get feedback and suggestions for improvement, particularly about code structure. Code is here: from .helpers import write_txt from enum import Enum from datetime import datetime # Define...
stackexchange/codereview
The following is my implementation of Reverse Polish Notation. I should have mentioned that this is for a coding question, which asked for unary, binary, ternary, etc. operations that also allows user-defined operators. Would it make more sense to use Factory Pattern to replace the code inside the for loop of RPNIntege...
stackexchange/codereview
In the past few days i have started to learn python 3 in my spare time and i am really enjoying it so far. I have attempted many simple programs such as a palindrome checker and reverse a string in an attempt to improve my skills. I was hoping that someone would be able to provide some feedback on the following program...
stackexchange/codereview
Please take a moment and review my code and tell me how I did. This is the first time in my class (CSC 111) I've been given an assignment in which I had to use a lot of my own resources and develop most of it on my own. Write an application that prompts for and reads a double value representing a monetary amount. T...
stackexchange/codereview
I needed a simple data structure to cache the most recent few directory contents for this project I was working on. I thought a linked hash map would be the right approach since we will cache only one item per path (the key) and keep only X recent items. We will store the timestamp and directory contents as the "payloa...
stackexchange/codereview
I have written a rather simple port scanner using python and I would like to know things I could do better regarding: Code quality, making the code in general better Performance, making the code run faster and more efficient Making the scan more lightweight for the system being scanned so there is no risk of it crashi...
stackexchange/codereview
Being my first time archiving data to the file system, I would like to have my code reviewed. This simple test project works as expected, but I want to see if what I am doing is following best practices. You open the app, put in text for the textfields, press button and strings are saved and displayed in labels. Whe...
stackexchange/codereview
How to shorten up this code? I know there's a way that this kind of code could be shortened, but I don't know how by myself yet. Who can help me? //CHOOSE LEVEL: FROZEN case 1213: sendOption5("Level 1 " + (c.achievedFloor <= 1 ? "@gre@(Achieved)" : "@red@(Not achieved)") + "", "Level 2 " + (...
stackexchange/codereview
I run a build system. Datawise the simplified description would be that I have Configurations and each config has 0..n Builds. Now builds produce artifacts and some of these are stored on server. What I am doing is writing kind of a rule, that sums all the bytes produced per configuration builds and checks if these ar...
stackexchange/codereview
I need to run CPU-intensive tasks on a very old machine with overheating issues. The script below will monitor temperature and pause the jobs when it gets too high, continuing them when it's back to normal. The actual commands run are, of course, not included, since they are irrelevant to the question. I am looking fo...
stackexchange/codereview
I created my own indexOf function. I was wondering if anyone could help me come up with a way to make it more efficient. I am practicing for interviews so the catch is that I cannot use any String methods. I believe the runtime of this method is O(n2) with space of O(n). Correct me if I am wrong. Also, I want to ensure...
stackexchange/codereview
I have this Library to control errors; I would like if you can evaluate it and make a review of the code, not about the goals of the library: Everything works for me correctly, but I am also open to hear about any type of improvement that can be implemented in the code as long as it does not affect the objective of the...
stackexchange/codereview
The code below is an implementation of purely recursive solution to find a powerset of any given set. The input set is a string, and the output - array of strings. Both of them are wrapped into a structure for convenience. The underlying algorithm is pretty common one. The recursive function executes exactly 2^n - 1 t...
stackexchange/codereview
For the problem given: Douglas Hofstadter’s Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle. Pick a positive integer \$n\$ as the start. If \$n\$ is even, divide it by 2. If \$n\$ is odd, multiply it by 3 and add 1. Continue this process until \$n\$ is 1. The thesis is...
stackexchange/codereview
<script> <?php unset($data0); unset($data1); unset($data2); $sth = $dbh->prepare(" SELECT a, b, c FROM t "); $sth->execute(); ?> Morris.Line({ element: 'morris-line-chart', data: [ <?php while ($row = $sth->fetch()) { ?> { m: '<?php echo $row['0']; ?>', a: <?php echo $row['1']; ?>, b: <?php echo $row['2...
stackexchange/codereview
The problem definition can already be found here. Given a chess board with dimensions n × n (where n is up to 100000) and the (r, c) positions of various obstacles, how many squares can a queen at a given position attack? My solution is in Java. Any feedback is welcome. import java.util.HashSet; import java.util.Object...
stackexchange/codereview
I wrote this to consume valid IPv4 addresses in dotted-quad decimal form: def dotted_ip_to_num ip strings = ip.split('.').reverse strings.each_with_index.inject(0) do |sum, pair| str, i = pair sum + str.to_i * (2 ** (i * 8)) end end But my chain of each_with_index and inject (aka left-fold or reduce) loo...
stackexchange/codereview
I have a class whose purpose is to display a comment. I'd like to be able to instantiate it by passing a Comment object if I happen to have it available, or just the values if that's what I have available at the time. Unfortunately PHP doesn't allow overloaded constructors, so here's the workaround I came up with. cl...
stackexchange/codereview
I just finished working on a coding challenge for learning Python 2.7. Essentially, I'm a function that if it is fed a string such as: "The man drank the drink and ate the bread and forgot the drink" I get in return: {'and': {'ate': 1, 'forgot': 1}, 'ate': {'the': 1}, 'bread': {'and': 1}, 'drank': {'the': 1}, 'dri...
stackexchange/codereview
The Helloworld class executes all of the methods. Human is the interface, and Nate & Ryan are two classes that implement the Human interface. Are there any deficiencies or faults that my code contains that could help me in the long run? public class Helloworld{ public static void main(String[] args) { Hum...
stackexchange/codereview
I just filled in the first assignment on course which involves learning Python. The assignment was to make vector class which supports scalar multiplication through operator overloading. The instructions included these constains: There will be one class called MyVector Nothing will be imported in file within that fil...
stackexchange/codereview
In order for Rubberduck to be able to "recognize" the built-in VBA functions, procedures and objects, I added yet another constructor parameter to my Declaration class: public Declaration(QualifiedMemberName qualifiedName, string parentScope, string identifierName, string asTypeName, bool isSelfAssigned, bool isWit...
stackexchange/codereview
I'm trying to teach myself streaming and lambda expressions. Here's the scenario: I have a collection of 10 Thing objects each containing an int[] of 3 random number. I've written code to print out the largest number in each Thing. I've already written two statements and an accompanying method that print the result I w...
stackexchange/codereview