instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
I've been working on a text-based RPG for a while now on-and-off. After a long hiatus, I've come back to the project. My goal as of right now is to port the game from it's current Print-output version to a version that works in a Pygame window before I add anything else. Now it's worth mentioning that I'm a complete n...
stackexchange/codereview
Python beginner here. Created this program as a project to help learn python. Just ran this in a centos7vm so far to test. What it does is - zip up files containing certain extensions (excluding those defined in the var ext_list), logs the zip up process as it continues through, and when finished, send an email confirm...
stackexchange/codereview
I am looking for suggestion to make my for loop iterate faster. With about 2000 rows of data. Below code is taking lot of time to run. So far I have followed various Stack Overflow answers. For example reducing db queries and using Bulk insert to improve EF performance. It just improved marginally. List<VehicleApplicat...
stackexchange/codereview
I've attempted to remedy the issues outlined in the answer to my previous question. I've added several hundred blank lines to better illustrate the grouping of functions and generally make things look less dense. I've trimmed all the lines to 80 columns except for one 83 character line in ppnarg.h which was inside the ...
stackexchange/codereview
I am building an web application that is going to work in a similar way like photoshop or illustrator regarding layers. Here are my code that is searching the ".case" div for images, and then put these images id's to an array. When that is done we are looping the array to find out if the received image is the same as t...
stackexchange/codereview
I have a working Java implementation of Bloom Filter. These are the methods to addElement and check for an element. private void addElement(byte[] element) { if (null == element) { throw new NullPointerException(); } long hash1 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, ele...
stackexchange/codereview
I have below working code which works fine, but just looking way around if there is an another elegant way of doing this, because here i'm using else condition to print the last line or dataBlock to be printed. Note: mydudalt1 and mydudalt2 are the host names My data File: $ cat mydata_test.txt -- mydudalt1 -- ...
stackexchange/codereview
I've got some time-series data. I want to examine the weekly and daily variation of that data. For weekly data I can make a plot like this, with the days along the horizontal axis: For daily data I can make a plot like this, with the hours of the day along the horizontal axis and the different colors corresponding to ...
stackexchange/codereview
I would like to select some information I have stored in my MySQL DB. I have 2 tables named gameTable and playerTable. Now I want to get the gameTable and get the names and levels of these players. This is what I got so far, it works but I'm not sure this is the most efficient way. Do I really need to create a join f...
stackexchange/codereview
public static DataSet execute_query(string query) { DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(); con.ConnectionString = DataAccessLayer.Properties.Settings.Default.cn; try { con.Open(); SqlDataAdapter da = new SqlDataAdapter(query, con); da.Fill(ds); ...
stackexchange/codereview
I am having performance problems with the following python function: def remove_comments(buffer): new_buffer = '' lines = buffer.split('\n') for line in lines: line_wo_comments = line.split('--')[0] + '\n' new_buffer = new_buffer + line_wo_comments return new_buffer When buffer is very ...
stackexchange/codereview
I am a total beginner at Python, so I wrote a very simple snake game using pygame to get some practice with it. I also don't have too much experience with object-oriented design. Does the code layout look okay? Is it easy to read and understand? I'm sure it can be simplified some. The update_segments section in pa...
stackexchange/codereview
I am calling show_thumb to create thumbnails , but I am realizing that it is making the site load a little bit slower. Below are two functions: show_thumb function that shows the thumbnail and make_thumb_gd that takes care of the thumbnail. Any suggestion on making it faster? The current approach makes the site slow, b...
stackexchange/codereview
A while ago, I was working on a chess project with a couple other people. In the end, I wrote all but a couple of the lines of code, including these: class Piece(list): def IsValidMovePattern(self, FromCoord, ToCoord): print(self, "Validation not done") return False class King(Piece): def I...
stackexchange/codereview
I have written following code for the this C++ Problem: Write a program to add only odd numbers between one to ten. #include <iostream> using namespace std; int main() { int num = 1, n = 0; int odd_num; while(num <= 10) { if(num % 2 != 0) { odd_num = num; odd_num +=...
stackexchange/codereview
(Homework alert) Working my way through "The Haskell Road...", not sure about my solution to exercise 2.15 on page 48 of the second edition: A propositional contradiction is a formula that yields false for every combination of truth values for its propositional letters. Write Haskell definitions of contradiction tests...
stackexchange/codereview
Intro Yesterday I posted this question. Since then, I've updated my code to incorporate these suggestions. I've also removed the dependence on C++11. Finally, I've made the following changes that get me closer to my overall goal: Rather than iterate over different values for dt within my script, I have dt specified...
stackexchange/codereview
So basically I am building an app that helps to download some documents via a rest api. Here is the SearchViewController import UIKit class SearchViewController: UIViewController, UISearchResultsUpdating, UISearchBarDelegate { let searchController = UISearchController(searchResultsController: nil) @IBOutlet ...
stackexchange/codereview
I have rewritten my tokenizer according to most of the suggestions from the previous question here. API It now reads all chars as long as they match the pattern. I use three types of attributes to achieve this. Regex - reads by regular expressions; this one requires a single group that is the value of the token; it ...
stackexchange/codereview
My previous iteration was here. I've since finalized the concept as described in the title, and would appreciate any feedback GitHub Link Introduction: value_ptr is a C++11 header only, deep-copying smart pointer that preserves value semantics for both polymorphic and undefined types. value_ptr aims to address the fo...
stackexchange/codereview
I have been going through some CodingBat exercises and I came across this problem. "Given a string, return the length of the largest "block" in the string. A block is a run of adjacent chars that are the same." Required output: maxBlock("hoopla") → 2 maxBlock("abbCCCddBBBxx") → 3 maxBlock("") → 0 My code seems to pa...
stackexchange/codereview
I have created this repo on GitHub and I have shown how this software works through a video. If you have time, please visit the repo and read the files. I'll post some relevant snippets below, but if you can quickly skim over the whole thing, that would be great. I'm new to Python so I'm sure there are some things in t...
stackexchange/codereview
I've been trying for a while to write clean and testable code, with the help of DI and abstractions. I found myself guilty of service-itis, creating 3 or 4 interfaces for something that clearly doesn't need it. So I decided to relax, and only abstract what really needs it. I'm faced with a problem where I'm not sure wh...
stackexchange/codereview
I have written this code to write string to file. If File is not created then create file and If created append to same file. File is created daywise. public static void WriteLog(string sMessage) { try { //string logfolderpath = System.Configuration.Config...
stackexchange/codereview
This is the code of my function to endless scrolling. It's a good practice to bind new disposable in onscroll listener? What do you think about my code? private fun searchData(srsearch: String) { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(et_se...
stackexchange/codereview
My game engine uses the following broadphase collision detection algorithm: internal void SweepAndPrune() { // First: order all objects from left to right on the x-axis: IOrderedEnumerable<GameObject> axisList = _gameObjects.OrderBy(x => x.LeftRightMost.X); // loop through all objects: for(int i = 0; i...
stackexchange/codereview
I have a registration form. Step 1 user creates an account. As user creates an account I need to authenticate user with the created account. in my account.service.ts I have following. Is this the best way to handle this? and how can improve this to handle errors from 2 different http calls? public createAccount(reg...
stackexchange/codereview
[edit] I realised why everyone does this with loops; my plan was to use .SpecialCells(xlCellTypeVisible).EntireRow.Address to return the row(s) of the results of the results of the filter, but that returns a string. Strings have a limit of 256 characters, so with even moderately fragmented data some will be truncated. ...
stackexchange/codereview
I am trying to solve a programming challange that involves converting reverse polish notation to infix notation. For example: 1 3 + 2 4 5 - + / would be: ((1+3)/(2+(4-5))) My solution so far does work, but it's not fast enough. So I am looking for any optimization advice. public class betteralgo { public static voi...
stackexchange/codereview
I've just started learning Erlang. Since my editor of choice doesn't have a syntax checker for Erlang, I decided to use the parser/linter in the standard library to make a standalone script. It works now, but I'd like my code to look cleaner, possibly handle edge cases better, be more ... what's the Erlang equivalent o...
stackexchange/codereview
Given You’re given the pointer to the head node of a linked list, an integer to add to the list and the position at which the integer must be inserted. Create a new node with the given integer, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates ...
stackexchange/codereview
I have this method that attaches the year and year's rowspan for a TD and Quarter and a Quarter's rowspan for the TD. Year and Quarter are 2 columns in an Angular Material Table which are calculated from an array of objects one of which property of the object is a date string. Here is a demo for the code: https://stack...
stackexchange/codereview
I'm building a contact manager with Flask for a community group, and I'm working on the function to export contacts as a spreadsheet. I want to export either all contacts, only those who have been assigned to a ticket seller, only those assigned to a specific ticket seller, or those assigned to no ticket seller. The fo...
stackexchange/codereview
I want to play some audio of two byte arrays. I was wondering whether it would be better to play them as two separate arrays both calling the method, or to put them into one array and play it from there. Note: The starting from position 4 because the first 4 bytes are saved for the sequence number in the array. All in ...
stackexchange/codereview
Given a string, find the first non-repeated character in it. E.g. "yellow" should return "y" There are several solutions for this in other languages but I haven't seen one written in Perl. My main question is: can this be done in a more Perl-ish way or generally in an even shorter way? use strict; use warnings "all"; ...
stackexchange/codereview
I am writing a function to decode a string, which means performing a string transformation like 3e4f2e --> eeeffffee. I have two versions of codes which are very similar but slightly different. In version1, def decoding(s): res = [] curr = 0 curr_val = 0 while curr < len(s): if not s[curr].isdig...
stackexchange/codereview
I'm just starting to use C++ so beginner feedback is fine here. CPP code (main.cpp, node.h, node.cpp, trie.h, trie.cpp, utils.h) main.cpp #define BOOST_PYTHON_STATIC_LIB #include <string> #include "boost/python.hpp" #include "boost/python/module.hpp" #include "trie.h" BOOST_PYTHON_MODULE(ptrie) { using namespace...
stackexchange/codereview
I am working with JSON API data in .NET6 and was having trouble de-serializing nested data that has a variable rootname since my class type will never match what's in the JSON string. { "???":{ "type":"static", "description":"n/a", "id":null, "upc":"s324df", "price":1802 } } in the ...
stackexchange/codereview
I'm a programming newbie. In fact, this is my second code ever (after Hello World). I did a lot of reading actually, here on Stack Overflow, and other websites. I would like to know if there's a way to further improve this code. #include <iostream> #include <string> using std::cout; using std::cin; int main() { cout <...
stackexchange/codereview
I just coded an object-oriented Sudoku solver, but I don't have any possibility to check whether I have written good code, so I thought I would just post it here for review. I have looked for other solutions online but they mostly use different approaches so it's hard for me to compare. I'm just getting started and try...
stackexchange/codereview
I'm hoping for suggestions of a concise way to write my list comprehension filter in the first solution. I would also appreciate insight on the underlying reasons for some performance differences in my solutions for Problem 5 (https://projecteuler.net/problem=5): 2520 is the smallest number that can be divided by each...
stackexchange/codereview
I've made a Python Steganographer using the Python Imaging Library. It basically encodes the binary text in the last 'n' bits of the red content in each pixel of the image. Here is my code, please suggest some improvements. from PIL import Image import os def str2bin(message): binary = bin(int.from_bytes(message....
stackexchange/codereview
let reply = ref "" let doAuto = async { let! resultAA = async { return SqlCmd.aaHits query |> Async.RunSynchronously |> List.ofSeq } let! resultBB = async { return SqlCmd.bbHits query |> Async.RunSynchronously |> List.ofSeq } let! resultCC = async { r...
stackexchange/codereview
I would like to get the current user's timezone name so it can be used with the PHP date_default_timezone_set(). After looking up a few things I've finally managed to come up with a solution for this. I'm not great with code though so any code checks/help will be appreciated. As long as it is a fair guess of the user's...
stackexchange/codereview
I've got some experience with Laravel but for fun I started a small project (basically a CRUD with also Google Maps) without a framework because I considered that is oversized. This is the directory structure. +---assets | +---css | +---img | \---js +---classes +---inc | +---templates | \---views | \---...
stackexchange/codereview
This function is for Python Pandas users. I noticed a lot of RAM can be saved by applying smaller datatypes to columns. The function's input is a Pandas DataFrame. The function output is the compact dataframe and a list of columns that have been altered by filling out NA values with dummy values. This function iterate...
stackexchange/codereview
We have two C-strings and for their concatenation we need to know the size of resulting string. And we want to calculate it at compilation stage. How can I improve this solution? char s1[] = "string1"; char s2[] = "string2"; constexpr auto SIZE = sizeof(s1) / sizeof(*s1) + sizeof(s2) / sizeof(*s2) + 2; // + for space...
stackexchange/codereview
I have no IT background and taught myself Java and made a simple Tetris game. I compared my code on the internet with other tutorials. My first impression of those implementations is that they are very complex: Shape-classes, No-Shape-shape, rotation arrays etc. The location of a shape in the grid is also the shape's c...
stackexchange/codereview
I made an Agario single player version (soon to become a multi player one using socket). What can be some improvements? Controller: package agario; import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapt...
stackexchange/codereview
How can I improve this program? #include <stdio.h> #define MIN 80 int main(void) { char line[MIN]; int i, c; for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i) { if (i < MIN - 1) line[i] = c; else { if (i == MIN - 1) printf("%s", line)...
stackexchange/codereview
I was watching the following video about software transactional memory(using a package that maintains an access log). At the moment I am trying to learn about concurrency with shared memory and thought that could be more easily achieved with immutability and checking referential equality. Never spent much time actually...
stackexchange/codereview
I have a React/Flux web app and want to follow the architecture best practices: I will focus on one view for my question, the component used to insert/update an entity (a User in occurrence). Everything is working with this code, but the core of my question is about the onUserDetailChanged function in my AdminUserDeta...
stackexchange/codereview
I like to user colored output in my interactive shell scripts. I've been using Ubuntu and bash for a long time, but haven't done much bash scripting. I'd appreciate a review of this function for generating colored output. #!/usr/bin/env bash # # Function to generate colored output. # # The output is specified using a f...
stackexchange/codereview
Problem Method getQuoteHTML generates an HTML string using an array returned from getQuoteParams method. They are methods of a large class, UpdateStocks. Would you be so kind and help me to replace them with faster, easier or more efficient methods, if possible? getQuoteHTML: /** * * @return a large HTML...
stackexchange/codereview
Going through the Rust book for the second time as I've been wrapped up in Typescript for a while and I want to build a personal project in Rust. In chapter 8.3, there's an exercise: Given a list of integers, use a vector and return the median (when sorted, the value in the middle position) and mode (the value that oc...
stackexchange/codereview
I have a simple two-class hierarchy to represent U.S. ZIP (12345) and ZIP+4 (12345-1234) codes. To allow clients to allow both types for a field/parameter or restrict it to one type or the other, the specific types inherit from a common generic ZipCode interface. Update: A ZIP code is five digits. A ZIP+4 code consists...
stackexchange/codereview
I did the following code challenge for a job interview. They apparently didn't care for my solution and I'm not sure why. What could I have done better? Here is the challenge: Create a small app with the following characteristics: With the device in the portrait mode, display a fragment with a single EditText instr...
stackexchange/codereview
this was my first thing i made on my own without any help. im sure theres a lot of improvement that could be made, i dont feel too confident about this. how can i make it shorter and more efficient? should this entire thing be rewritten in some other way? refactored? keep in mind if i wanted to add more birds to the li...
stackexchange/codereview
I'm learning Haskell, and one exercise was to implement squashing of identity-multiplications, e.g.: \$5 + (2*1) => 5 + 2\$ Here is my implementation: squashMulId :: (Ring a, Eq a) => RingExpr a -> RingExpr a squashMulId (Mul x y) | x == (Lit (mulId)) = squashMulId y | y == (Lit (mulId)) = squashMulId x ...
stackexchange/codereview
Project Euler #1: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. Here is my solution: public class MultipleFinder { private static final int MAX_NUMBER = 1000; privat...
stackexchange/codereview
This is the code I came up with. I added comments to make the solution more verbose. int findComplement(int num) { // b is the answer which will be returned int b = 0; // One bit will be taken at a time from num, will be inverted and stored in n for adding to result int n = 0; // k will be used to...
stackexchange/codereview
Goal of Program Consider a template file template.txt with double brace variables, intended to be replaced by values: hello there {{ MY_VAR1 }} some other stuff some other stuff foo: {{ MY_VAR2 }} {{ MY_VAR2 }} is the value of MY_VAR2 and assume you have defined and exported those variables: export MY_VAR1=val1 export...
stackexchange/codereview
I need to add some characters to a String before using it for an API call. The idea is to add a " char both at the beginning and at the end of the String, to make sure the API does an exact search for the input string. Version 1: StringBuilder(escapeJava(query)) .insert(0, DOUBLE_QUOTE_CHAR) ...
stackexchange/codereview
I am sampling from m normal distributions n times each, and storing the samples in a 2-dimensional ndarray. I then need to turn this into a polars dataframe as I need to add some string columns and do a lot of querying/aggregating. I think where I convert the array to a dataframe is inefficient. The Polars docs did not...
stackexchange/codereview
I have implemented a dynamic programming solution of the egg-dropping problem (this problem, but generalized for any number of eggs and floors): #include <iostream> #include <limits.h> //Optimal sub-structure //We have K floor and N eggs //Case1: If egg break of X floor then we have x - 1 floor and N - 1 egg //Case2: ...
stackexchange/codereview
I'm in the unfortunate position to where I have to create files and folders programmatically that have to work with a legacy system. In this process, the file and folder names have to be heavily sanitized. The POST requests that create the files and folders are sent from the client in javascript, while the actual creat...
stackexchange/codereview
I just handed in my first assessed coursework for my Computer Science degree. Part of it was to take in a date (dd mm yyyy) between 1900 and 2100 and output the ordinal date. My function to do that is below. I’m new to C - I’ve used Python, JavaScript and more recently Pascal, so I might be approaching this from the wr...
stackexchange/codereview
The idea behind this is mainly educational but I might even consider using it in reality if turns out to be good. Here's my first try at implementing smart pointers: template<typename T> class smart_pointer{ T* pointer; std::size_t *refs; void clear(){ if (!--*refs){ delete pointer; ...
stackexchange/codereview
I'm writing a program in wxpython, and to make GUI parts that are built in different modules I made a module called runtime, where all the GUI parts get stored on runtime. This is how it looks: mainFrame = anotherGUIPart = InputDialog = SomethingElse = None For example, when I need to make a ListControl to update it...
stackexchange/codereview
I saw a programming puzzle. Find a string containing letters from a to z such that its MD5-hash starts like 314159265359. I am a junior programmer so I would like to know if I can solve the problem faster that checking firs strings a-z, then aa-zz, then aaa-zzz and so on. As the computation takes time, I save results t...
stackexchange/codereview
I have text inside a variable that I need to separate in paragraphs, and at the same time respect the manual breaklines. This is my code: {description.split('\n\n').map(paragraph => ( <p> {paragraph.split('\n').map( (line, index) => index > 0 ? ( ...
stackexchange/codereview
Last time I asked for a review of my tokenizer, and I would like to thank for all of the feedback! This time I wrote a parser for my language. The parser generates an AST (abstract syntax tree), from which (later) I will generate code in an intermediate language. Each node will have a Generate() method outputting the c...
stackexchange/codereview
I was asked to complete the task described below: Event Emitters are objects that serve as the core building block in event-driven architectures. They simplify the process of handling asynchronous events and enable clean and decoupled code. Create an Event Emitter module in JavaScript (as modern of a version as you ...
stackexchange/codereview
I've implemented a small program in JavaScript to count the number of lines of a string of java source code. This was done for one of the Code Kata exercise: http://codekata.com/kata/kata13-counting-code-lines/ Overall, the goal of this exercise is summarised as follow: The mixture of line-based things (single line co...
stackexchange/codereview
Here is my implementation of an all-or-wait-until-all kind of process. Each thread (kid) needs to guarantee it is the only thread processing the required resources (toys) at that moment. If some resources are not available (being marked by another thread), then it should wait for them and check again next time. Thread ...
stackexchange/codereview
Description Very small subset of Forth This is a proof of concept level compiler, no optimizations or over/underflow checking See the embedded POD for more information NASM is used as assembler gcc is used to link with glibc 32bit ELF Binary is generated bhathiforth.pl #!/usr/bin/perl use strict; use warnings; use f...
stackexchange/codereview
So I have implemented an application that acts as a chatbot for telegram in C#. I use a library that allows to set a filter of updates that the application whishes to receive. I assume the filter makes it more performant. This filter is passed in the StartReceiving method. My bot consists of multiple modules and each o...
stackexchange/codereview
The idea is to implement the observer pattern, with a separate notification method for each observed property of the observed object. Let me start with a simplified use case: class Point { val observers: ObserverSet<PointObserver>() val x by observers.observe(0f, PointObserver::xChanged) val y by observers....
stackexchange/codereview
I'm currently having this code & looking for a simpler and shorter way of showing, hiding & disabling my elements... $("#chReportData").click(function(){ if($(this)[0].checked){ $("#reportDataOptions").show(); } else { $("#ReportDataStatusOptions").hide(); ...
stackexchange/codereview
Does someone want to review my solution to part 1 of Day 7 Advent of Code in Scala? The assignment is here: http://adventofcode.com/day/7 Without repeating the whole text, in short: Given a text file of the following form (simplified): x AND y -> a x -> 1 y -> 0 calculate the value of a. Here is an example of a full i...
stackexchange/codereview
I am implementing a lexer for an experimental language by the name "Phoenix", the language supports four primary arithmetic expression for integers only (add, subtract, multiply, divide), variable assignment and print statement. Typical input: # this is a comment value = 1 + 7 / 4 * (30) print('Value = ', value) lexer...
stackexchange/codereview
I wanted to practice functional programming (fp) without using any library. So I took the 1st problem from project euler: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. My solutio...
stackexchange/codereview
The macro below loops through column E in Sheet2 and finds matches in column Z of Sheet1. If a match is found it copies the value on the same row contained in column AA. It works ok but hangs when it runs. There are usually a few thousand values in column E but less than 30 in column Z. I've run it on a few PCs with de...
stackexchange/codereview
What can be simplified, altered, or implemented differently? I would like to know if there's a way to further improve this code. #ifndef _DEQUE_H_ #define _DEQUE_H_ //------------------------------------------------------------------------- template <typename Type> class Deque { private: struct Node { T...
stackexchange/codereview
I'm flattening a JSON structure where objects have their interaction type appended at the end, for use in an HTML/PDF generated file. I have variable names for Checkboxes, Text inputs, TextCheck is a combined checkbox/input that needs to be broken apart for my logic. Lastly, I have a Radio Index and Radio Label ojbect ...
stackexchange/codereview
The purpose of this code is to find a password with brute force cracking where as it will try all the possible combinations until it finds the correct password. For example, it will start like a then b then c . . . ab . . . cz . . . dd and so on until it finds the correct password. All of it works, but the performance ...
stackexchange/codereview
#include <cs50.h> #include <math.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> int k = 0; int convUpperAsciiToAlphaIndex = 65; int convLowerAsciiToAlphaIndex = 97; int AlphaIndexWrap = 26; int main(int argc, string argv[]) // get Key from user via Command-Line Argument...
stackexchange/codereview
A class Array which contains two data members: a pointer on array of complex numbers and the length of the array. Implement a function for reading the array. The class should have a constructor, destructor and copy constructor. In the main program, enter the array of complex numbers. main.cpp #include <iostream> #inc...
stackexchange/codereview
I have implemented my own Observer pattern. I want to post my events in a new thread. This thread would simply call all the the observers/listeners with the posted event. public class EventManager { private ArrayList<Observer> observerList = new ArrayList<>(); public void post(Object event) { new Th...
stackexchange/codereview
Basically, what I mean by illumination is having a method create an object where the caller supplies all the dependencies. This allows us to hide our new keyword behind a dependency on an Illuminator, allowing us to much more easily test our code. Yes, a little bit of reflection is involved, but not too much (IMO). Pl...
stackexchange/codereview
I have stored in a XML file some Travel packages, each package has a code( the codes are stored in an array = $code). I am using the below code to pull the requested data from the XML based on the given code. At this time I have copy/paste the code for each given code, but I have lots more and I dont want to copy paste...
stackexchange/codereview
I have been reading some NumPy guides but can't seem to figure it out. My TA told me I should be able to speed up my code by using a NumPy array instead of a for loop in the following segment of code. for neighbor in get_neighbors(estimates,i,j): pXgivenX_ *= edge_model(True,neighbor)*observation_model(obs,...
stackexchange/codereview
I wrote a program that calculates the minimum number of coins required to give a user change. One concern I have is: When do we initialize the value of a float to be negative or positive? I recently saw float userInput = -1.0; but what about float userInput = 1.0; Are there differences between the two, and when...
stackexchange/codereview
How can I make this better? public int BubbleSortNonEfficient(int[] arr) { int temp = 0; int LoopCount = 0; for(int write = 0; write < arr.Length; write++) { for(int sort = 0; sort < arr.Length - 1; sort++) { LoopCount++; if(arr...
stackexchange/codereview
My problem I am working with two objects, structured as follows: test <- structure(list(rs1_A = c(0.1, 3), rs2_B = c(0.2, 2), rs22_C = c(2, 1)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L)) > test # A tibble: 2 × 3 rs1_A rs2_B rs22_C <dbl> <dbl> <dbl> 1 0.1 0.2 2 2 3 2 1...
stackexchange/codereview
I've been in an interview some time ago. They objected my Symfony API code with following line: Too much code in controller actions. Can be moved to services to keep the business logic apart from the representation. Also violating single responsibility. I have been trying to improve my code since then. Trying to...
stackexchange/codereview
I created a plot on which the y value is visible with the marker. What's your opinion ? I wonder if I could have done something simpler. (code should run in a Jupyter notebook) %matplotlib inline fig = plt.figure() axes = fig.add_axes((1,1,1,1)) X = np.array([3,3.2,3.5,3.8,3.9,5,5.5,5.8,5.9,5]) y = np.array([1,1,1...
stackexchange/codereview
I have a controller that has gotten a little out of hand. This is my first AngularJS project and I am using it as a learning experience... but I feel like I am doing some things wrong. This controller is used for resetting data on a weekly basis. There are "foos" of which 10 random foos are selected each week, "bars" w...
stackexchange/codereview
I am trying to find the number of capture groups for a regular expression using this PHP function. /** * Finds the number of groups in a regular expression * @param $regexPatten string The regular expression * @return int Returns the number of groups inside the regular expression */ public static function numOfGrou...
stackexchange/codereview
I'm doing a clock in javascript and I am not sure this way is the best way to rotate the pointers. Is this ok, or is there a better way? // browser vendors var browsers = [ 'webkit', 'Moz', 'ms', 'O', '']; // function to move the pointers function moveMe(el, unit) { var deg = unit * 360 / 60...
stackexchange/codereview