instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I want to split the following String into java ArrayList "[\"1-72\",\"1-111\",\"1-4\"]" I had wrote a very rough solution but not sure how to enhance it: String sample = "\"[\"1-72\",\"1-111\",\"157f9d3dfb4-4\"]\""; sample = sample.replaceAll("\"", ""); //to replace double quote sample = sample.replaceAll("\\[", ...
stackexchange/codereview
I'm trying to learn digital design this summer and currently going through this excercise of creating a 32-bit ALU based on this schematic: Im using the + operator to create an adder, but I need to grab the carry out for use in my carry flag. Should I just hard code an adder instead of using the + operator? I pretty m...
stackexchange/codereview
I started to learn Python not long ago to automate certain tasks I work on. I want to optimize a script I wrote that takes a line in an Excel file and prints a pattern of text based on this line's content. Here's an example of output from my code: mgmt_cli add access-rule layer "network" position bottom name "thirdline...
stackexchange/codereview
In a ray tracing project that I'm trying to make compile-time (constexpr) for fun and challenge, I've run into a bit of an issue: I have an object (intersection) that needs to refer to one of a group of other objects (shapes). Now, my understanding is that you cannot use polymorphism / virtual methods with constexpr be...
stackexchange/codereview
During a code review the following approach of delivering content conditionally dependent upon the state of the user was rejected as adverse to performance due to its multiple use of RenderAction, and instead the approach of RenderPartial was preferred. In order to take this approach it would be necessary to include co...
stackexchange/codereview
I am trying to create a function for a larger script to determine the third octet of a site IP address based off a user entered site number. I have actually come up with the function, but was hoping that someone could help me come up with something that is simpler and more elegant, instead of the multitude of nested if...
stackexchange/codereview
This set of questions are related to a project I've published for converting characters, or strings, to Hex based Unicode; eg... toUnicode.fromCharacter(''); //> 1f34d toUnicode.fromString('Spam!', '0x'); //> ['0x53', '0x70', '0x61', '0x6d', '0x21'] Questions Are there any mistakes, such as unaccounted for edge-case...
stackexchange/codereview
I made a script in JavaScript to calculate how long it takes until a certain date. Do you find it user-friendly enough? Is the code correct? var object = "object" function formatDate(date) { // get the date in proper format var d = new Date(date), month = '' + (d.getMonth() + 1), day = '' + d.getDate(), yea...
stackexchange/codereview
I have tried to make modification in below specified code by removing synchronized and replacing Integer with AtomicInteger . Is it correct and going to ensure that code does not run into synchronization issue? /** * */ package com.ciena.ems.server.system.dataManager.layer1Connection; import java.util.Hashtable; i...
stackexchange/codereview
I tried to look up and suck in most of the information about optimizing this operation and this is what I came up with. As it's pretty much core of the game, I really would like to have it performant as much as I can. I would appreciate if someone can take a look at this and possibly find weak spots. Note: I am using B...
stackexchange/codereview
I've read several places that say it's really bad to use append, and I understand why. I read somewhere that it was never even correct to use append. However, I was working on a textbook exercise in Essentials of Programming Languages (Ex 1.21 pg27) that asked me to write a Cartesian product function. I couldn't think ...
stackexchange/codereview
This is the first thing I've written in Perl besides one-liners. It just generates random text based on a text file. I was inspired by this. Any tips on making this better are welcome. I'd especially like to know if there are more idiomatic ways I could do certain things. #!/usr/bin/env perl use strict; use warnings; u...
stackexchange/codereview
I commonly run into the need to implement IDisposable in my code. To correctly dispose of both managed and unmanaged resources requires a reasonable amount of boilerplate code. Based on the documentation found here I have created the following base class. My intent is that any object I create that needs to dispose of r...
stackexchange/codereview
I have some directories with artifacts in them, and I want to clean them up by deleting them. The requirements are: Keep the 3 most recent directories Keep only one snapshot folder Keep only one rc folder Delete everything else The print commands should be written to a log file for posterity This code is in the root ...
stackexchange/codereview
I created this class to load in an image and get some specific values I needed. from PIL import Image import pandas as pd class Img: def __init__(self,filename): self.name = filename self.image = Image.open(self.name) # open image using PIL # convert the image to a pandas df self....
stackexchange/codereview
I am implementing some of the architectural designs from Google I/O's app to my own app, but I have come across something in their app that has created some confusion for me. They have a domain layer with repository usecases, which I use myself in my apps usually. However, I do have to provide these usecases with dagge...
stackexchange/codereview
I built a simple Node app, and the code "works", with no failures, no syntax errors, and does not break, but one component doesn't work right. I showed a snippet on Stack Overflow, in this question, but viewers found no issue. So, I think the infrastructure, the method, in which I put this app together must be problema...
stackexchange/codereview
I present my implementation of an "ArrayView". I am totally aware the standard nowadays provides such facilities, but for the purpose of learning generic template coding (or is template meta programming anyway) I tried to implement my very own version. My aim was to avoid any runtime operation as far as possible, so th...
stackexchange/codereview
I'm learining JS. I have prepared a simple color flooding game, like Pixelated. The engine below works, though scoring is not implemented. Please help me find out how this code could be made better, more idiomatic JavaScript, or more efficient. // global variables var canvas = document.getElementById("game"); var co...
stackexchange/codereview
Please refer to this problem from Hackerrank HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity. If the amount spent by a client on a particular day is greater than or equal to the client's median spending for a trailing number of days, they send the clien...
stackexchange/codereview
Here's an odd pattern I found for sieving out composite numbers to find primes. I wrote it myself, originally thinking I made an indexing error, but it turned out to work after removing squares. import bitarray def sieve(n): """bitarray sieve""" b=bitarray.bitarray([1]*(n+1)) x=int(n**.5)+1 for k in ran...
stackexchange/codereview
I wrote a Java NIO Echo Server and want to maximize the number of connections to the server. The problem is that when I try to connect more than 10k clients the clients get their connections refused: error Connection Refused : no further information available. The client program that I use generates a batch of 50 cl...
stackexchange/codereview
I am working on a PHP/MySQL application that uses a different time zone from the server it runs on, and neither of the timezones are UTC. I'm converting displayed times to be in the user's timezone, and am wondering whether my approach is sensible. I would love any feedback you might have. Firstly, the application's ...
stackexchange/codereview
class Class1 { private bool _noise = false; private bool _cmbGrammageSelected = false; private bool _cmbSize1Selected = false; private bool _cmbSize2Selected = false; private static refine() The Section below was my trying to refactor, but I did not want to convert the ot...
stackexchange/codereview
Here's a class I made in java. It's pretty simple, the description of what it does is in the comment. I'd appreciate any feedback. import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * An unordered, duplicate-allowing collection of items that are added with a * time-to-live, and will au...
stackexchange/codereview
Here's my first program in C, which is not my first language. I have been reading Modern C and I attempted this challenge on page 26. The prior pages are pretty much the only exposure I have had to C, for reference. I have a rough understanding of pointers but I have read no formal material on the subject. #include <st...
stackexchange/codereview
Help me with code code review. Helium is my pet project, written in Golang. Helium is a small, simple, modular constructor with some pre-built components. https://github.com/im-kulikov/helium Simple example how to use it package main import ( "context" "github.com/davecgh/go-spew/spew" "github.com/im-kul...
stackexchange/codereview
ERROR: type should be string, got "https://leetcode.com/problems/sliding-window-median/\n\nMedian is the middle value in an ordered integer list. If the size of\n the list is even, there is no middle value. So the median is the mean\n of the two middle value.\nExamples: [2,3,4] , the median is 3\n[2,3], the median is (2 + 3) / 2 = 2.5\nGiven an array nums, there is a sliding window of size k which is\n moving from the very left of the array to the very right. You can only\n see the k numbers in the window. Each time the sliding window moves\n right by one position. Your job is to output the median array for each\n window in the original array.\nFor example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.\n\n\n\nTherefore, return the median sliding window as [1,-1,-1,3,5,6].\nNote: You may assume k is always valid, ie: k is always smaller than\n input array's size for non-empty array. Answers within 10^-5 of the\n actual value will be accepted as correct.\n\nPlease review for performance. also I am not sure about GetID function is there a smarter way to get the same result of unique number and sorting for median? \nusing System;\nusing System.Collections.Generic;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace TreeQuestions\n{\n /// <summary>\n /// https://leetcode.com/problems/sliding-window-median/\n /// </summary>\n [TestClass]\n public class SlidingWindowMedianTest\n {\n [TestMethod]\n public void ExampleTest()\n {\n int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 };\n int k = 3;\n double[] expected = { 1, -1, -1, 3, 5, 6 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n\n [TestMethod]\n public void ExampleTestFailed()\n {\n int[] nums = { 1, 4, 2, 3 };\n int k = 4;\n double[] expected = { 2.5 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n\n [TestMethod]\n public void ExampleTestOverFlow()\n {\n int[] nums = { 2147483647, 2147483647 };\n int k = 2;\n double[] expected = { 2147483647.0 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n\n [TestMethod]\n public void ExampleFailed2()\n {\n int[] nums = { 5, 2, 2, 7, 3, 7, 9, 0, 2, 3 };\n int k = 9;\n double[] expected = { 3.0, 3.0 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n }\n\n\n\n public class SlidingWindowMedian\n {\n public static double[] MedianSlidingWindow(int[] nums, int k)\n {\n var res = new List<double>();\n var med = new SortedList<long, int>();\n for (int i = 0; i < nums.Length; i++)\n {\n med.Add(GetId(i, nums), nums[i]);\n if (med.Count > k)\n {\n med.Remove(GetId(i - k, nums));\n }\n\n if (med.Count == k)\n {\n if (k % 2 == 0)\n {\n res.Add( ((long)med[med.Keys[k / 2 - 1]] + med[med.Keys[k / 2]])/2.0 );\n }\n else\n {\n res.Add(med[med.Keys[k / 2]]);\n }\n }\n }\n return res.ToArray();\n\n }\n\n private static long GetId(int i, int[] nums)\n {\n return Convert.ToInt64(nums[i]) * nums.Length + i;\n }\n }\n\n}\n\n"
stackexchange/codereview
I have the need for load balancing in my MSD-radix sort routine and doing it optimally is not an option. So I tried to play with two simple routines for putting integers into a prespecified amount of buckets such that the sums of buckets are "close" to each other. My main question is: Can you suggest more optimal, poly...
stackexchange/codereview
This is an iterative implementation of alpha beta tree search in C#. Please help me confirm the correctness of my code. search() is called when the search begins. int depth; Func<board, int> value; Func<board, List<string>> legalmoves; Random randomgenerator = new Random(); board board; Stack<int> alphas = new Stack...
stackexchange/codereview
I have finished my first Android App, but I am getting lots of skipped frame messages from Choreographer. So, I started reading and got the impression that I should put as less calculations/works as possible in main thread, rather should use AsyncTask. To understand the thumb rule, can anybody please validate my code w...
stackexchange/codereview
In my sample data table below, all datatypes are varchar(255). | event | timestamp | traceid | | accepted | 2016-01-16T09:35:48.653418931Z | AIP1452936948-44467 | | published_event | 2016-01-16T09:35:48.659767348Z | AIP1452936948-44467 | Here is the expected output: ...
stackexchange/codereview
This is citty.py, part of the citty repository. It's formatted using black, so I'm not super worried about small style items. I'd like a review with suggestions for other, better practices -- choice of technologies or implementations (e.g., "use xml instead of json", or "use goodpackage instead of badpackage"), approac...
stackexchange/codereview
I am using this code on my own personal website (my personal administration site) so it doesn't need any security and so on. I am not into learning everything about that yet, and although I do know a lot about it already, it is not the case for this code. My order/sort links are looking like this: {{ URL::route('events...
stackexchange/codereview
Template IO Module This is a single-file, header-only input validation with two variadic output functions. One output function simply inserts a new line char after every output and the other one inserts a space; this is the only difference. The end goal of this project is a convenient, cross-platform IO module, and I t...
stackexchange/codereview
I have known about unit testing for a while now, but I am just now finally understanding how to implement it. I think that my initial implementation is a little rough so I could use some feedback. I have implemented these tests in order to verify that a new feature of my strategy game is working properly. Previously,...
stackexchange/codereview
The script should be a single python file that takes an excel file (or csv). Each row represents one switch. For each switch, there will be one or more interfaces. The objective is to output a script of commands to execute to configure each switch, as specified. For example, Row 1 is below: switch1 Eth1 trunk ...
stackexchange/codereview
Let's say we have the following class which performs interpolation on irregularly spaced data: template<class Real> class interpolator { public: interpolator(const Real* const x, const Real* const y, size_t length) { m_x.resize(length); m_y.resize(length); for (size_t i = 0; i < length; ...
stackexchange/codereview
I made a simply user vs. computer game on Tic Tac Toe. I used Object Oriented Programming to increase my understanding of this programming paradigm. Can you criticize any design flaws I have in my code? #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 15 20:56:48 2018 @author: von-vic """ import r...
stackexchange/codereview
I've posted a similar program previously, but I have not made any major modifications in the code, so I am posting it again by deleting the previous question. I am afraid of the thread keyword and I am not too familiar with threads and blocking, so can you please review this code for me? Is the use of future enough or ...
stackexchange/codereview
I am working on learning more about arrays and loops! I have been trying to create a method which will allow me to take for example an unlimited amount of arrays and append or concatenate them to each other! The method takes multiple arrays as arguments and creates a merged array in the order in which the arrays where...
stackexchange/codereview
Not long ago, I was asked about how many lines of code I have written in C++ and could not answer that question. For this reason and to become more familiar with Bash shell scripting, I wrote a small system to monitor the lines of code written in a specific subdirectory. Currently, I count the lines of code at 5 second...
stackexchange/codereview
Please help me improve my code. Note that it runs just fine. Especially with the way I use SFML, I need lots of guidance since I've just started learning how to use this library. I'm still learning C++ as well. main.cpp #include <SFML/Graphics.hpp> #include "counter.hpp" std::string day(int num) { return (num!=1)? "s...
stackexchange/codereview
I am a Haskell beginner. Here is my function to find prime factors of a number primes = 2:takePrimes [3, 5 ..] where takePrimes (x:xs) = let smallPrimes = untilRoot x primes in if 0 `notElem` (map (mod x) smallPrimes) then x:takePrimes xs ...
stackexchange/codereview
I wrote a program for a basic AI with voice recognition that makes request to News API to retrieve metadata for the headlines currently published on a range of news sources and blogs. For now it does everything I need it to do. What I want to do is improve the quality of the code with best practices and I am hoping som...
stackexchange/codereview
The story... A bit of background info and how is the database designed... Please notice you don't really have to rebuild the tables in SQL but I shared an SQL Fiddle just in case and screenshots1 of what the database looks like. I thought it was going to be easier to explain the story of what I am doing + you can alway...
stackexchange/codereview
I am a newbie to C++ programming and am currently reading this book called Jumping to C++ by Alex Allain. I have finished the pointers chapter and I am doing the exercises at the end of the chapter. The following paragraphs are the exercises and included are my own solutions: Write a function that prompts the user to...
stackexchange/codereview
The tests are taken from this answer on an insertion sort in rust question. The algorithm is taken from Algorithms in a Nutshell (2nd Edition). I'm not looking at crazy performance, the goal being to learn about basic algorithms and rust, but if there is something shockingly inefficient please let me know. fn main() {}...
stackexchange/codereview
Which of these 2 functions is better and more readable and why? (Both functions do the same thing). My goal is to get the total time of a series, using the TMDB API (which has a limit of 20 different things in the append_to_response parameter). async function getSeriesRuntime1(tmdbId: number, numberOfSeasons: numbe...
stackexchange/codereview
I have made a successful test page that satisfies my goals of using JavaScript ( jQuery specifically ) to add and remove content from a webpage. <!doctype html> <head> <title>test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="main"></div> <s...
stackexchange/codereview
This is my solution to CodingBat problem p150113. My Java knowledge is from 2011 and I'd like to know if this is still the optimal way to approach such a problem. and if my code is clean and understandable. We'll say that 2 strings "match" if they are non-empty and their first chars are the same. Loop over and then r...
stackexchange/codereview
I am trying to puzzle out api based user registration for a service I am building, but I have a strong feeling that my code is not optimal. It feels like passing "state" in the way I did prevents the server from being multithreaded, as I have no clue how actix could share data that isn't Send or Sync across multiple th...
stackexchange/codereview
Here is my working attempt to allow multiple/infinite child record entries with the original parent post in .NET MVC. Any refactoring to simplify my code would be greatly appreciated: Controller: public ActionResult Create() { EquipmentLicense equipmentlicense = new EquipmentLicense(); equipmentlicense.Equipme...
stackexchange/codereview
What do you think about the following approach to CRUD? Here is the reading+pagination example. DTO types have Dto* prefix, EF Entity Types have E* prefix. DAL example: class UserQuery : PagingQuery { public int CompanyId { get; set; } } interface IUserReader { IPage<DtoUser> Read(UserQuery query); } class User...
stackexchange/codereview
I wrote a function template to compute the GCD of two integers. This function checks that its arguments are an integral type. I also wrote a function template which accepts a pair of iterators in order to compute the GCD of two or more integers. It calls the first function to compute the GCD of pairs of integers. Here ...
stackexchange/codereview
I am diving into Data Analysis with pandas, and I have just written this Python script to calculate the average of hotel review scores of each country. The dataset contains an individual average score for each customer review, like: 8.86 or 7.95. My goal was to average all these individual scores for a particular count...
stackexchange/codereview
One of the companies I was recently interviewing with gave me a following task to implement in a day or two using .Net, just to see where my coding abilities are at: Implement a Web API that gets webhook on POST and enters it to DB Enter the data first to collection, then read from this collection (other thread), and ...
stackexchange/codereview
I have written this class to check internet connectivity on Android, while there are many instances when WiFi is connected is taken as an implication that internet is connected as well. I wanted to have a method which actually checks if internet is connected. One issue was to run the internet code in a background threa...
stackexchange/codereview
The purpose of this class is to wrap a std::vector in a class so that never a new object is added. We don't allocate a new object on the stack but we trying to fit it on the current memory page, or create a new page for it. #include <vector> template<class T> class PagedVector { public : PagedVector(int initialC...
stackexchange/codereview
I recently developed a simple treap data structure in C#. In the future, I may have the class extend IDictionary. For now, I only expose a public accessor and a delete method. public TValue this[TKey key] { get { return Get(root, key).Value; } set { root = Set(root, new Node(key, value)); } ...
stackexchange/codereview
I'm a CS Student and I've coded a program to compute Grade Point Average (a metric used in the US for a student's performance across the curriculum). I'm looking for your suggestions and comments for my code. I used sentinel controlled loop and for loop. Is there any way for improvement?? //Sentinel-Controlled GPA Calc...
stackexchange/codereview
In context of preparing for a coding interview, I gave the division problem a go using Java. This is what I came up with. It's a little bit different to other solutions I've come across the interweb. Implement integer division without using multiplication or repeated subtraction (i.e. to divide n by d, you man not rep...
stackexchange/codereview
I've been watching digital technology in the last few days. This has aroused my interest. I would like to realize a program that simulates basic components of circuit technology and their functions. I have developed a small approach on how to implement the elements of circuit technology on an object-oriented level. Is ...
stackexchange/codereview
Dumbserver, or the simplest workable HTTP server. It is supposed to operate in the 'traditional' way, that is, mapping paths in requests to the directory structure. Why did I write it: I needed a simple development server for a website I'm trying to make. Instead of using Express or something like that for this purpose...
stackexchange/codereview
I am wondering if it's possible to avoid looping. I want to make the function faster. The function is to find how many times a particular value is lower in the overall data. For example: Value <- c(0,10,5,1,0,0,11,0,0,7,3,2,5) # length =13 The 1st value is 0 and 0 is NOT lower in any of the values. Therefore the value...
stackexchange/codereview
The purpose of this code is to check for errors in my code for a custom shell. In a previous answer, they say that my code didn't have error-checking. You need to check the result of every function that might fail POSIX arithmetic expansion So I've been asking about how to do it. https://stackoverflow.com/question...
stackexchange/codereview
Recently I was experimenting with QTableViews and I wanted to create something where I can add a new row to a table without having any additional button/menu item outside the table. I achieved this by adding a single item to the view's model and set that not editable. Then if a double-click happens on the table I check...
stackexchange/codereview
I implemented a basic Socks4 client and server which can handle CONNECT requests only right now also without identfication protocol support. I've tested it with a simple ncat echo server which works but I would like to have a review of my: project structure filenaming/code splitting naming/design of structures error h...
stackexchange/codereview
Scenario: I wanted a task scheduler/doer that enables my application to schedule some tasks to be executed in a specified time but in the same order they were scheduled in or depending on their priorities (DataFlow like). I also wanted it to enable the usage of C# 5 Async/Await functionality so I looked up over the In...
stackexchange/codereview
I have been working on this: Design a class for a bank database. The database should support the following operations: ❍ deposit a certain amount into an account ❍ withdraw a certain amount from an account ❍ get the balance (i.e., the current amount) in an account ❍ transfer an amount from one account to another Th...
stackexchange/codereview
I develop an application which installs updates. These updates have a version id (this version id is created as a part of the application and the format is a fixed requirement) and I use a regex to parse/validate their id. Each group must be separated by a dot. The id must have 2 digits in the first group, one or two d...
stackexchange/codereview
In order to learn C++11, I propose to myself implement a simple single linked list using smart pointers. The idea was to cover the basic operations without leave any memory leak. I came up with a solution but I'm sure that it could be improved in many ways. So, I would like to receive feedback of any kind: format, read...
stackexchange/codereview
I have solved the Problem 25 of the Euler Project: The Fibonacci sequence is defined by the recurrence relation: \$\qquad F_n = F_{n−1} + F_{n−2}\$, where \$F_1 = 1\$ and \$F_2 = 1\$. Hence the first 12 terms will be: \$\qquad F_1 = 1\$ \$\qquad F_2 = 1\$ \$\qquad F_3 = 2\$ \$\qquad F_4 = 3\$ \$\qquad F_5 = 5\$ \$\qqu...
stackexchange/codereview
I was writing a function (named listenString) in haskell to see if a string contains one of the strings in a list of strings, and to then return a value (of the type m ()) that corresponded with the string it found. The type of that function is (Eq a, Monad m) => [a] -> [([a], m ())] -> m (). The reason why I used a li...
stackexchange/codereview
I'm trying to create a program that creates a record of how many times letters appear in a given string (ignoring blank spaces) using recursion. s = "Hello there this is the string" new_s = "" for i in s: if i != " ": new_s += i new_s = new_s.lower() com_dict = {} def merge_count(s): global com_dict ...
stackexchange/codereview
I have finally finished creating my first real project. It's just a simple music player that can provides the user with the latest music from any site (as long as it contains MP3 files) he provides in the settings file. It can play it, download it and has an simple settings file from which the user can: add/change si...
stackexchange/codereview
Here is the Euler problem referenced, it says: The n\$^{th}\$ term of the sequence of triangle numbers is given by, t\$_n\$ = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and addin...
stackexchange/codereview
I have just finished learning basic-intermediate Python subjects and wanted to test myself. This Battleship game is the third game i have written. import random def create_random_ship(): return random.randint(0, 5), random.randint(0, 5) def play_again(): try_again = input("Wanna play again? <Y>es or <N>o? >...
stackexchange/codereview
I have a test that I've already turned in but would like some outside review on where I could improve. Spent most of the day today trying my best to keep this O(n) complexity. Any help is very much appreciated. If it's a bit difficult to read here feel free to check out the repository Example of how it should be format...
stackexchange/codereview
This is the first code I've written. It's for an intro to Java course. Could you look over it and let me know of things I could improve before handing it in? For reference, I've also provided what I'm being graded on at the bottom. import java.util.Scanner; public class LB01Smith { public static void main(String[...
stackexchange/codereview
My program brute-forces a password. The password is a string composed of a key and a four digit numeric code. The key is known so we are basically brute-forcing between 0000 through to 9999 An example password is: UoMYTrfrBFHyQXmg6gzctqAwOmw1IohZ 4143 I updated that script I wrote to take advantage of multiprocessing i...
stackexchange/codereview
I'm trying to take advantage of NumPy broadcasting and backend array computations to significantly speed up this function. Unfortunately, it doesn't scale so well so I'm hoping to greatly improve the performance of this. Right now the code isn't properly utilizing broadcasting for the computations. Is there a way wh...
stackexchange/codereview
I want to compare the values in two arrays. The order of the values doesn't matter. Basically they are two Sets. This function returns true if the values are the same in both arrays, or false otherwise. function compareSets(a1, a2) { if (a1.length !== a2.length) { return false; } var len = a1.lengt...
stackexchange/codereview
I created a function that finds internal and external IP addresses, returns them in dict with the keys external_ips and local_ips: def get_address_types(address_list): """ determine whether an IP address is local or external from a given list of ip addresses returns a dict containing external and inter...
stackexchange/codereview
This is a very basic script. If the screen width is larger than say a tablet, and a portfolio link is hovered over, it will fade out the original text and replace it with the text held in the 'data-portfolio' attribute. I'm fairly new to jQuery so any improvements will be welcomed. You can see it working here. (functio...
stackexchange/codereview
I have a file with mostly 0 and 1. For each line I would like to compare it against all others (without the redundancy) and count the different combinations. It is slightly more complicated as there are also "N" in the matrix when there is missing data. For example if the two lines are: line1 = "0 0 1 0 1" line2 = "0 1...
stackexchange/codereview
I've got an element with multiple classes in a page and I need to dynamically get the number at the end of a specific class name. Example: <div id="gallery-1" class="gallery galleryid-555 gallery-columns-3 gallery-size-thumbnail"> ... </div> In particular I've to get "3" from gallery-columns-3. I've made this func...
stackexchange/codereview
I am trying to solve Project Euler Problem 224: Let us call an integer sided triangle with sides a ≤ b ≤ c barely obtuse if the sides satisfy a2 + b2 = c2 - 1. How many barely obtuse triangles are there with perimeter ≤ 75,000,000? For large v_max and v_max_n, the generator below yields very slow when I have 75000000...
stackexchange/codereview
I'm writing an MD-like simulation and I'm having some difficulties in making this code run faster. I profiled the code using callgrind and kcachegrind, and it appears I'm using about 30% of my time on calculating distances, 43% on setting up the linked-cell list and calculating my forces, 20% on malloc and free (I assu...
stackexchange/codereview
I have recently started looking into networking with Python. I saw some tutorials about the socket library so I decided to give a "live chat room" idea a go. It works (on Windows, os.system("cls") may be problematic) but was just wanting to see how people could improve upon it server.py from socketserver import Threadi...
stackexchange/codereview
Seeking to improve upon my high score 'module' code. It saves users' high score in a pickle database and if needed prints out the current scores in the database. import pickle import os global high_scores def setup_scores(): global high_scores high_scores = {} if os.path.isfile('highscores.pkl'): ...
stackexchange/codereview
I have client's methods that processes a large SQL query. I wouldn't like to do that through getting whole query result to memory, but process it in batches. It entails with exposing JDBC API to client's code. I think that this code could be refactored much better. //client's method m_jdbcManager = JdbcManager...
stackexchange/codereview
The question states: Given an integer A, and two indices Li, Ri. Find if the number from A which is bounded by the two indices is divisible by 7? For example if A = 357753 indices Li = 3, Ri = 4, then the number is 77, which is divisible. My program give a time limit exceeded when executed for larger numbers. Are ...
stackexchange/codereview
While working with dictionaries I've been always running into the same two problems (who wasn't?): The indexer throws the KeyNotFoundExcepion if you try to retrieve an item with a non-existing key that does not tell you which key is missing. The Add method throws the ArgumentExcetpion if you try to add an item with t...
stackexchange/codereview
Edit: This code was reworked and repostetd under a new question: Generic Skip list implementation in C++ Version 3 This is a follow up of: Non generic Skip List implementation in C++ If you don't know what a Skiplist is: https://en.wikipedia.org/wiki/Skip_list I continued the work on the Skiplist. I tried to incorporat...
stackexchange/codereview
I'm making an application that has a UIViewController with a UITableView in order to show the favorite users that the user of the app have added. They are being stored in UserDefaults, for which I have created a UserDefaultsManager struct to handle its logic. I had the following ViewController: import UIKit class Favo...
stackexchange/codereview
I understand that using eval is extremely dangerous as it can execute deadly commands as an input by the user. I'm trying to write a code to get a letter grade from a number between 0 to 1. I was trying to write it in the most elegant way. Is this safe? try: score = float(raw_input('Enter score: ')) except Except...
stackexchange/codereview
I have the following data frame: set.seed(1) SOURCE <- as.data.frame(matrix(c((1:10), sample(c("20-24","25-28"), 10, replace = TRUE), sample(c("10000", "20000"), 10, replace = TRUE), sample(c(1, NA), 10, replace = TRUE), ...
stackexchange/codereview
Merged cells are a PITA in Excel. They prevent doing a lot of actions and make copying columns impossible. So I wrote this little code to change all the merged cells in a given sheet into 'Center across selection'. I did NOT test against vertically merged cells, but it should not trigger an error (just unmerge them). S...
stackexchange/codereview
Currently, I have a code which downloads a file from FTP to local hard disk. It then uploads a file in chunks to Azure. Finally, it deletes the file from local and ftp. This code is very slow though. Just wanted to know how to improve it. private async Task UploadToBlobJobAsync(FtpConfiguration ftpConfiguration, Bl...
stackexchange/codereview