instruction
stringlengths
71
71.9k
I'm new to programming, became interested in learning a while ago and only got to it recently. I'm working on a very simple text-based adventure game using Python, and would like some tips on simplifying my code. Any other tips are also welcome. Please don't criticize the storyline though, since this is not the point o...
This is for a university assignment (don't worry the code is in working order), and while I could hand it in as-is and receive full marks I feel like there is probably a more efficient and better way to handle what I am doing. What the code does Takes user input of 4 names and for each name take True / False assignment...
I use this code to get values from SharedPreferences. public static String getSharedPreferenceValue(Context context, String key) { SharedPreferences sp = context.getSharedPreferences( Utility.PREFERENCES_NAME, Context.MODE_PRIVATE); String value = sp.getString(key, Utility.EMPTY_STRING); return value; }...
Description: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. ... Of course I didn't include the numbers in the description... I am sure there is a better way to do this. I just did a simple solution, where I add all the numbers and take the first 10 digits. import java.math.B...
I have made a custom keyboard that gets loaded from an .xib file. I decided to go with an in-app only keyboard rather than a system-wide keyboard because the documentation states: Make sure a custom, systemwide keyboard is indeed what you want to develop. To provide a fully custom keyboard for just your app or to ...
This is a hash map library for C that stores void* pointers with char* strings (null terminated) for keys // ColiisionHashMap // Copyright © 2015 Leo Dastur. // #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct HashMapNode { char* key; void* data; } HashMapNode; typedef struct HashL...
I have written this function (and others similar to that one) But I am not sure I am using references on their full power. My currently concerns is if I make a huge use of memory. The subroutine recieve a reference to two files, the subroutines, like these one return a hash (except &log_time, which returns a scalar). T...
The code works as it is but it's very messy. Is there a way to clean up the null checking in the if statement? public function submitCoil ($data) { $db = Database::getInstance(); //Define certain query values $uniqueID = $this->hash("id"); $queryData = array( 'fields' => array( 'uni...
I wrote a Logger which uses the destruction of temporary objects to Log their values including a scope time logger. Lets see what i can improve here to increase the performance and everything else. class Logger { public: static inline LogMessage Log(LoggerTypes type, const std::string& file, ...
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: ...
I used to get a JSON file with some configuration settings from the file system, using this class: public class ConfigurationFileService : IConfigurationService { private readonly IConfigurationManager _configurationManager; public ConfigurationFileService(IConfigurationManager configurationManager) { ...
I have the following function for turning on some ports on a piece of hardware: public Boolean SwitchOn(Int32 portNumber) { HttpCommandBuilder builder = new HttpCommandBuilder(_ipAddress); builder.Command = HttpCommandBuilder.CommandType.SetPower; String result; if (portNumber == 1...
I wrote a simple program to sum the digits of a number in Clojure for learning purpose. Not very complex (I hope) so not adding any explanation. I am a beginner in Clojure so please don't mind pointing out even the most obvious mistakes. NOTE: It recursively calculates the sum of digits in the result until a single dig...
First, some code. I have a class, Circle: package aag; public class Circle{ private final int RADIUS; private float xVector; private float yVector; private float xCurrent; private float yCurrent; public Circle(int radius, int xCurrent, int yCurrent){ RADIUS = radius; this.xCu...
I really like c#'s Using statement as it allows you to pair Open statements with their corresponding Close/Dispose statements in an elegant way which matches C#'s syntax. I realised that something similar can be achieved in PowerShell; e.g. Push-Location should be paired with a Pop-Location, and this can be enforced by...
Here is my code in Ruby that shows the look-and-say sequence. It shows correct result, but my teacher said, that I could actually make it better. Can you tell me what the flaws are there in my code? In the input I tell how many sequence elements I want to see. For example I type 5 and get: 1 11 21 1211 111221 class ...
For my assignment, I have to take a data set and stratify sample it into three different training sets (one with 10%, one with 30%, and 50%). Then I have to classify it using a Naive Bayesian classifier I believe I did here, but since the code is very non-functional, I'm not sure if I'm going about it the right way. I...
Does exist a cleaner way to call a static method inside ES6 Array.filter function ? mine(input = '') { var translatedAnswers = this.constructor.translate(this._defaultAnswers); var self = this; return translatedAnswers.filter(function (answer) { return self.constructor.match(input, answer); });...
Given four lists of numbers, calculate how many ways there are to choose one element from each to get a sum of zero. The input is given on stdin, first the length of all lists n, then n tuples containing an element from each, like this: 6 -45 22 42 -16 -41 -27 56 30 -36 53 -37 77 -36 30 -75 -46 26 -38 -10 62 -32 -...
I'm currently working on a project where I have to map some objects to several properties. Basically I need a Dictionary with Tuples as keys and instances of MyClass as values. As using tuples can quickly lead to an obscure (because of item1, item2... properties) and verbose code I decided to make a class to wrap the t...
I am fairly new to Python. I implemented a short cross-validation tool for gradient boosting methods. import numpy as np from sklearn.metrics import roc_auc_score as auc from sklearn import cross_validation from time import time def heldout_auc(model, X_test, y_test): score = np.zeros((model.get_params()["n_estim...
A lucky number is defined as a positive integer whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. I need to check if a given number is evenly divisible by any lucky number or not. Now, suppose I want to add all Lucky Numbers under a g...
I have posted my first version of RockPaperScissors a while back. It was on an old version of python with improper use of some functions. This version was updated to a more recent version of python and has a little extra for users who run on terminal. Is there anything I should add or change? Are my classes used correc...
I'm relatively new to Python scripting. I made a script that takes two raw data files and merges them into one CSV file, but it takes a long time to complete. Are there any logic problems in this code? input_fileVms = open( 'vms.csv', 'rb') if site == 'eg': output_merge = open('mergedFileEG.csv', 'wb') elif site=...
To learn about classes, I chose to create a little something that checks if you have included the following: @ sign Provider (e.g. 'hotmail') Domain extension (e.g. '.com') It also checks if you entered spaces in the address and gave the option to keep them or get rid of them. I would really like some feedback on wha...
I'm an 'old school' programmer (C, C++), and I have step-by-step, algorithmic thinking. I'm writing some code in Angular + Django and I know that this code is ugly but I don't have any idea how to refactor it. First of all, I have the models: class Product(models.Model): name = models.CharField(max_length=100) ...
Lets say we need to write an algorithm for giving money to the bank. We need to know interest rate, money which we put every year on our account, and amount of money we want to get. F.e int. rate is 1%, money we put every year is 1000 (or whatever) and we want to get 10000 (not more). It'd look like this: MoneyOnAcc=1...
I tried to make an is_Prime() function in PHP. What do you think about this code? <?php function is_Prime($x) { if($x <= 1) { echo $x. " is not a prime number.</br>"; return false; } $data = array(); for ($i=1;$i<=$x;$i++) { if(is_integer($x/$i)) { array_push($data, ($x/$i)); }...
I have taught some SQL to others before, and I thought of making a script that has these attributes, for the purposes of teaching: Fully functional to run on local DB instance with no fuss Easy to follow along Representative examples of real-life types of operations Documented The example first goes over some Data De...
def toPairs[A](xs : Seq[A]) : Seq[Tuple2[A,A]] = { @tailrec def accumulator(as : Seq[A], accum: Seq[Tuple2[A,A]]) : Seq[Tuple2[A,A]] = as match { case Nil => accum case x :: tail => tail match { case Nil => accum case _ => accumulator(as.tail, accum :+ (x,tail.head))...
Now I have task very similar to this: Job is a group of print items. For example, a job can be a run of business cards, envelopes, and letterhead together. Some items qualify as being sales tax free, whereas, by default, others are not. Sales tax is 7%. Also applies a margin, which is the percentage above printi...
I find it hard to do integration tests for a repository and very time consuming. Things I think about when creating integration tests for a repository: Should I skip them? Should I create an in memory database? Should I create a local database for the test? Should I delete inserted data? Is my repository caching resul...
Following is my hand-rolled implementation of name demangling for names generated by Microsoft's compiler, partially reimplementing the UnDecorateSymbolName WinAPI function. static std::string getCallConv(char code) { static const std::map<char, std::string> callConvs{ { 'A', "__cdecl " }, { 'I', ...
I'm pretty sure there's no better way to do this but I thought a consensus on here might be nice. Let me know what you think. public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue = default(TValue)) { TValue value; return dictionary.TryGetVa...
I'm training my coding and wish you guys to see how my code is. I made a cat clicker based on the MVC pattern. Basically it shows a list of cats and when you click a cat name it shows an image, and if you click the cat image it increments the number of clicks you made in the image and shows it. By the image there is an...
I made a dynamic CSV formatter as a personal challenge after having to hardcode a behavior to convert some data to CSV earlier. You input any List that contains supported types as properties (all primitive types, strings, or collections of primitive types or strings). And it will spit out a list of strings that are eac...
My current student accommodation uses a manual paper and pen system for checking if students have mail so I made this simple Python script to help mitigate the problem of manually searching through spreadsheets just to see if you have mail or not, which I have been asked to demo soon. It's quite basic but I figured I s...
I made a differential equation solver to forecast heat loss through a pipe with heat loss coefficient contours. It does what I want it to do but I had to use global variables to change the outputs of my simulation function - is there a better way to deal with this issue? Another problem I have is that my code is very s...
I recently participated in a small friendly competition and this was one of the questions: A number whose only prime factors are 2, 3, 5 or 7 is called a humble number. The first 20 humble numbers are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, ... Given n, find the nth humble number. E...
I'm on a quest to combat all the magic strings which tends to pile up in an ASP.NET MVC application. All reviews will be highly appreciate but please note that: Some of the classes contains more (unrelated) code than I've presented here. I do not use the c/c++ type aliases (unless forced to as with base type of an enu...
I have the class SeguimientoSeccion with this relevant attributes public class SeguimientoSeccion implements Serializable { private Integer id; private Transportista transportista; private String fijacion; private Integer month; private Integer year; } I created a custom comparator to sort by ye...
I'd like to see if I can somehow make this loop more effective (smaller?). I'm using MultiDatesPicker to make a reservation plugin. And I've set everything right, and everything works, but I'd like to see if my jquery code can be optimized somehow. HTML looks like this (minus the actual calendar): <div class="reservati...
I have a WCF service that work with databse. The service should handle incoming message and store messagId into database. Please suggest me how can I improve it? public class DBWorker { static DBWorker instance; private string connectionString; private SqlConnection connection; protected DBWorker() ...
I recently read K&R The C Programming Language and wanted to write a small program to count the occurrence of each word in the input (std-input - I piped a file with all shakespeare pieces in there). Since I wanted to learn how to split source files into multiple files with this project I pretty much outsources every f...
I have a function that generates a URL using a stringbuilder: internal String GenerateUrl() { StringBuilder urlBuilder = new StringBuilder("http://"); urlBuilder.Append(IpAddress); urlBuilder.Append("/set.cmd?" + "user=" + Username + "+"); urlBuilder.Append("pass=" + Password + "...
I have written a class that connects to a database using MySQLi and has methods for the connection itself and returns the instance of the MySQLi class. This works, but feels a little "clunky" and can be a bit slow, can someone help me to improve this? The class is as follows: <?php /** * Connect to a db. */ class m...
Loosely basing myself on this blog post, I implemented an ordered dictionary. In essence, it's a wrapper struct for a list of tuples with some initialisers and some functions (map, filter, toArray, ...) added to it. struct OrderedDictionary<KeyType: Hashable, ValueType>: SequenceType { typealias KeyValueType = (key...
I'm currently trying to teach myself JavaScript. If someone could critique my implementation of Pascal's Triangle I would be very grateful. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Pascal's Triangle</title> <style> .container { displ...
After reviewing many Tic-Tac-Toe implementations, I decided to write my own. Here it is: Logic.hs module Logic ( Symbol(..) , Space , Board , Position , GameResult(..) , GameState , placeSymbolAt , isFree , gameResult , initialState , makeTurn ) where import Data.Maybe (isNothing, isJust) import Data.List (find, trans...
I want to calculate all the prime factors of a number in the range 2 ≤ N ≤ 107. Here is my function: public static long cal_me(int a, long[] A){ long ans=1; int count=0; while(a%2==0){ a/=2; count++; } if(count!=0) // I am calculating value which depend on Number of prime Num...
I've made a login page using Python Flask which works with MySQL. I started learning Flask 2 days ago and it was fun, so I came up with this: from flask import Flask, session, redirect, url_for, escape, request, render_template from hashlib import md5 import MySQLdb app = Flask(__name__) ####################### # D...
Background: You have an eCommerce order of 10 products but you want to refund only 5 of them. The stock managing system needs to preserve the order of row number (orderline) when you do the returns, but don't send the items that are not refunded. The order looks like this: "Poduct1" Orderline ="1" "Poduct2" Orderline =...
I'd like to eliminate the code duplication in the following two methods by moving the common code into a separate method callable by both. The comments indicate the blocks of code that have a differing implementation in each method. def compute_totals_h(self, size, bad_codes): with open(self._in_file_path, self._FI...
I wanted a reusable class for generating a list of primes till some arbitrary (but reasonable) limit. So, I wrote a class Primes that implements the Sieve of Eratosthenes and another method that makes use of this sieve. The implementation is done on the basis of clarity and swiftly obtaining results. I admit that using...
I wanted to get into C#, so I tried making a simple game. My first language was Java, so it was pretty easy to get the hang of C#. I know that there are multiple other posts of Tic Tac Toe games, but I want some critique on my own code. Is there any cleaner way? Any redundant code? Parts that I can jam together? using...
public byte[] PackToZip(IEnumerable<byte[]> files) { using (var archiveStream = new MemoryStream()) { using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create)) { foreach (var file in files) { var entryName =...
I spent far too much time trying to simply get data from an Xbox controller with Python. This is the cleaned up result, classified. This requires xinput1_3 or possibly 1_4 - I'm running Windows 7 and cannot use 1_4. import ctypes import threading import time xinput = ctypes.windll.xinput1_3 class controller_manager(): ...
This is the first AJAX website I constructed. I am trying to have information generated according to the name that user types in. It works well but I have some problem with the slow performance. Is there anything I can do to improve the performance of this code please? HTML: <body background = "http://starecat.c...
I wanted to write an add function that implemented currying in JavaScript. I welcome criticism and suggestions for improvement. function add(...args1) { if(!args1.length) { return sum(args1); } return (...args2) => { if(!args2.length) { return sum(args1.concat(args2)); } return add.apply(n...
I have a 2 dimension matrix : public struct Matrix2D { private double[,] matrix; public Matrix2D(double[,] matrix) { if (matrix == null) throw new ArgumentNullException(nameof(matrix)); this.matrix = matrix; } private double[,] Matrix => matrix ?? (matrix = new double[0, 0]); ...
I have created an auto-typer that runs through a simple little GUI.This was my first ever Java program so it's pretty simple and not anything special, but I'm curious to know if there's anything that I could have done better. import java.awt.*; import javax.swing.*; import java.awt.event.*; public class AutoTyper{ ...
I need to filter Turkish words according to vovel alternation rules. For example -ler is plural but can have form of -lar thus I use metaphonemes for these transitive allomorphs as vovel_dict in my algorithm. There is only one condition not to alternate vovel it's 'ken' which excluded. I wrote this but it takes too muc...
This is a trivial problem. The reason I'm here is to get a better idea of how to use Java's numerous APIs for working with files, folders, and paths. I'm hoping this specific example will help. Problem Statement I want to rename a file like this: /path/to/myFile.txt to this: /path/to/myFile_old.txt Ugly Solution I'...
What is the most Pythonic way to take a dict of lists and produce a new dict with the list items as keys and the previous dict's keys as list items. Here's a visual explanation: favorite_fruits = {"alice": {"apple", "orange"}, "bob": {"apple"}, "carol": {"orange"}} people_by_fruit = {"orange": {"carol", "alice"}, "appl...
For school I had to do a real simple login and authentication system on an Android app, and I'm wondering how my code can be optimised to reduce code duplication and how it can be made more object oriented? All the app does is make an API call to my SLIM restful web service using AsyncHttpClient library and stores the ...
The concept is very, very simple: let's do merging run by run (a run is a range without decrement). template <class RandomIt> void RunAwareMergeSort(RandomIt first, RandomIt last) { RandomIt m_first(first); // the begin of first run of merge RandomIt i(first); // the locater while (true) { while (++...
Any feedback on my code would be greatly appreciated. /* The Sieve of Eratosthenes using a javascript array as an associative data structure. */ function range(start, limit, step) { var rangeArray = []; for (var i = start; i < limit; i += step) rangeArray.push(i); return rangeArray; } funct...
I want to count email addresses with different status. I use ASP.NET MVC and this query is supposed to run every 5 minutes on these tables, which every table is on different .ndf files. About 5 million records will be inserted into email address table every day. Is this query good enough, in terms of performance? You c...
I am on the learning curve of C and its capabilities. Below I have tried to create 4 individual programs where the execution is always in order (program 0,1,2,3). About the program Program #0 is always executed (called) first, it also creates semid's Program #1 can ONLY be executed if Program #0 has ran Program #2 c...
I'm developing a php framework called Stack. I just created the autoload.php as follows. <?php namespace Stack\Application; define('ROOT', __DIR__); class AutoLoader { private static $pos = false; private static $namespace_path = NULL; private static $namespace_name = NULL; private static $file = NULL;...
(define loop (lambda (x proc) (when (not (= x 0)) (eval proc) (loop (- x 1) proc)))) Is this the best way to create a loop function in Scheme?
I made a fizzbuzz program in Java 7 I'd like reviewed. Given an input file with three numbers in each line, fizz, buzz, and count: 3 5 10 2 7 15 The output, for each line, should be the numbers from 1 to count, except that multiples of fizz are replaced with "F", multiples of buzz are replaced by "B", and multiples of...
What it does is simple: the user inputs a from- and a to-value in a field, sets it with ok. With the go-button, the user makes the program count from f to t and adds it to the site. With delete, the user clears the added markup. I feel I could simplify the two set-functions into one, but I'm quite stuck. $(document)....
I do need to use jQuery autocomplete for two inputs. But I have use same processing script for these two elements. At this stage I am doing it like this: $("#suburb").autocomplete({ source: function(request, response) { $.ajax({ url: "includes/state_au_ajax.php", dataType: "json...
When searching for information about the Binary Tree, the code on people's blogs are complicated, so here I'm trying to code a very simple Binary Tree. Am I missing anything? Is there a better way I could be implementing the BinTree::Remove? #ifndef _BINTREE_H__ #define _BINTREE_H__ using namespace std; class BinTree{...
I coded this function to check for a violation of a primary key in a DataTable. The main idea is to retrieve a list of every row that the same value of the column in input and set an error to it. Private Sub PrimaryKeyCheck(Of ColumnType)(dt As DataTable, ColumnName As String) Dim violatingGroups = dt.AsEn...
I built this wrapper over the System.Security.Cryptography.Aes encryption/decryption so that one need only instance the class and call the appropriate methods. This makes it much simpler to work with AES encryption so that developers don't need to reuse the same AES code everywhere they need encryption. Any and all com...
I want to create a JS MVVM framework for learning and personal project. jsFiddle HTML: <input type="text" mk="value=test" value="test" /> <br /> <span mk="text=test"></span> JS (markjs): (function () { Mark = {}; var mark = { text: {}, value: {} }; Mark.set = function (name, value) {...
I have written a CFG (text file) parser for my specific needs. I have found other libraries to be much too large. Even other parsers that bill themselves as "simple" run hundreds of line long. The code that I need reviewed is the parsing and tokenizing of the input. I feel like it can be simplified. I have added more ...
I have a Morse Code translator, which can translate text to Morse code and vice-versa. Note that for the two files that the first three lines are generated by the Code::Blocks IDE. translator.h #ifndef SPLIT_H_INCLUDED #define SPLIT_H_INCLUDED #endif // SPLIT_H_INCLUDED #include <iostream> #include <map> #include <str...
Often I need to perform multiple assignment from a sequence (e.g. from the result of a split()) but with some semantics that, AFAIK, are not available in the language: Assign N first elements and silently ignore the rest (like Perl's list assignment). >>> a, b = 'foo bar is here'.split() >>> a, b ('foo', 'bar') >>> A...
I'm trying to design a multithreaded daemon for an industrial automation related project. The daemon will be using a number of 3rd party libs like MQTT, mysql, etc.. My idea is to have worker threads (or callbacks registered with these 3rd party libs) relay events to the main thread using a global mutex and conditional...
Already read this, but OP is using some other method. My website finds the time till new year. But this website claims to be accurate to the tenth of a second. So what I found out was my timer and their timer is off by about a minute. var daysSpan = document.getElementById("days"); var hoursSpan = document.getElementB...
This is my first Rails project. I have read about concerns which are a great tool, but I am confused about how I should redesign my models. Some models have similar fields, but the validations are not the same everywhere. For example: 3 models have a phone field, but in one model the phone field is not required. 3 mod...
I'm writing a program to help with remembering complex bash commands. On invoking the program, it asks for a description of the desired operation, e.g., "increase volume" or "find orphaned packages", and displays the commands matching the input ordered by closest match. Matching is determined by splitting the command t...
This is my first time writing C++, so I would appreciate advice in the areas of: Code style (naming conventions, indentation, etc) Memory usage (am I performing unnecessary object copies?) Class design (move constructors, destructors, etc, are they necessary?) Correct usage of standard library functions (especially th...
I've written a Java class that will provide the utility of, in essence, hashing user passwords for an Android app that integrates Couchbase mobile into it, and then, checking whether or not the hashing of the password string entered by the user matches the hash stored in the DB to grant access. Does there appear to be ...
I have a structure that is organized much like a Sudoku board, where individual cells reside in an n x n region, and those regions reside in an n x n area. I need to be able to address both the regions and the individual cells within the regions separately. When operating on every individual cell (in a particular order...
I have created an Insertion Sort code that sorts numbers (obviously). #include <iostream> #include <cstdlib> void insertion_sort(int arr[], int length); void print_array(int array[],int size); int main() { int array[] = {4,6,3,7,5,9,2,8,1,10}; insertion_sort(array,10); print_array(array,10); return 0;...
Problem The main idea is to build some fine scale weather data using inverse distance weighting (idw) from the 5 closest stations of the observed station. If the value in the newdat data set is greater than 134, less than -80, equal to -9999, or NA then run the function to get an interpolated value. If greater than 2 ...
I created a Python module to access Samba shares some time ago, using Mike Teos' SMB module as some kind of a base to it. It is mostly a wrapper, but as I said, I wrote it some time ago and would appreciate feedback on readability, usability and modularity of this module. ServerAccess.py #!/usr/bin/env python2 # -*- co...
I'm doing this small Breakout clone for school, and I've looked at heaps of people's takes on Breakout and tried to combine bits and pieces that I liked. Only problem that I'm having is getting the game to end when the ball hits the bottom window edge and sounds. You should be able to copy/paste the code into a projec...
For some purposes it can be highly desirable to use GetSystemTimePreciseAsFileTime() whenever it is available (i.e. Windows 8+) because the accuracy of GetSystemTimeAsFileTime() isn't very high and it varies from system to system. On old systems it's tied to the 15.625 ms heartbeat, but even the 1 ms of newer systems i...
I want to get the key from value / and value from key ,can anyone help to do in better way ? or can we implement the below code using java enum or spring or apache enumutils or java generic ? Note : I used to get string from frond end(.jsp) and I want to store store this value into database table as integer. Frond end ...
I am working on an app that will interact with assembly (app) versions. I created a struct for that, along with an exception for parsing error. Here's the code: [Serializable] public class VersionParseException : Exception { public VersionParseException() { } public VersionParseExce...
The data (news items) comes from a <ul>. I'm using setInterval and setTimeout for the timing aspects, and jQuery animate for the movement to the right. I know that setInterval and setTimeout start acting weirdly when the tab is not active, but that's not a problem for my specific use-case. I'm looking for any comments...
Some exercise required me to write a piece of code to double every second item in a list. My first thought was just using cons and I came up with the following: doubleSecond :: Num a => [a] -> [a] doubleSecond [] = [] doubleSecond [x] = [x] doubleSecond (x:y:xs) = x : (y * 2) : doubleSecond xs While it's straightforwa...
This is not ordinary question but it's also not opinion-based, it's more about the standards and the right way of writing JS code. I admit, I'm a total noob in JavaScript, I do not have experience with this language but since it is necessary for the project I'm working on - I had no other choice but to learn a bit abou...
My code takes input from the user and creates a receipt with the information the program receives from the user: import easygui items = [] prices = [] amount = [] amounts = 0 finished = False total_price = 0.00 list_num = -1 def take_item(): global list_num, amounts, finished item = easygui.enterbox("What it...
I created a simple Java program to calculate Goldbach's conjecture and I was wondering how I could improve it (besides using clearer prompt messages). /* Title: Goldbach Conjecture * Author: Harris R */ import java.util.Scanner; public class Goldbach { public static void main(String[] args) { Scanner scan =...