instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I have lots of external shell commands to run. So I gave every command a name and then run it. tar_report_cmd = 'zip -r {0} {1} '%(report_file, _export_dir) exec_proc(tar_report_cmd) mv_report_cmd = "mv {0} {1}".format(report_file,report_dir) exec_proc(mv_report_cmd) But it looks sort of redundant and not beautiful. ...
stackexchange/codereview
I just finished a scraper in python using scrapy. The scraper logs in to a certain page and then scrapes a list of other pages using the authenticated session. It retrieves the title of these pages and puts it in a list of items together with the page name. Because there are little examples to find on continuing scrapi...
stackexchange/codereview
This is my first code in C++. Since I'm new to the language, I'm just looking for pointers on what can be made better. I tried to cut out unnecessary stuff, but there are some comments in there. I know Java, so if you're trying to explain anything in Java, I can understand it. Feel free to mention anything, whether ...
stackexchange/codereview
I am writing a brute-force method to search for a word. Please review my code and tell me how I can improve it. public class Searcher { private static String filepath = null; private static final String defaultPath = "//sample_text"; private Searcher() { this.filepath = defaultPath; } private Searcher(...
stackexchange/codereview
On almost every page in the Stack Exchange Network, there lives a list of some the current "hot" questions across the network (sometimes abbreviated HNQs). Some of these posts have very exotic titles (especially the ones from Arqade) and some have very simple titles. Either way, I've always found it fun to try and gues...
stackexchange/codereview
I wrote a script which logs memory usage of a process (pid in file), and reacts in case a limit is reached. I run the script nightly. In my case, the process concerned propably has a memory leak and locks up the whole system after a couple of days. Hence, the script should reboot the system if excess memory is used. Lo...
stackexchange/codereview
I'm working through Advent of Code 2016 in Rust. The prizes go to the swift, but I'm aiming for well-written code. This is Day 1. To summarize the problem statement, given a instruction string of turns and distances (e.g. "R5, L5, R5, R3"), return the Manhattan distance from the origin (in this case 12). I am using Rus...
stackexchange/codereview
I've written a simple implementation of tail as part of reading The C Programming Language by Kernighan & Ritchie. The question states to write tail, which prints the last n lines of its input. By default, n is 10 but should be able to be specified by writing: tail -n to print the last n lines. I don't think the progra...
stackexchange/codereview
Context I'm doing Advent of Code as a way of learning Rust, and have a working solution to Day 8, Part 1. This involves moving between nodes, starting at AAA and looking for ZZZ, where the next node is determined by the L/R instruction chain in the first line. We loop over the L/R instruction set until ZZZ is found. So...
stackexchange/codereview
I have implemented the integer residue ring \$ \mathbb{Z}/m\mathbb{Z} \$ and the integer multiplicative residue group \$ (\mathbb{Z}/m\mathbb{Z})^* \$. Functionalities include: In \$ \mathbb{Z}/m\mathbb{Z} \$ , you can do addition, subtraction, multiplication and raising elements to a nonnegative integral power. In \$...
stackexchange/codereview
So I got this code; public bool Guest { get { return GetValue("guest", true); } set { SetValue("guest", value); } } I am wondering if it would be possible to shorten that as I would like to keep the code very clean, I've tried some stuff public bool Guest => GetValue("guest", true) Bu...
stackexchange/codereview
I'm investigating some feature for the ScalaDoc tool, which would allow library writers to link to documentation created by third party tools like JavaDoc. My idea is to have some (XML) configuration which specifies which package prefixes belong to which vendor and how to create a valid URL from the the class name, sto...
stackexchange/codereview
I am trying to represent questions in quizzes. The database is Mysql but I am using fairly generic sql. The assumption is that varchar cannot handle more than 255 though, so I am supporting longer text by having multiple text components. There are four primitive kinds of questions: multiple choice, multiple answer, fi...
stackexchange/codereview
How to do optimization and provide less of code here: for _ in _get_valid_json(): if _['size'] != '': available_params = [ {'productSku': _['upcID']}, {'productUPC': _['upc']}, {'productColor': _['color']}, {'p...
stackexchange/codereview
I am trying to pick 3 providers with the highest calculated score based on my algorithm, to recommend them to a user. The recommendation algorithm takes into account a few things. Most are static values, but the one that is dynamic is the physical distance from the user (based on lat/lng). Since each user's location is...
stackexchange/codereview
I am new assembly programming in Linux (x86_64) and I want to make sure that I am programing in a correct way. I wrote a program that just takes an input from the user and then writes his input to stdout SYS_WRITE equ 1 ; write text to stdout SYS_READ equ 0 ; read text from stdin SYS_EXIT equ 60 ; terminate the...
stackexchange/codereview
Here is an earlier attempt to solve the original problem: Solving Sierpinski Triangle in Haskell I was never satisfied with my solution and found it was awkward and twisty. Here is another attempt to solve the same problem using Data.Array and I found that by using mutable arrays the solution becomes much shorter and e...
stackexchange/codereview
Class To Test Some methods hidden for clarity namespace RiPS.Infrastructure.UA { public class UAWorkflowManager { private readonly IContextIOAPI _api; private readonly IUAjoinedRepo _dbJoinedRepo; private readonly IRemindersSystem _remindersSystem; public UAWorkflowManager(ICon...
stackexchange/codereview
I made the following code in C, which is supposed to create a list of booleans $n + 1$ long, such that the $i$'th element is true if $i$ is prime and $i$'th element is false if $i$ is not prime (starting the count from zero). So for n = 10, it is supposed to give [false, false, true, true, false, true, false, true, fal...
stackexchange/codereview
I have spent hours on this code. I am a beginner and open to advice and improvements. I've put # where I feel insecure about the code. It lets you pick your marker, checks winner, checks draw, ask player if want to play again and checks if the square is occupied. #TicTacToe def drawBoard(board): print(' | |')...
stackexchange/codereview
I am working on designing a simple version of a Connect 4 game. Here is my first draft code. I would like some feedback on it, and also required modification for these follow up questions: Add some intelligence in the players to select the column optimally. How will you make the game generic so that it can check for 1...
stackexchange/codereview
I've written a script in VBA in combination with selenium which is able to scrape all the 1000 links from a lazy-loading webpage which displays it's content 20 at a time and doesn't display the full content until it reaches the bottom of that page. However, my script can make this webpage scroll to the end. After colle...
stackexchange/codereview
This is a program I wrote in Python using the BeautifulSoup library. The program scrapes YouTube search results for a given query and extracts data from the channels returned in the search results. I'm just looking for some tips on how to make my code look (and function) better. I removed most of the redundancies but ...
stackexchange/codereview
This is a cocoa app that adds a right click menu option to change whether a file is executable. It works by executing the system command chmod on each of the files. But I want to know if there is a better way to change the permission of a file, such as a cocoa function that can change the permission of a file. What are...
stackexchange/codereview
First I've to indicate that this is my homework. An example of a given input is: s1 = {'p1': (x1, y1), 'p2': (x2, y2)} where all names and coordinations are user input, only the input format is predefined; also p1 is the upper leftmost point and p2 is the lower rightmost point as shown below: I can go on to get area,...
stackexchange/codereview
I am just trying to apply a "mean filter" with C#. The working code below gets window size (3,5,7,9,...) from textBoxWinSize and applies the mean filter. I am new and I want your comments and suggestions about my code so I can improve myself. Can I make it faster? How? Is there any unnecessary or absurd part in the cod...
stackexchange/codereview
Although throwing excptions for control flow is a controversial topic there are some quite popular examples of using this anti-pattern like C#'s async routines throwing the OperationCanceledException to cancel a task or python throwing the StopIteration to control iterators. I thought I'll try to use such an exception ...
stackexchange/codereview
I got a piece of code I'm not pleased with; Does anyone would have a better idea? def myFunc(verbose=True): if not verbose: print = functools.partial(globals()['print'], file=open(os.devnull, 'w')) else: # Required, othewise I got the error 'local print variable was referenced before being decla...
stackexchange/codereview
I have a list of tasks I get from my database (as strings) and then execute. However I'm uncertain on how to implement this correctly. Currently I have implemented this in the following way: Private Sub Monitoring(installationCode As String, drive As String, syncFolder As String) InitializeDatabaseConnection(in...
stackexchange/codereview
I'm a newbie at programming, just one month into C. Working with Stephen Kochan's programming in C. There is a question in chapter 6 to write a printing calculator where 's' tells the program to set the accumulator, 'e' tells that the execution must end. And the operators tell the operations to be performed on the accu...
stackexchange/codereview
(continuation from Speeding up and fixing phone numbers from CSVs with Regex) I'm pulling all of the phone numbers from all CSVs in two different directories, outputting them in a single simple format to two different files, and then comparing those two files for which numbers are in one but not the other. I'm failing ...
stackexchange/codereview
I'm learning ASP.NET and think I figured out ViewState. Can you tell me if I have it right? The goal of the ViewState in this page is simply to keep the value in a DropDownList. So first, let's have the aspx page markup: <%@ Page Title="Parameters" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Cod...
stackexchange/codereview
I am developing a .Net application that involves reading data from XML and writing to HTML. The methods to do these tasks are all in the same class as the data they read/write are properties of objects of that class. The problem is that while they perform their function, they are rather long winded and complex. I would...
stackexchange/codereview
How would I make this code look less ugly? // we are looping over an array of images // width is a parameter passed to the current function // // the resulting string looks like this: "30px 0" // (it's a tool that returns coordinates for a CSS sprite) // when iterating over the first item, we don't need // to add "-"...
stackexchange/codereview
This is my very first program that using threads. I use C++11 standard threads and I run it on Linux. The program creates two threads that sums all the elements in a vector together. The first created thread sums the left half of the vector and the other thread sums the right part of the vector. The main thread runs un...
stackexchange/codereview
[Base on https://codeforces.com/contest/1360/problem/G] So my logic is to process each column at a time and find b rows such that the total 1s in them is less than a and if there are many candidates I take the rows with least 1s. import Data.List import Data.Array import Control.Monad -- i...
stackexchange/codereview
First I work on all of my projects alone, and I feel like I need my code to be reviewed by others and deep dive into performance and best practice ... etc. I created a simple jQuery plugin that excerpts text of an element depending on whether lines / characters count. If option of type was set to chars the method of _...
stackexchange/codereview
I am trying to implement DSs in C++ and this is BST insert and search functions. I tried in two different ways, please review and see if one is advantageous over other. With pointer to pointer #include <stdio.h> #include <iostream> struct BstNode{ int data; BstNode* left; BstNode* right; }; BstNode* NewNode(int da...
stackexchange/codereview
This is a simple guessing game I have made, an improvised one. I will do a GUI version of this shortly. I'm looking for comments and interesting code ideas. import random sec_no = random.randint(0, 10) ncount = 0 att = 5 while True: sec_no = random.randint(0, 10) ncount = 0 att = 4 minp = input('''...
stackexchange/codereview
I'm new to programming and have created a simple Rock, Paper, Scissors game. The entire program is under a single class and the main method. I hear that's probably not the best way to code. How should I have written this to utilize multiple classes or to adhere to best practice? import java.util.Random; import java....
stackexchange/codereview
Please review my code based off of a responsive Initializr template. It's functional and visually correct, but I know there's better ways to write the code. Let me know if I can layout the HTML5 better and/or best practices I'm not using for CSS selectors because I feel my stylesheet is all over the place. HTML <!D...
stackexchange/codereview
Consider the following two tables in a PostgreSQL database: create table if not exists public.users ( id text primary key, is_staff boolean ); create table if not exists public.issues ( id int primary key, issue_owner text not null references public.users on delete restrict ); alter table public.issues enable...
stackexchange/codereview
I have an interesting problem with my chess application. The application reads PGN files, and at any time while viewing a game from the file, the function below, when called, iterates over the chessboard, gets the square names for each piece, and then constructs a string containing the description of which piece is whe...
stackexchange/codereview
I was doing an exercise in PHP, and it works perfectly, no problems. But I think that maybe I coded it so long, and I think it can be shorter than it is now, but I don't know how to make it shorter and that works exactly the same way. I will explain what this code is doing for you so it's faster if you are going to hel...
stackexchange/codereview
I'm looking to increase the conciseness of this code. I realize that I can use Joda (or Java 8's new date API), but if I were to keep this to just Java 7, any suggestions? (I care less about whitespace and formatting.) /** * Tests whether the date input represents * a real date in mm/dd/YYYY format that is after th...
stackexchange/codereview
I have a grid in which i have to display some/all fields of a Java Class, this grid displays the List of elements of that class type. I have to sort this list provided: Class type of the List item Field name of the class to be sorted to get field from a class by field name private static <T> Field getField(Class<T> c...
stackexchange/codereview
I have this function to ease out the task of inserting data into databases. I am not very sure if it is secure to use it this way. Any suggestions on improving it? function insert_into($query,$datatype) { //$i=0; num=1; $i=1; num=2; for(i=1;) $num=func_num_args()-1; global $CONN;//set the g...
stackexchange/codereview
I'm new to iOS development and also Swift. I'm working on a project consisting of a menu that leads to my various experimentations with the iOS SDK. I've written the menu titles and segueIdentifiers in a plist and I'm populating an array of NavigationItem in viewDidLoad(). Is the following code idiomatic, particularly ...
stackexchange/codereview
This is a budgeting script I wrote for myself that now works perfectly as planned. I just wanted the Code Review community to help me make any improvements and/or optimizations that they deem necessary. #!/usr/bin/python # Accounting.py - A simple command line based budgeting software with the # ability to have data sa...
stackexchange/codereview
I would like to know how I might improve my code? I just started coding and liking it a few days ago so I am quite new to this whole world... The objective is to calculate the amount of water one has drunk in a day. Depending on the user's input, the app tells him or her if the amount of water drunk is great or not. N...
stackexchange/codereview
This code works and does exactly as I want, but I am wondering if/how it could be done faster/more efficiently? This runs quickly on a demo file, but bogs down when I introduce much larger files (3-100GB). Premise: Take a large list of latitudes and longitudes remove the negative values (WGS1984) and put them into a No...
stackexchange/codereview
I am working on a simple web crawler that returns the start time and date for an event listed on a webpage. The webpage can be in two different formats and there are multiple other dates listed on the page. The part of the webpage I am scanning looks like this: ... <h4>Time</h4> <p> Starts: <time itemprop=...
stackexchange/codereview
I have been trying to write a number guessing game and I am trying to condense the second while loop when guess =! random_number. I can't figure out if there is any better way to shorten the code but to still achieve the same result. I wonder if someone is able to help me out. If there's anything else which is redunda...
stackexchange/codereview
I am trying to write a ruby script that will take all of the CSVs in a given directory and map their headers out so that duplicate columns will match up and columns unique to a file will have their own column in the final data file. The following code produces the output I desire, however something about it seems overl...
stackexchange/codereview
I've been reading about loops this morning, to try to improve this snippet of code: $deliveryoutcode1 = array(); $deliveryoutcode1 = explode(",",$rows['deliveryoutcode1']); $deliveryoutcode2 = array(); $deliveryoutcode2 = explode(",",$rows['deliveryoutcode2']); $deliveryoutcode3 = array(); $deliveryoutcode3 = explode("...
stackexchange/codereview
I have the following DAOParent class that I use to put connect/disconnect code in one place. Each DAO class in the application is an EJB that extends DAOParent (note that I don't use JPA): public class DAOParent { private InitialContext context = null; private DataSource ds = null; private Connection conn ...
stackexchange/codereview
I have an initialize method for a class that looks like this: def initialize( site:, name:, date_online: '-', date_offline: '-', date_modified: '-', date_tagged: '-', tags: [] ) @site = site @name = name @date_online = date_online @date_offline = date_offline @date_modified ...
stackexchange/codereview
Project structure without code: Packages: Classes in packages: In ConfigConstants I store path to folder, where I save pictures. Also in WebConstants I store URL of Servlet. Here is mySQL script for creating db: drop database meme_exchanger; CREATE SCHEMA `meme_exchanger` DEFAULT CHARACTER SET utf8 ; use meme_exch...
stackexchange/codereview
Based on a question I asked on SO, I have come up with the following solution. As I am very new to Python Qt, I would like a review rather than just add it as an answer in SO. The code runs a script in another thread. That script needs to open a file dialog to get another file from the user. To do that, I pass a signal...
stackexchange/codereview
I have a list of 2,888,991 channel objects. Each object has a name and a sample rate. I am trying to put them into a QTreeView. Each channel name is split on ':' '-' and '_'. If the name is H1:IOP-LSC0_DCU_ID and the sample rate is 16.0 then it should go into the tree as: H1 IOP LSC0 H1:IOP-LSC0...
stackexchange/codereview
I'm trying to brush up on my Python, so I'm going through some simple problems. Big concerns are style, though any algorithmic problems I'm open to suggestions on. Basically you have an input file where the first line is the number of test cases. The following lines are composed of the cases. Each case starts with a n...
stackexchange/codereview
For this task, you're going to play a dice game, but first you must prepare for an overwhelming victory. The game itself is very simple. Both players roll a single die and whoever rolls highest scores a point. (On a tie, both players must reroll until someone scores.) These aren't standard dice however. Each pla...
stackexchange/codereview
Explanation : I am adding new elements in the list until the window runs out. Head will have the earliest element and tail will have the most recent element. Once the window is over, every addition requires deletion of the very first element or least used in the list which was temporally inserted a lot earlier than oth...
stackexchange/codereview
I wrote this factory class in order to pass parameter to Singlton class, is it a good design in term of design for multithreading environment? public static class LoggingServiceFactory { private static string _connectionstring; private static readonly Lazy<LoggingService> _INSTANCE = new Lazy<LoggingService>(()...
stackexchange/codereview
The problem I have is to find the sum of 2 linked lists. Each linked list node contains 1 digit that represents a number. My algorithm works but I was wondering if there is a more efficient (speed and memory wise) to solve this problem OR maybe some minor tweaks I can do to reduce space and runtime. Example: 7 -> 5 -> ...
stackexchange/codereview
I have created the following function which filters a linked list in place (here it removes all instances of the element k), but it could easily be modified to take a function pointer as an argument and filter on something else. Any ideas on how to improve the code? typedef struct list_integer { type value; str...
stackexchange/codereview
I have a neural network that I am training on a loss function composed of two terms (i.e. loss = loss1 + loss2). Ideally, I would like for both loss1 and loss2 to simultaneously decrease. Although I am wondering, is there any way to ensure neither loss1 nor loss2 increase during training, i.e. while minimizing loss is ...
stackexchange/codereview
I have code that is identical minus two changes that would happen each time, which I can use variable for, but I don't want to use a bunch of if statements. C = 1 fnd = Sheet1.Cells(C, 8) While InStr(fnd, "Customer Name:") <= 0 And C <= 300 C = C + 1 fnd = Sheet1.Cells(C, 8) Wend If C >= 300 Then Sheet2.Cells(r, 2) = "...
stackexchange/codereview
I've been working on this game for a couple weeks now as a purely personal project to help myself learn Java. I'd like to know if I'm on the right track with my project. Items I'd like specific feedback on: GridBagLayout - I think I'm working this out okay? Classes - Do I need to break parts of this up into other pi...
stackexchange/codereview
An array is defined to be maxmin equal if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array. ...
stackexchange/codereview
I am doing a code challenge of codesignal.com which ask for following things: Given an array of integers, sort its elements by the difference of their largest and smallest digits. In the case of a tie, that with the larger index in the array should come first. Example For a = [152, 23, 7, 887, 243], the output should b...
stackexchange/codereview
I've never participated in a codereview before and I was pointed that I should in another thread for a slow query. var longReturnListt =await (from i in db.Inventory_Vehicles join l in db.Inventory_Descriptions on new {inv = i.ID, cli = i.ClientID} equals new {inv = l.Inv...
stackexchange/codereview
This snippet is about detecting whether the carry flag is set or cleared. I work on Mac OSX, so my snippet supports Mac only. First, we need a routine that does the job: func.s: global _read_carry_flag _read_carry_flag: mov al, 0 jnc end mov al, 1 end: ret (Try nasm2 -f macho64 func.s for compiling ...
stackexchange/codereview
The code bellow is code of "Hello" message handler. It works, but I really don't like as it looks. The "hello" protocol contains three messages: client -> server: diffie-hellman client public parameters server -> client: diffie-hellman server public parameters client -> server: used data Could you please review the c...
stackexchange/codereview
I have been working on the following kata from CodeWars. It's basically a Caesar Cipher — see the test cases below my solution code. Any comments/feedback appreciated! def encryptor(key, message): new = "" for letter in message: if letter.isalpha(): id = ord(letter) shift = id+...
stackexchange/codereview
The reliability polynomial (specifically, the all-terminal reliability polynomial) is, given a value \$0 \le p \le 1\$, outputs the probability that a given graph \$G\$ is connected. Note: at the link given, the probability is given to an edge being deleted, and not to an edge existing (which is the definition we will ...
stackexchange/codereview
I have written a small password manager script for my own purposes. It is hosted locally and cannot be accessed outside my local network. You can see the code on GutHub I know it is better to encrypt the passwords before storing them in the database, but how to retrieve them back when viewing the record? I mean I don't...
stackexchange/codereview
I've created a Christmas tree using only HTML and CSS. It's pretty sure that the code can be written in a more efficient way. Also, the lights are turning on and off at the same time, is there a way to make them work independently? body { background-color: #9fd8ee; } .tree { display: flex; flex-direction: colu...
stackexchange/codereview
I have written the following Bash script which includes an Nginx WordPress bootstrapper: A program establish WordPress apps fast on a Debian-Nginx environment. It utilizes CertBot for HTTPS, SSHguard for protection from BFA (see Nginx conf), WP-CLI for creating a WP app dir and conf file fast, MySQL CLI to create a dbs...
stackexchange/codereview
I want to convert int64 to custom base 64 number string, with this specification: 0..9 -> 0..9 10..35 -> a..z 36..61 -> A..Z 62 -> _ 63 -> - Is this implementation correct/efficient? func EncodeLogKey(id int64) string { str := make([]byte,0,12) if id == 0 { return "0" } for id>0 { var ch rune m...
stackexchange/codereview
I'm required to calculate the average value of all nodes in a BST using a Visitor, I'm not sure if I did this correctly or if i could just calculate the average with inOrder() and therefore I'm not really utilizing the visitor. import java.util.*; public class Node{ int val; Node left; Node right; pri...
stackexchange/codereview
I am currently working on a project that classifies tweets based on certain categories of information they belong to (7 given categories for his project). For example, a tweet with the keywords "I think NY should ban smoking" should be classified as a tweet in the "Pollution" category with negative sentiment. I have b...
stackexchange/codereview
I'd highly appreciate it if you can: Spot flaws, especially bad practices and suggest a possible alternative method. Spot inefficiencies and suggest how to perform that task efficiently. You may review my HTML/CSS as well. var addRecordFormVisibility = false; var addRecordForm = document.getElementById('addRecord')...
stackexchange/codereview
So I'm making my own singly linked list class, with methods that you'd expect such as remove() and insert(). I don't use pointers that much (almost never), so I thought by making a SLL class it would be good practice for me. But I'm not sure if I'm deallocating my memory correctly. Here's the structure of my SLL: class...
stackexchange/codereview
Below is my code for generating a random string of random length. I am using it in integration tests. Currently I have almost 2000 tests running each time a commit is made to master and a few of those tests are using this class. I would like to make sure the code is optimized so that the tests complete as quickly as po...
stackexchange/codereview
In reply to previous question I rewrote ColumnReader and would like more suggestions using System; namespace R2D.IO { public sealed class LineReader { public string NewLine { get; set; } string _buffer = ""; public void Parse(string text) { _buffer += text; ...
stackexchange/codereview
What I'm trying to do here is first set the first eight variables to the proper default values. That's the first area I'm thinking there might be a way to optimize. Is there anyway to set both variables at once for example I know in PHP I could do $title=$d_title="value"; Is there any way to consolidate that section? (...
stackexchange/codereview
The task is to find the longest common prefix. While I had no trouble to find the solution, I'm interested in the statistics of my code: Runtime: 7 ms, faster than 56.36% of C++ online submissions for Longest Common Prefix. Memory Usage: 9.3 MB, less than 54.46% of C++ online submissions for Longest Common Prefix. Al...
stackexchange/codereview
Consider the MCG with parameters: a = 23, M = 10^8 + 1, and let the seed be 47594118. (This is the original MCG proposed by Lehmer in 1948.) Apply the Kolmogorov-Smirnov test to the first 1000 random numbers (including the seed) from this generator. Compute the KS-statistic and find its p-value. What is your conclusio...
stackexchange/codereview
I'm doing a CodingBat exercise and would like to learn to write code in the most efficient way. On this exercise, I was just wondering if there's a shorter way to write this code. monkeyTrouble(true, true) → true monkeyTrouble(false, false) → true monkeyTrouble(true, false) → false public boolean monkeyTrouble(boolean...
stackexchange/codereview
Please review the code. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>RGB to HEX (and vice versa) converter</title> <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.0/normalize.min.css"> <style> body{ color: #222; font-family: "Segoe ...
stackexchange/codereview
I'm writing a URL validator. Firstly, it checks for special characters in the input. Secondly, it adds 'http://' and checks for validity. /* Returns true if url is valid */ private static boolean isValidURL(String url) { boolean containsSpecialCharacters = specialCharactersExists(url); if ( !con...
stackexchange/codereview
I have two questions. Does it make sense to test that an event will not be fired? If yes, what is the best way to accomplish that using the xUnit framework? For example I have a class with a single property Mark, public class Box : INotifyPropertyChanged { private Marking mark = Marking.None; ...
stackexchange/codereview
Today I tried to learn how to make a simple garbage collector for a future project, it didn't need to be fast nor complex nor optimal, it just needed to work. After lots of searching and reading, I was able to make something work. So, how can I improve it from here? At some point I guess I'll have to ditch the std::arr...
stackexchange/codereview
I wrote this code, based on the Newton-Raphson method, to find the square root of a number. I'm wondering how I can optimise this code, as I am out of ideas. #include <stdio.h> int main(void) { float n, x, i; printf("Enter the number you wish to find the square root of.\n"); printf("\n"); scanf("%...
stackexchange/codereview
im developing a program that will read text files and convert it to JSON format dynamically. Users are able to input the key name and their respective digit to slice the index from a raw text file. Everything is working fine when reading a small size file, but whenever the text files is huge, the program will load like...
stackexchange/codereview
I have a string like "food | dairy | milk". The string may consist of more or less words. How do I turn it into a dictionary {'food': {'dairy': {'milk': {'eco': {}}}}}? The only way I could achieve it was to create a string and then turn it into a dictionary using exec. I understand it's messy. How could I improve on i...
stackexchange/codereview
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you! Problem Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal. For example, "tars" and "rats" are similar (swap...
stackexchange/codereview
In working on this answer it occurred to me that it might be interesting to further expand the idea. The game This is an extremely simple (and boring!) text-based game that creates a few monsters which attack the player and which the player can attack. The goal is for player to defeats all of the monsters before dying...
stackexchange/codereview
Background I came up with this solution to a question that I posted on stackoverflow. It uses Tkinter to create a file select dialog window and raise it to the topmost position from jupyter notebook. Questions 1) Is there some kind of built in or canonical way to do this in jupyter notebook that I've missed in my sear...
stackexchange/codereview