instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
How would I simplify the following function to reduce repetitive code? I would like to define "arg" as an array since that is the only changing aspect of each case. function jumpMovement(iMovement) { switch (iMovement) { case 0: document.getElementById('opus-08a').contentWindow.po...
stackexchange/codereview
I've been studying computer science for around two school terms now. Currently, I'm making a Caesar Cipher program as a base for my examination, this is so that I can use the 15 hours to either add, or improve my code. Please, give me some feedback on how to improve my code or, at least, make it clearer. class Function...
stackexchange/codereview
In order to improve the performance of this code fragment, I have speeded up some code fragments by using the numba. However, a frustrating thing is that the performance of this decision tree is bad. For example, in the below code fragment, the performance of the decision tree is nearly 70 times slower than the impleme...
stackexchange/codereview
I've made this script to automate blocking some deviant hosts on my router, and was curious if there's anything much else that can be done to make it quicker and more efficient. Presently I'm restricted to using packages available on the Entware repository and the latest Busybox/ash shell environment. So, for example, ...
stackexchange/codereview
This is good practice, to make square image? Side of the square container is equal to its width. public class SquareImageView extends ImageView{ public SquareImageView(Context context) { super(context); } public SquareImageView(Context context, AttributeSet attrs) { super(context, attrs); ...
stackexchange/codereview
I'm currently doing a project, requiring me to implement a CircularQueue data structure in C++: template<typename Type> class CircularQueue { template<typename Type> struct CQNode { Type head; CQNode* tail; CQNode() { this->head = NULL; this->tail = NULL; } CQNode(Type head, CQNod...
stackexchange/codereview
It works just fine, but is there any other way to write this shorter? Nurses are only available to intensive care patients (room I) and TV's and telephones are only available to non intensive care patients (room D or room P). Also, X_COST has a value of 0. if (room.equals("I")) { // if (room.equals("I")) roomCost ...
stackexchange/codereview
I'm working on some Scala problems given here, specifically: sealed abstract class Tree[+T] case class Node[+T](value: T, left: Tree[T], right: Tree[T]) extends Tree[T] { override def toString = "T(" + value.toString + " " + left.toString + " " + right.toString + ")" } case object End extends Tree[Nothing] { overri...
stackexchange/codereview
I tried to literally convert recursive algorithm taught here to iterative, by simulating the recursive stack exactly as much as possible. I have tested my code and it passed all test cases. Please let me know if any more improvements are possible. Here is my code: public class Graph { private int tv; //total verti...
stackexchange/codereview
How should I go about creating a registration page in Windows forms? I can easily create a registration page, but I'm not sure if it's the best way. I'd have a service account that is hard coded, and it creates entries in a user table. I don't like to hard code passwords, but I don't know of another way. I guess in eve...
stackexchange/codereview
A little while ago I wrote some jQuery code to make a div flip (similar to the Apple Dashboard). I know there is already code that has this idea from Jon Raasch, but this code positioned divs absolutely, which I did not need for my cause. I just wondered if anyone could give me some advice as to how to tidy this up and...
stackexchange/codereview
OK... last sort of the day and probably the most fun. F# is really awesome. let rec quickSort list = match list with | [] -> [] | [x] -> [x] | hd :: _ -> quickSort (List.filter (fun x -> x < hd) list) @ hd :: quickSort (List.filter (fun x -> x > hd) list) [<EntryPoint>] let main args = p...
stackexchange/codereview
TLDR: Rendering is too slow when having lots of custom fields and rules. So I need help to improve this javascript code. #9606: Trac ticket about issue I have a trac 1.0.8 installed on a ubuntu machine with DynamicFields 1.2.6 installed (compiled from latest revisions 0.11 folder). I have more than 100 custom fields ...
stackexchange/codereview
This script opens a basic form which allows one to search all files in a directory for instances of a string, before outputting results to a textbox and CSV (found in the script location). Each line outputted is of the format: Word {string} in {file} on line {line number}: {full line} Steps: Specify Directory Input ...
stackexchange/codereview
private static void OnSundayChangedCallBack(DependencyObject sender, DependencyPropertyChangedEventArgs e) { BinaryDataGrid c = sender as BinaryDataGrid; if (c != null) { if (_shouldCallBack) { if (c.Sunday.Length == 4) return; ...
stackexchange/codereview
I asked this question before. However, I realized that I had to edit some of my code after I got good answers. Therefore, I'm asking a new question here. I have the following database: Each member may have multiple addresses (1:n) stored in table address. It's possible that one member has multiple addresses within on...
stackexchange/codereview
I have a .net core razor app that has a special use case where I need to have a global counter that will be incremented by every request, and yet it should remain thread-safe. Also at web application load, this counter will be read from a database using entity framework. I don't think that static variables are threadsa...
stackexchange/codereview
I'm new to Android programming. I am going to make lots of HTTP requests: 500, 1k, 2k, 10k. I have tried to create a singleton class for OkHttp. I wrote this: public class OkSingleton extends OkHttpClient { private static OkSingleton minstance; private final OkHttpClient myClient; private OkSingleton (){ myClie...
stackexchange/codereview
I was asked to implement a hash map in this phone interview (screen-share), so time was limited and this is what I came up with. I'd appreciate if someone can take a minute to critique/review it and help me improve. Here is an online version of the code. #include <list> #include <iostream> using namespace std; const i...
stackexchange/codereview
Problem: Data: 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 6...
stackexchange/codereview
Assumptions Basically, a Connection class has a "Disconnect" event. Subscribing to this event isn't thread-safe, because the disconnection may fire from another thread right before I subscribe. So checking before the subscription doesn't help. Checking for the disconnect after subscription doesn't help either because t...
stackexchange/codereview
This code invokes a function for every 40 seconds inside a loop. I am doubtful about this condition: if ((time_left <= 0 || time_left > interval)) Is only checking (time_left <= 0) fine? I referred to some websites and they have also added a check for time_left > interval. Is this check required? int print_timed_op(...
stackexchange/codereview
Is the code below safe to create unique ids for objects? I will create new yoga classes and need to have a unique id for each class. I made this small piece of code to generate the id numbers. Regarding specifically the uniqueIdCreatorHandler method, would this solution incur in bad performance, or is it just far from ...
stackexchange/codereview
The aim of the code below is to see if selected fields are empty so data can be saved in that field. Since I'm making a library system, I wanted to record the basic info on one record (all the books they have taken out so the ID's of them as well as author and title) but this proves to be quite tricky and quite long to...
stackexchange/codereview
I'm trying to make a kind of Dungeon Keeper clone. I got the code up and running and even supporting touch events. But I don't think it's as well optimized as it could be, so I am looking for help and best practices on helping improve my map. You can test it out and play with it here or for full screen here. It runs pe...
stackexchange/codereview
I have a table that reads every minute, but the data on one meter only changes once every 60 minutes. It will then repeat that value for 60 minutes before changing again. I need to take the sum of these values and add them up for the day. But if I grab it by the hour, I will get duplicates. So what I decided to do was...
stackexchange/codereview
I am reviewing some C code (see extract below) that uses inline asm. I believe there are 4 spec violations, 1 inefficiency and 1 honking big design flaw in this code. While some of the problems I'm seeing apply to both the x86 and x64 sections in that code, this post is focused on x64. Before I'll be allowed to check...
stackexchange/codereview
I have a pattern where every number is counted by the number of repetitions. A new resulting number is formed by adding that repetition to the front of that value. The resulting pattern would look like this. 1 11 21 1211 111221 so: indexnumbercomment 0      1       one + 1 ->11       1      11       two + 1 -> 21 ...
stackexchange/codereview
I'm trying to compare several files using md5 hash with powershell 2.0. The code works, the problem is that it's to slow. It takes longer in step 3. It's about 500 files to compare. Can you see a way to get it faster, like, don't do the step 3 every time? write-host "1" $COMP_ORI=$LOCAL_HOME+"\"+$PROG+"\"+$COMPARE ...
stackexchange/codereview
Is there a way to do in a nicer way the following thing in Python ? def proving(): a = 4*5 b = 1*9 results = [a,b] return results results = proving() a = results[0] b = results[1] I would like to make a function that makes some calculations and then obtain the values of the variables of interest from ...
stackexchange/codereview
I wrote a script to turn a file like this one into a colored 2D histogram: xbins, ybins, xmin, xmax, ymin, ymax 12, 12, -0.1, 24, -0.1, 25.1 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0...
stackexchange/codereview
This is an implementation of the minion game, which takes in string input and declares a winner between two pre-determined players. The logic is player 1 gets all sequenced words not starting with a vowel and player 2 gets all sequenced words starting with vowel in the input string. Objective: performance optimisation....
stackexchange/codereview
See Problem - 151B - Codeforces for details. I think I have been very messy with using the Streams. Can you review for a good and better implementation with Streams? Any other improvements? public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); List<Person> ps = new ArrayList<>(); for (i...
stackexchange/codereview
I really like to use PDO because it's simple and easy to make a safe query, i prepared all queries and used placeholders, i think it's safe but i'm not sure at all, and I'm thinking if i used trim() the right way. What you guys think? Any doubt please ask me on the comments section. login.php <?php if($_SERVER['REQUES...
stackexchange/codereview
As the question already says, my code returns a list with the index's that don't exist inside another list. For this I currently create two lists joining the objects of each index, then filter the values not found and finally I do a loop searching in which index I will find this value within the initial list: function ...
stackexchange/codereview
This exercise is from jshero.com. Write a function parseFirstInt that takes a string and returns the first integer present in the string. If the string does not contain an integer, you should get NaN. Here is my working solution. I'm posting in hopes of receiving pointers on how I could have written the code more effec...
stackexchange/codereview
I have a private method in my class to update user experience. First of all, I create giveExp based on contentLength (string.length) In that method I had formula for count level from exp: (Math.sqrt(2 * user.xp - 175) + 25) / 10; I also need to inform the player that they have leveled up. Full code private updateXp( ...
stackexchange/codereview
I'm working on a React app with websocket. In this app there is a socket event listener which returns 3 types: add, change, and remove. Certain state update operations will be performed based on the type received. Do I properly mutate the users state? I'm not sure whether it follows the principle of React regarding upd...
stackexchange/codereview
I have this code written and I wanted to get a better performance out of it. Could somebody help me please? If possible I would like my code to get a better performance when rolling high numbers and when it getting to the percentage operation. #implementation of multiple dice rolls at the same time and showing what eac...
stackexchange/codereview
To find the row with max zero Matrix will have either 0 or 1 in sorted manner. public static void main(String[] args) { // TODO Auto-generated method stub int[][] inp=new int[][]{ {0,0,0,1,1}, {0,1,1,1,1}, {0,0,1,1,1}, ...
stackexchange/codereview
Suppose I have a H*W numpy array like this (H=3 and W=2): [[0 1] [2 3] [4 5]] I would like to replace each element with a matrix of M*N repeated element (M=2 and N=3): [[[[0 0 0] [0 0 0]] [[1 1 1] [1 1 1]]] [[[2 2 2] [2 2 2]] [[3 3 3] [3 3 3]]] [[[4 4 4] [4 4 4]] [[5 5 5] [5 5 5]]]] ...
stackexchange/codereview
I have an PHP endpoint used to mail me feedback or error logs from my sites here: https://github.com/kaihendry/vanilla-php-feedback-form/blob/master/feedback/feedback.php <?php switch ($_SERVER['HTTP_ORIGIN']) { case "https://example.com": header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']); ...
stackexchange/codereview
I built this basic in-memory database that can support some basic operations, like SET, GET, DELETE, COUNT, etc. As well as support transactions. Some of the constraints are as follows: GET​,​ SET​,​ DELETE​, and C​OUNT​ should have a runtime of less than O​ (log n),​ if not better (where ​n​ is the number of items in ...
stackexchange/codereview
Suppose we have an application which process packets from somewhere. We should choose right handler for the packet depending on packet type and also we know that it might be necessary to change algorithm of handlers and add new handlers in the future. The question is: how can I write maintainable code? Here is my draft...
stackexchange/codereview
I'm "playing" with ARM assembly on a Raspberry Pi, reading various tutorials and posts to help - no, it's not a college assignment, I'm too old for college! I'm pleased with getting the following code to take a decimal value (between 0 and 255) and output the binary string equivalent to the screen using scanf() and pri...
stackexchange/codereview
I have found this question online from an Amazon interview: Design a kind of Kindle Fire application where we can subscribe to a news channel and read the news from all publishers as a digital format. I thought that using the Observer design pattern would be a good solution here. Here is my implementation: UnitTest...
stackexchange/codereview
Any input is appreciated! And can I get some advice on how to properly delete the dynamically allocated memory with the destructor? My professor said we have to delete each individual element of an array before doing delete [] array, and I'm not sure how I would do that here because I don't know the length of the array...
stackexchange/codereview
I am taking a Ruby class and our assignment was to write a class that takes two users inputs (1. the time, 2. the amount of minutes to move forward). Then based on the two inputs forward the time by that amount. I am new to Ruby so any feedback on how to improve my code would be great. class Timeshift @time @time...
stackexchange/codereview
From this Stack Overflow answer, I learned that C++17 will have __has_include, which can [make] migrating from experimental to std almost seamless This still leaves the question of how to do it. Doing something like namespace std { using namespace std::experimental; } is undefined behaviour, so I came up with this m...
stackexchange/codereview
Often end up using a Scanner to grab some simple input and often when dealing with Number input it can result in a lot of little bits just to check for valid input. In an effort to reduce this, I tried making it more generic with a Functional Interface and a self contained class to hold the Scanner. The following is th...
stackexchange/codereview
This is a follow up question to 3D bin packing in Java I finished testing my code's result and started cleaning it up. Could anyone please tell me what I should do or fix to clean up this code more? I'm required to put a comment for every instruction line I write. English is not my first language, so maybe some of t...
stackexchange/codereview
I have to write a simple web application using the Java Spring framework as my course project. So I decided to write a simple Stack Overflow clone. My application has the following features: Authorization (using Spring Security); Posting new questions and answers; Voting up/down for questions/answers. I am very new i...
stackexchange/codereview
I have created the code below that compare two spreadsheets . It initially compares the range of value from sheet1 ("Status") to sheet2 ("Interface") . Whenever a range matches with the ranges present in other sheet , it does nothing .When the range does not any matches in the other sheet , then the entire record is co...
stackexchange/codereview
I am a total novice to Python and have been testing my skills recently. I found this particular challenge and wanted to give it a shot. I made this code and it functions well, but very slowly. I was looking for feedback on how to optimize in Python, as well as general Python best practices! Main.py from PIL import Imag...
stackexchange/codereview
Please check my code, did i get some things wrong I'm a newbie in jquery and ajax, please check and show me how to fix this In jsp page : <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>AJAX calls using Jquery in Servlet</title> <link rel="stylesheet" href="jquery-ui.css" ...
stackexchange/codereview
kexec is a way for a Linux kernel to directly boot another Linux kernel without going through the usual BIOS startup sequence, which can take several minutes on enterprise servers. The big problem with kexec is that Linux distributions don't set it up for you when you install a kernel, and setting it up yourself is man...
stackexchange/codereview
I have made two SQL statements as I was unable to figure out how to solve my problem. One is called Product_GetID and the other Product_SaveRecord. I wanted the save record to read and see if there was an ID entered in a field in a VB front end and if there was not, it would assign one for it, but I was unable to figu...
stackexchange/codereview
I have read CLRS Introduction to Algorithms book, now I'm on Elementary data structure chapter. I read about queue concept and try to implement in c. I have tested a lot it work fine, but I have a little doubt on its working. Please tell me this implementation is correct or not. #include <stdio.h> #include <stdlib.h> ...
stackexchange/codereview
So I have a loop that works great, but doing some testing I notice it is a bit slow. I get an average time within the loop of about 0.11 seconds. Include that with some arrays containing a length of over 100 and the time starts making a big difference. So I mainly want to improve the speed of the loop without compromis...
stackexchange/codereview
I'm try to create array of strings from a text file. I need a review from experienced programmers about my program. (MinGW gcc, Win7) #include <stdio.h> #include <string.h> #include <stdlib.h> main() { FILE *file; char *fname = "lines.txt"; file = fopen(fname, "r"); if(file == NULL) printf("Can't read %s", fname...
stackexchange/codereview
I'm a beginner in programming overall, started about a month ago and so I'm still trying to fully grasph the concept of OOP, for instance. Here I used a class for the encryption and decryption processes, but everything else is in functions in the main part of the program (getting the cipher key, user message etc). What...
stackexchange/codereview
I have written this script to stop and start a specific service and check if it was able to load and unload applications tasks correctly, by checking a status in application log. Also it writes a log which tells the sequence of events in the script. I have following questions related to my code : I feel this is not an...
stackexchange/codereview
I have a Pandas DataFrame with users subscription dates in the following format: UserId, StartingDate, EndingDate And I try to calculate the Churn Rate metric for every day. What Churn Rate is: The churn rate, also known as the rate of attrition, is the percentage of subscribers to a service who discontinue their subs...
stackexchange/codereview
I tried to write my first jQuery plugin. It's a very simple AJAX file uploader. HTML <input type="file" id="upload" multiple="multiple" /> Plugin ;(function ($, window, document, undefined) { // Function-level strict mode syntax 'use strict'; $.fn.ajaxUpload = function(options) { var defaults = ...
stackexchange/codereview
I have completed a FreeCodeCamp exercise to create a tomato timer and chosen to do so with vanilla Javascript. Although it works, I don't like in how many places I am checking against two state variables onBreak and isPaused in many areas of the application. (function() { "use strict"; // Initialisation ...
stackexchange/codereview
#include <stdio.h> #include <assert.h> #include <stdlib.h> #define STACK_SIZE 100 typedef struct _stack { char *mem; size_t size; int top; } STACK; STACK *stack_create(char *mem, size_t size); void stack_push(STACK *stack, char c); char stack_pop(STACK *stack); char stack_peek(STACK *const stack); void st...
stackexchange/codereview
Preface I have decided to let my pet project created some years ago to undergo a code review here. The review will be broken into parts according to meta question Multiple reviews or one big review?. The overall concept and motivation can be inspected here (be patient, it takes some time to load). The doxygen generate...
stackexchange/codereview
I recently got a prompt when looking for a job. To spare any details, the company decided not to get back to me, so because I did not get a code-review/feedback from them, I was wondering if someone would review this and tell me how i could improve it. Here is a link to the full prompt (pretty long) with sample input ...
stackexchange/codereview
I am debugging one legacy J2EE application I and think I found some dead code and some redundant condition checks. Please give me your thoughts on my observations i.e. if they are valid. Please note that I am not permitted to rewrite this block, only to fix something if wrong or redundant. ... else if ((emailList != nu...
stackexchange/codereview
I implemented the Dijkstra algorithm from scrath and wonder if I can save some code? The whole algorithm is here. n is the number of nodes, and m the number of edges. 1 ≤ ≤ 10^4, 0 ≤ ≤ 10^5, ̸= , 1 ≤ , ≤ , edge weights are non-negative integers not exceeding 10^8. def restore_heap(heap_arr, dist, updated, vertices2...
stackexchange/codereview
Updated question on 2023-08-31 with extended codebase, since so answers were posted yet. Background I am rewriting a program in Rust, which needs to be able to beep the PC speaker. I am using a udev rule to grant a user in the group beep access to the speaker, which works fine with beep. However, I did not want to invo...
stackexchange/codereview
I've only just started learning javascript and decided to try and make a simple app where individual countries can be selected, highlighting them, and the name appearing in the top corner. The code works, but there as a novice I'm sure its far from the best way to do it! One thing I feel isn't the best is using a globa...
stackexchange/codereview
Now I'm reading C Premier Plus by Stephen Prata and there's an exercise 4 in chapter 6 which has no solution in the book, so I can't check if I did it properly. My code works like it should, but I want to know maybe there are some better or cleaner solutions. Here's the description: Have a program request the user to ...
stackexchange/codereview
First I have two conditions on the number of list elements,then in one of these conditions I have two others conditons to treat it : My code: List<StringBuilder> result = ReadResult_WS_Import(NameFile); if ((result != null) && (result.Any())) { var is_No_Errors_Found_Exist = result...
stackexchange/codereview
A word is balanced at the index if the sum of the alphabet positions of all the chars multiplied by the distance to the index is zero. This description is equivalent to the one given by DailyProgrammer in the challenge info. I did not code Input/Output as I found them not as interesting as the logic. The code works f...
stackexchange/codereview
I wrote this program to convert binary to hex, it ignores other characters between the binary digits. I would like to receive any recommendations on how to improve it. #include <stdio.h> #include <stdlib.h> #include <string.h> const char table[] = "0123456789abcdef"; int main(int argc, char* argv[]) { int flip = ar...
stackexchange/codereview
This question is about improving my C++ coding skills. I was asked to implement a simple static integer stack in C++ as an assignment. I've come up with the following code: class myStaticIntStack { int stackSize; int storedElements; int *elements; public: myStaticIntStack(); myStaticIntStack( int...
stackexchange/codereview
It's been a while since I last looked at C++ so before resuming one of my old projects I thought I'd brush up on the basics so I've written a basic noughts and crosses game (because it's just getting back into the language don't expect a fully fledged game, just a bit of working practice). The game features (or lack th...
stackexchange/codereview
In an effort to rid my code of jQuery, I wrote a custom global event management/handling system. I was expecting this to be hard as, from what I've read, most people don't create their own. It's far simpler than most libraries I've seen. Is there a flaw in this method? What are the benefits of using something like Even...
stackexchange/codereview
I want to use something like Setting.RES_WIDTH in my code without the need for a getter function (i.e.: custom getter, enum's .name(), .toString() or .valueOf()). Someone suggested using a final class, so I wrote this: public final class Setting { public final static String RES_WIDTH = "resolution_width"; ...
stackexchange/codereview
I have to handle an Action (Modify) about my web application. The app working with SMTP Email, ActiveDirectory, External System (Biztalk, CRM, FTP, others WCF Services) and Internal System (WebServices and Databases SqlServer-Oracle). The main action checks several conditions in several entities. There are duplicate c...
stackexchange/codereview
I'm using an HTML editor to insert code into a website. When you embed media like an iframe element, it deletes the code. It's apparently a bug with TINYMce and grappelli, so as a workaround, I insert non-media content into the HTML editor: <div id=”youtube1”><p>width="854" height="480" src="https://www.youtube.com/emb...
stackexchange/codereview
Here comes the next round. I've implemented some of the suggestions from the previous review. That being said, though, there are a few things that I have on the horizons but haven't yet put in that were suggested. I am currently working on implementing dependency injection so that the database object is not redundantly...
stackexchange/codereview
I'm from PPCG so I was making an esolang and I decided to write it in Python. Eventually it went from an esolang to an OEIS (Online Encyclopedia of Integer Sequences) lookup tool. I'm very new to Python. Essentially this program takes an OEIS sequence number (e.g. 55 for sequence A000055) and the nth number in the seq...
stackexchange/codereview
I'm going to implement something like the Unity3D component model for my C++ game engine. Please, review my draft of the Component base class: class Component { public: template<class T> static T* create(void) { if (Type<T>::id == 0) Type<T>::id = ++_idCounter; T* component = ne...
stackexchange/codereview
Explanation This software is currently designed to: Spawn a daemon which controls and monitors multiple threads Create threads based on a 'list' of functions Monitor threads for operation Restart threads if not running Cleanly stop threads and exit upon SIGTERM It runs on a single embedded system, operating Debian 8 ...
stackexchange/codereview
This seems like an easy thing to mess up, so I'd be grateful if you could think of any edge-cases that I've missed. public class StreamIterable<T> implements Iterable<T> { private final Stream<T> stream; public StreamIterable(Stream<T> stream) { this.stream = stream; } @Override public Iterator<T> iter...
stackexchange/codereview
Hobbyist here. I think my case/when logic needs to be cleaned up a bit. I'd also appreciate critique on the other parts...but I'm more interested in cleaning up the case/when statements... puts "please assign an integer to x:" x = gets.chomp.to_i if (x > 0) value_of_x = true else value_of_x = false end puts "now ...
stackexchange/codereview
So, I've written FizzBuzz for a dialect of JavaScript called Dogescript. It has the same functionality as JavaScript, it simply changes some of the syntax points: [A few from the language spec] shh [comment] - // [comment] very [var] is [value] - var [var] = [value] [var] is [value] - [var] = [value] such [name] much ...
stackexchange/codereview
I recently implemented a binary reader/writer for my multiplayer game. Now reading bytes looks like this: static int32_t readInt32(std::vector<uint8_t>& msg, int *off) { if ((*off) > msg.size()) return 0; int32_t result; int size = sizeof (result); memcpy(&result, msg.data() + (*off), size); (*off) += size;...
stackexchange/codereview
Would it be possible to refactor the following methods? If so - how would I go about best doing it? public void PlotListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (PlotListView.SelectedItems.Count == 0) return; var selectedItem = (PlotComponent.PlotList) PlotListView...
stackexchange/codereview
I have a method in a Python app to write a list of records to a CSV file. Each record is a "football player", which is really just a dictionary. But one of the dictionary items contains a list of weekly scores. I want to write out to CSV a record for each player, and then flatten the list of scores and write that ou...
stackexchange/codereview
I'm new to java and I have just finished my very first game - Arkanoid. I would appreciate, if anyone could look at this and tell me some advice and tips how can I optimize my code. Thank you. :) I have 5 classes - Breaker, BlockBreakerPanel, Ball, Paddle, Block. Look: This is the main classs: public class Breaker { ...
stackexchange/codereview
This is my model: class Subject(Document): uri = StringField(required=True,unique=True) resources = EmbeddedDocumentListField('Resource') date_modified = DateTimeField(default=datetime.datetime.now) meta = { 'indexes': [ {'fields': ['uri'], 'unique': True}, ], } class R...
stackexchange/codereview
I'm in the process of writing a matrix like container to store objects. Despite many existing matrix implementations, I won't do numerics. Instead I want to replace a std::vector<std::vector>> variable to increase performance (memory allocation and cache misses are an issue with this double-vector implementation). I wa...
stackexchange/codereview
The input is a set of alphabets. The output is a string of 32 in length. For any letter in the set if it is preceded by a '¬' we replace the n-th character in our output string with '0', such that n is the position of the letter in the alphabets. If it is not preceded by a '¬' and was there in the set then we replace i...
stackexchange/codereview
This is my first dice game and I have spent countless hours working on it, yet it is still very basic. I was wondering if anyone could spare the time to suggest improvements. import time import random import sys Password= 'password' while True: password= input('ENTER PASSWORD:') if password == Password: ...
stackexchange/codereview
I am working on a multi-object recognition program. I have succeeded recognising two objects. However, the speed of my program is really slow and laggy. Can somebody please tell a way to speed the program up? So far, I have seen that ORB is quite fast at matching features. However, my program is still too slow. I have ...
stackexchange/codereview
I've written a function in Haskell for calculating the entropy of a collection. I'd like feedback on how the function could be rewritten to be more flexible/reusable, and also how to profile the function and how it could be tuned and/or modified for better performance. import Data.List (foldl1') entropy :: [Int] -> I...
stackexchange/codereview
Goal I am aiming to create a page with two columns, left side to be a summary section and the right side just an image. I'd like to hear some reviews to where I can improve my current html and css code :) It is not yet media responsive, just wanting to improve each step at a time. * { margin: 0; padding: 0; }...
stackexchange/codereview