instruction
stringlengths
71
71.9k
I have completed my homework with directions as follows: Declare and implement a class named Binary. This class will have a method named printB(int n) that prints all binary strings of length n. For n = 3, it will print 000 001 010 011 100 101 110 111 in this order. Here is my code: import java.util.Scanner; c...
I'm new to Haskell, and here is my first not-totally-trivial program. It's the first program I tend to write in any language -- a Markov text generator. I'm wondering what I can change to make it more idiomatic, or what language features I could make better use of. import Data.List import System.Environment import qual...
Please review and recommend improvements. It looks horrible to me, difficult to read, too lengthy, and just plain old inelegant. But I don't see the potential improvements. private boolean useCachedReportBean(BeanReport cachedReportBean, String strRequestedReportID) throws ExceptionInvalidReportRequest { /*...
I'm implementing Kruskal's algorithm in C++11 and would like feedback on style and performance on my graph data structure and algorithm for educational purposes (for production code, I'd use a pre-existing library). The main design questions I have are: Is there a better way to implement the handle class for the graph ...
Lets imagine we have an Article entity, with data imported from a legacy database. It contains an appendix column with type integer. This column is always filled with values 0, 1 or nil, so we decide to call it in_appendix with type boolean. We want to preserve all existent data so we convert the data like this: class ...
I am happy to receive all recommendations for improvement. But below I am mostly interested in a review of my handling of the exception thrown by the close() method of RandomAccessFile. The FileNotFoundException thrown by the opening of a file (in the constructor of RandomAccessFile) is declared as thrown by my method...
Consider this simplified code which successively permutes array elements: import Data.Word import Data.Bits import Data.Array.Unboxed import Data.Array.Base import Data.Array.ST test3 :: UArray Int Word32 -> UArray Int Word32 test3 arr = arr `seq` runSTUArray (change arr) where change a' = do a <- thaw a' ...
I have just picked up Scala like 2 hours ago, and I am thinking of printing a series like 1 to 10 but in a recursive fashion. I do not understand what is wrong with this: def printSeries(x:Int):Int = { if(x==0) doNothing() else doSomething() def doNothing() = {} def doSomething() = { println(x) printSe...
I am learning C from K.N. King and at ch-17, I covered linked list and wrote a code to add data in the ascending order in the linked list which is opposite to found in the book (In the book, it store in reverse order). Here's the code: #include <stdio.h> #include <stdlib.h> typedef struct NODE { int value; str...
I am writing a basic image upload script in PHP, and am looking for critiques. The script below is the result of various suggestions I have found online... for now I am running it locally and it works fine, but I would love for someone more experienced to look over it. Is this secure? Poorly implemented? Too redundant?...
I have a collection of PlaylistItem objects. They are linked together such that each item knows the ID of its next/previous item. I am iterating over this collection of objects, starting at a known position and working with each object once. I'm not a big fan of how I do this, but I am not seeing an obvious way of rewr...
For my display functions in my Blackjack game, I want to control each player's stats output based on whether a turn is in progress or has ended. Normally, you could only see one card that your opponent(s) hold, while the rest are only revealed at the end of each turn. My code does that well, but I'm having trouble ma...
My program has to decrypt ciphertext. It has to try all possible 26 shifts and store each in an array so that I calculate the frequencies of each array and find the highest frequency, in which that would result in the plain text. #include <stdio.h> #define CIPHERSIZE 42 char decryptCiphertext(char data[], double data2...
I have been working on a project where I needed to analyze multiple, large datasets contained inside many CSV files at the same time. I am not a programmer but an engineer, so I did a lot of searching and reading. Python's stock CSV module provides the basic functionality, but I had a lot of trouble getting the methods...
I am hoping to streamline this bit of code better. This snippet does not cause my any slow downs in relation to other parts of the algorithm(?). I would just like guidance on making it better. Some variables not given by code: regionDimensions = whatever you want. (256) hexagonArray[,] = new Hexagon[regionDimensions,...
The goal of my assignment is simple: Write a program that converts a given text to "Pig Latin". Pig Latin consists of removing the first letter of each word in a sentence and placing that letter at the end of the word. This is followed by appending the word with letters "ay". Example Input: THIS IS A TEST O...
I have a dropdownbox, ActiviteitAardItems, where ActiviteitAard items can be checked (checkbox). If one (or more) are checked the property Opacity will be changed, and the code beneath will be executed. The Tijdblok mentioned below also has a property Activiteit and ActiviteitAard. public double Opacity { get {...
The new MultiWayIf extension (available with GHC 7.6) allows guard syntax in an if: {-# LANGUAGE MultiWayIf #-} fn :: Int -> String fn x y = if | x == 1 -> "a" | y < 2 -> "b" | otherwise -> "c" But I don't find it better than the old way: fn :: Int -> String fn x y | x == 1 = "a" ...
I really like using the new TAP pattern in .Net 4.5. and I am updating some of my older projects to use it. One of my old patterns was to use EAP with WCF so I could have functions that could take longer than 60 seconds (the default timeout for WCF) to complete without doing custom setup on the client side App.Conifg. ...
Coding to the interface, rather than the implementation. Here is what I'm doing in simple terms. Note: Although written using PHP, this is more of a general design / abstraction question that developers using any language could help answer. I'm writing an application that can handle different types of connection to gat...
I have to run a python script that enters data into MySQL database table. My below query runs and inserts data into MySQL database. But I want to optimize it and I have 2 requests: I want to use try except error handling inside the for loop. Probably before insertstmt or where it would be more efficient. If there is b...
To work around the XmlSerializer memory leak thing I created this: public static class XmlSerializerCache { public static XmlSerializer GetXmlSerializer(Type type, XmlRootAttribute xmlRoot) { var cache = System.AppDomain.CurrentDomain; var key = String.Format(CultureInfo.InvariantCulture, "Cache...
I have the following code: const String sqlSelect = "SELECT * FROM UserPasswords WHERE username='System Administrator';"; const String sqlInsert = "INSERT INTO UserPasswords VALUES (@username,@Password,@startDate,@Expired,@UserPasswordsID)"; using (var con1 = new SqlConnection(System.Configuration.ConfigurationManager....
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...
The goal of this was to be able to enter any number and print out the prime factors of that number. Are there any shorter ways of writing this code? I'm not very familiar with low-level syntax and was hoping somebody could give it a look. .text .align 2 .globl main main: # compute and display the first prime numbers...
The class does some database abstraction operations. And while I could have just used an ORM, I prefer to get my hands dirty when learning something new. There are no bugs (not as far as I know anyway) and the code is working as intended. But, since I'm learning Python, I want to make sure I'm thinking and working in t...
I recently built an improved version of a bank account program I made. It has no GUI or any interaction with users, but I simply built it to test it and play with it via main(). I'll post all my classes below and you can run the program yourself or just critique my code. I'll take any and all suggestions, so please lea...
I have started working with Cassandra database recently and I was trying to insert some data into one of my column family that I have created. Below is the code by which I am trying to insert into Cassandra database. In my case I have around 20 columns in my column family so that means I need to add below line mutator....
I'm trying to create a wordpress plugin but checking for the existence of a value doesn't really feel right because there's a bunch of values that I have to check: $flickr_key = ''; if(!empty($ecom['ecom_options_flickr_api'])){ $flickr_key = $ecom['ecom_options_flickr_api']; } $flickr_secret = ''; if(!empty($ecom['e...
There are not many available resources for refactoring go code. I'm a novice gopher who would appreciate any feedback on a small program which reads a .csv file, string converts and parses a few rows in order to perform a sub method. package main import ( "encoding/csv" "fmt" "io" "log" "os" ...
I came across the following piece of code in a UI application I need to maintain. int tool_unhex( char c ) { return( c >= '0' && c <= '9' ? c - '0' : c >= 'A' && c <= 'F' ? c - 'A' + 10 : c - 'a' + 10 ); } void unescape2QString(const char *sOrg, QString & str) { /* * Remove URL hex escapes from s...
I have a few Python codes like this: workflow = [] conf = {} result = [] prepare_A(workflow, conf) prepare_B(workflow, conf) prepare_C(workflow, conf) result.append(prepare_D_result(workflow, conf)) prepare_E(workflow, conf) #.... about 100 prepare functions has the same parameter list I was wondering that w...
I use this code to Load and Insert data to a table using a DataGridView in a C# windows application. SqlCommand sCommand; SqlDataAdapter sAdapter; SqlCommandBuilder sBuilder; DataSet sDs; DataTable sTable; private void form1_Load(object sender, EventArgs e) ...
I've made an algorithm solving Hanoi Tower puzzles, for n disks and m pegs. It uses lists as pegs, each list's element contains disks array - {0, 0, 0} means the peg is empty, {1, 2, 0} means the peg contains "1" and "2" disks, {3, 0, 0} means the peg contains the biggest disk only. The algorithm is iterative (and has ...
I need concurrent HashMap of List as value with following behavior: count of read/write ops approximately equals support add/remove values in lists thread safe iterations over lists After some research I implemented ConcurrentMapOfList, but I'm not sure in his correctness. public class ConcurrentMapOfList<Key, ListVa...
I got this answer here: https://stackoverflow.com/questions/15902299/selecting-an-item-in-a-listbox-to-assign-it-as-a-temp-variable Suppose you have loaded the lisBox1 with objects of type Genre. lisBox1.Datasource = this.GetAllGenresFromTextFiles(); lisBox1.DisplayMember = "Genre"; Add an event to SelectionChanged o...
I'm no stranger to JS, but I think I still have a lot to learn. I originally wrote this code to manipulate a "help" bar, which would be positioned as a thin ribbon on the side of the browser window, which when hovering over or clicking would open up and display it's contents. Nothing major, but an okay example to use h...
I have the following dataset in numpy indices | real data (X) |targets (y) | | 0 0 | 43.25 665.32 ... |2.4 } 1st block 0 0 | 11.234 |-4.5 } 0 1 ... ... } 2nd block 0 1 } 0 2 ...
I was wondering if this is the correct implementation of a times task to destroy a thread after it overruns a predefined time period: It works by creating a getting the thread from runtime.getRuntime, which it then uses to create a new process to run a command with the exec() method (creates a sub process). This is the...
I have a merge statement that takes around 10 minutes to process 5 million or more records. The merge statement is part of a stored procedure that takes my newly bulk loaded staging table then runs data integrity checks, transforms the data into the proper format, and inserts that data where it should go. Here are the ...
This is my first attempt at using Python to send http requests. I want to keep a zone record on cPanel pointed at my home network's public IP. I'm just looking for some general feedback/suggestions. Is there an easier way to do this? Is there a more Pythonic way? My intent is to run this as a cronjob to stay ahead...
This is my attempt at constructing a singly-linked-list with basic functions. I initially tried to build the whole list as a series of nodes, but ran into problems when trying to remove or pop index-0. This time I created a series of Node structs and a single List struct as their head. This allowed me to modify the ...
I have 3 fields: Net Price (ex. tax) tax amount Total price (price ex. vat + tax amount) The NetPrice and the Total are writable (i.e. you can change either of them and the other 2 values must be auto-calculated). The way I've done it is using 3 observable and 2 computed knockout objects but I thought perhaps someone...
I have constructed a simple implementation of a parallel loop: #include <algorithm> #include <thread> #include "stdqueue.h" namespace Wide { namespace Concurrency { template<typename Iterator, typename Func> void ParallelForEach(Iterator begin, Iterator end, Func f) { std::vector<Iterator> its;...
I have a functionality that imports data into a database, based on an Excel workbook and some meta data (both user-supplied). The functionality implements interface IFunctionality which essentially specifies an AuthId string property (used for fetching authorized AD groups for a functionality) as well as a CanExecute a...
The problem I am facing is: I need to interate through a bunch of lists, and there are separated conditions which needs to be satisfied by the list. conditons are not independent. I care about the situation when all the conditions are matched. The solutions I come up is nested interations mixed with conditions on each...
I'm very new to coding and have been diving into the skill with Python as my first language. One of the first programs I wrote for a class was this Tic Tac Toe game. I re-wrote this game using classes and have just recently refactored it looking for different smells. The person who's been teaching the class suggested t...
Here's a part of my controller and it's getting quite lengthy (the code works). Would this code slow down the performance of my website? Can it be cleaned up and be written more efficiently? def create @post = current_user.posts.build(params[:post]) if @post.save if @post.verify UserMailer.verify_email(...
I have just started to try and learn 'OOP' but it appears I'm doing this wrong, according to the people on Stack Overflow. The code below is far from object-orientated, but I'm finding it hard as I'm self teaching my self and everyone does everything differently. I'm building a shopping cart and I need to be able to h...
I have recently created my first game in C++: #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { cout<<"\tWelcome to Guess my Number!\n"; const unsigned short kusiLower=1; const unsigned short kusiHigher=100; srand(time(0)); unsigned short usiComp=rand()%kusiHi...
I have just started learning erlang...I am just practicing the recursion and all in erlang...I tried to write a few of the list processing functions on my own in erlang...Can someone review the code and give some advice on it... -module(listma). -export([duplicates/1,reverse/1]) %% Remove the duplicates in a list dupl...
I am using jQuery's collapsible lists grouped and named #List01, #List02, #List03, etc. My code captures clicks on list elements and remembers list items' ID for further processing. Each group has identically looking code so I was wondering how I could encapsulate it in one function. $(document).on('click', '#List01 li...
I'm trying to improve my OOP code and I think my User class is becoming way too fat. In my program a user has rights over "lists". Read, Write, Update, Delete. So I made a User class class User { protected $_id; protected $_email; protected $_username; protected $_hashedPassword; //...Various setters/getters public f...
Take the below code: public interface ISettingsManager { SettingData GetSettingByIdentifierOrCreateIfDoesNotExist(Enum identifier); T GetSetting<T>(Enum identifier); } [IocComponent] public class SettingsManager : ISettingsManager { private readonly ISettingGetItemByIdentifierService _settingGetItemByIden...
Without changing the semantics and performance, how can I make this where clause more readable? where (@Category = 'all' or (@Category = 'omitted' and Category is null) or (@Category = Category and ( @SubCategory = 'all' or (@SubCategory is null and SubCategory is null) or (@SubCategory ...
I've combined some of my own functions with a function I found and I'm curious to know what others think of it. It will be used to upload and resize/crop images that are jpeg, jpg, png. <?php class ImageUploader { var $multiple_file_upload = true; var $max_size = 1024; var $mime_types = array('bmp' => 'imag...
I've got a string that consists of an arbitrary combination of text and {} delimited python code, for instance, A plus b is {a + b}. However, braces are used for dictionary and set literals in python, so You chose the {{1:"first", 2:"second"}[choice]} option should also be interpretted correctly. It's also valid to h...
Of all the macros that I put into heavy rotation these days, this one is running the slowest. ~4-5 seconds depending on the size of the files. It's not a lot but I'd like to know why code 16x as long is running much more instantly. The code tries to merge documents (usually 2 excel docs out of at most 5) depending on t...
I wish to create audit trails for specific tables and columns in my database, and document who made the change, when it was made, and what the change was. To do so, I will create the following tables: Audits: Create a record whenever a change is made to any table, and stores the table, the date, the user who made the...
I'm learning Ember, and I've come across a situation where I haven't been able to find a pattern online. My application's main route includes a list of "stories" (think scrum). However, this list also has a StoryController associated with it. I don't want to assign the stories in the IndexRoute file; it doesn't feel ...
I want to do some object-oriented programming in Lua, and I decided on something like this: local B = {} -- in real life there is other stuff in B B.Object = { constructor = function() end, extend = function(this, that, meta) if not that then that = {} end if not meta then meta = {} end meta.__index ...
I have this piece of Java (Android) code that adds a list of brokers to a local SQLite database as one single SQL instruction. public void Add(List<Broker> brokers) { if(brokers == null || brokers.size() == 0) return; String sql = "INSERT INTO " + TABLE_NAME + " SELECT " + brokers.get(0).getId() + " AS '...
I have a abstract class which is extended by many many other classes: What I have done: public abstract class AbstractActionHandler { protected WorkItem currentWI; protected String status; protected String field; protected void init(WorkItem currentWI, String status, String field) throws IllegalArgume...
Here's a fiddle: http://jsfiddle.net/YF8cg/ Focussing entirely on the javascript and on the structure of the HTML (.qapair .question and .answer), how could I improve this system? JS: $(document).ready(function() { $('.question').click(function() { $(this).siblings('.answer').slideToggle(400); // Disp...
I'm new to Rhino mock and I would like to know if the test I did is not fake testing, as I've read a lot about it. Are there any improvements that need to be done? [Test] public void GenerateDateTable_Returns_DataTableOfGroup() { //Arrange var groupStub = MockRepository.GenerateStub<Group>(); var groupEnume...
You can find a JSFiddle demo of my tabs. The jQuery tabs work well as intended. However I was asked to include arrows alongside the tabs so readers could navigate through tabs using them instead of the tab titles alone. So I used: $("li.tab").click( function() { $('#div1').removeClass( 'hide' ); $('#div2').removeCl...
I'm trying to convert TimeSpan object to text that can be read like a sentence. e.g. TimeSpan(2, 1, 0, 0) --> "2 days and an hour" TimeSpan(1, 2, 1, 0) --> "A day, 2 hours and a minute" Some more samples for conversion are in the 'TestCases' object under 'TimeSpanPrettyFormatterTests' class. Is there any better way ...
numerator: Value being divided. denominator: Divisor value. method so far: def calc_percentage(numerator, denominator) ((numerator/ (denominator.to_f.nonzero? || 1 )) * 100) end What are the bad practices you see in the code above? How can I improve it or write it in a better way ?
I have this ugly age printing method. Can you do better? def age(birth_date) today = Date.today years = today.year - birth_date.year months = today.month - birth_date.month (months -1) if today.day < birth_date.day if years == 0 && months == 1 age = "#{months} month" elsif years == 0 && months > 1 ...
Before I try to make this work, I wondered if anyone had tried this, whether it was a good idea or not, etc. I find myself doing this a lot: if some_result is None: try: raise ResultException except ResultException: logger.exception(error_msg) raise ResultException(error_msg) I would ra...
I have a class with 2 date properties: FirstDay and LastDay. LastDay is nullable. I would like to generate a string in the format of "x year(s) y day(s)". If the total years are less than 1, I would like to omit the year section. If the total days are less than 1, I would like to omit the day section. If either ye...
I want to know if using volatile in this scenario will give better performance than using synchronized, specifically for the paused and running instance variable in the SimulationManager class. public class SimulationManager { private List<SimulationPanel> simulations; private boolean paused = false; priva...
Tonight I decided to revamp some code I wrote a few months ago. One part of that was to do with showing (and hiding) tooltips. The functions are called with: jQuery(element).showTooltip('HTML'); jQuery(element).hideTooltip(); The old code $.fn.showTooltip = function(text) { /* Remove any existing tooltip. */ $...
Generally speaking, I try and write my classes so they are highly cohesive. Sometimes I have accessors (this problem isn't limited to accessors) which derive their value from non-public data only, which lowers cohesion. (http://www.ndepend.com/metrics.aspx#LCOM) Take the following class example: public class Person { ...
A friend of mine asked me a question recently. He was needed to subscribe to an event of some object (window button click) and unsubscribe from it on a first call of a handler. Also he noticed that object is dynamically created and his handler is a delegate. After some thinking I came up with a solution using closures ...
public function getStuff($brand) { $web=FALSE; if($this->getWebcorners()): foreach ($this->getWebcorners() as $webcorner): if(strtolower($webcorner->getBrand()->getName())== $brand): return $webcorner; endif; if($webcorner->getB...
I'm fairly new to JavaScript and jQuery and this is my first attempt at creating a plugin. The code below I've written to parse a JSONP feed from a search engine API (funnelback) using ajax() calls. The returned object is used to create a set of results, some pagination links, a facetted navigation etc, everything you'...
I submitted a previous version of this program but I've completely rewritten it in an Object Oriented style. This is only my second attempt at OO programming so I'm interested in hearing how I can improve things. Here's the main program: import tweepy import sqlite3 import json import re import time import datetime imp...
I would like feedback on how to optimize this jQuery plugin used for triggering change event on any DOM element. This plugin doesn't use a timer to check for DOM changes but instead extends some jQuery native functions. I'm mostly concerned by the .on() method extension because I'm sure there is better way of doing thi...
I'm understanding the question, but I want to know whether or not my implementation is correct. The question is: Write a method that accepts as its argument a BinaryTree object and returns true if the argument tree is a binary search tree. Examine each node in the given tree only once. This is my implementation: ...
Consider this class: using Ninject; using Ninject.Syntax; using Ninject.Parameters; namespace MyApp.Dependencies.Factories { public abstract class FactoryBase<T> where T : class { private IResolutionRoot _resolutionRoot; protected FactoryBase(IResolutionRoot resolutionRoot) { ...
The struct and the prototypes of the functions were given in the question. I am unfortunately aware that this is more C code and less C++ code. I am looking to compact my functions (specifically ordered_insert and find_remove) without removing functionality. For example, at the moment my find_remove function works if ...
This script updates a MySQL database with golf scores and calculates how many strokes under the player is in real time and is working. I'm just looking for a better way to make it cleaner and compact. <?php // Get values from form $uid=$_POST['uid']; $name=$_POST['name']; $course=$_POST['course']; $h01=$_POST['h01']; ...
This is a security question. I'm quite new to PHP and just a beginner in SQLite. For practical, and educational reasons, I'm writing a small PHP site that will serve as one-threaded discussion (meaning, only one topic / no topics) between me and my friends. The site will be open to the Internet and the final version wi...
I am writing a method to find me a price range for special price as well as the retail price. Such as in example below I have price range for retail from 129 to 329 where as special price range is 89 to 199 array 0 => array 'id' => 83739000038374 'special-price' => 99.99 'retail-...
The exercise is as follows: Create a class called Fraction that can be used to represent the ratio of two integers. Include appropriate constructors, properties, and methods. If the denominator becomes zero, throw and handle an exception. Create an application class to test the Fraction class. The program runs. ...
I have some code that allows me to enumerate over months in a year. This code is used both in a Web application as well as a standalone exe. Although it doesn't have to be efficient it is used a lot so if there are any improvements that would be great (I haven't done any profiling). It also needs to be thread-safe. ...
When a user is created, deleted and update the system will give feed back. e.g. User Deleted/Updated/Create success or unsuccessfully, but I'm sure there is a better way to do it than what I have done because I repeat the same code in all functions within my class. Code to create user $userOne = new userActions($databa...
I am working out a bit of Clojure code that will take a ref to a map and increment a key value pair in the map. I think I am using ref correctly, but Im not sure about atom. Do I need to use swap! to be more idiomatic? I am new to STM and Clojure, does this look thread-safe / sane? What am I missing? (defn incremen...
I am doing exercises for the Art and Science of Java textbook. I had an exercise that required me to program the simulation of flipping a coin until 3 consecutive "Heads" result appeared. I did it, but I'm not sure if my code is simple enough - since I used an instance variable to count the heads and a function that no...
I'm writing a program that downloads stuff from the internet. While the program is working fine, I want to get one critical part reviewed. I use System.Diagnostics.StopWatch object to measure the time taken for the ns (NetworkStream) object to read the bytes in buffer. I then divide the number of elapsed seconds in sto...
For a WordPress login form I have written a small plugin. It adds a checkbox with a unique name to the form and if that name is not present in the login POST request it just dies. The idea is preventing scripted attacks made for regular WordPress login forms. The PHP code is okay (imho), but I think the JavaScript code...
with below query i'm getting the results that i want but it's quite slow taking nearly 0.2 seconds (on an i5 machine). Is there a more optimized way to get the same results. Basically this query fetches the last 20 rows in the table and shows only one row per yzr.name and orders by yzr.favorite_count SELECT gzt.n...
I have to write this program in java. Write a program name sorting.java that will use an array to store 10,000 randomly generated numbers (ranging from 1 to 10,000 no repeat number). Here is what I have so far: public class Sort { public static void main(String[] args) { Random rgen = new Random(); ...
I've found two ways of writing the same program (one that only uses local variables, but no methods other than the main one) and other that uses one instance variable that is used in two methods. This program aims to simulate the radioactive decay of atoms and uses a random number generator. Here are the two versions o...
Basically, I'm performing an if statement on an array based on the returned value <?php if($array[1]>10000 AND $array[1]<50000){ $selling = $array[1] - 250; } elseif($array[1]>50000 AND $array[1]<100000){ $selling = $array[1] - 500; } else{ $selling = $array[1] - 100; } $...
Here's my code. Please review it for correctness, readability and efficiency. If you think it can be improved also let me know. This code works fine for positive numbers but doesn't for negative. How can I change it ? Any comments for improvement will be appreciated. int sum(int a, int b) { int sum = 0; ...
I feel this is deeply inelegant, but I really want the option of classical inheritance in the future. How could this be written better. FYI animation here is from GSAP if you are curious. class Modal angular.element(document).ready => @modalElem = document.getElementById 'modal' @overlayElem = do...
How can I optimize this code to have fewer loops and return values for unit testing? public class Diamond { public void DiamondShape(int num) { for(int ucount=num;ucount>0;ucount--) { //Loop to print blank space for(int count_sp=1;count_sp<ucount;count_sp++) System.out.printf(" "); //Loop to print * ...
I wrote a Connect Four game including a AI in Clojure and since I'm rather new to Clojure, some review would be highly appreciated. It can include everything, coding style, simplifications, etc. But keep in mind the AI is not finished yet, other heuristics will be added in the near future. Currently it only cares abou...