instruction
stringlengths
71
71.9k
I have a big (50k*150k) matrix with co-occurrences of nouns (rows) and adjectives (columns). As most nouns don't co-occurr with most adjectives, this matrix is very sparse, >99.9%, so I'm using the CSR format. For every pair of nouns I need to calculate the Jason-Shannon Divergence to asses how similar the co-occurrenc...
I'm writing a function to reverse a number in Ruby. IE, 314159.reverse should return 951413. Here's what I have, which works: class Numeric def reverse str = self.to_s.reverse if self.is_a?(Float) return str.to_f elsif self.is_a?(Integer) return str.to_i end end end I don't like the en...
I have a legacy system with a class with a lot of data. I am creating a web service that inserts a new claimant into that system for a contractor. I can not refactor the claimant object. I need help on how to refactor my tests. I would never leave this as is but I wanted you to have the raw code to speculate about. Cur...
I've been using Ruby for about a year now, mostly for small scripts with uses ranging from data munging to DevOps tasks. However, I am not intimately familiar with OOP (I appreciate the functional programming approach I'm often able to take with Ruby) and so I think my code is harder to read and debug than it could be....
This PHP class is to allow user to enter a URL of a remote image file and have it download the image to local server. It will be used in a Markdown editor just like Stack Overflow / Stack Exchange uses for their Markdown editor image dialog. To make it more reliable across different server configurations, since my cod...
I've created a JavaScript image slideshow, using only JavaScript (no jQuery). I want to become more familiar with JavaScript, which is why I didn't use jQuery. My four requirements were: It must work if JavaScript is disabled. It must be responsive. It cannot use jQuery. It must work in IE 8. The code works - I'm ju...
Here is the Assignment instructions: Create a Java class named HeadPhone to represent a headphone set. The class contains: Three constants named LOW, MEDIUM and HIGH with values of 1, 2 and 3 to denote the headphone volume. A private int data field named volume that specifies the volume of the headphone. The defaul...
This code will determine if three numbers are consecutive for any order they're supplied to the method (any permutation of [n, n+1, n+2] should be accepted). Is there any way to make this code easier for me to write, or make the code more efficient? Any feedback would be most welcome! I tried testing with 3! combinati...
I'm implementing a plus method that should work this way: 1 plus 2 // 3 "a" plus "b" // "a and b = ab" Here is my implementation: object MyMath { implicit class MyMath(a: Any) { def plus(b: Any) = { (a, b) match { case (s: String, s2: String) => s"$s and $s2" case(i: Int, i2: Int) =...
I'm practicing for technical interviews and I'm looking for ways to improve my answers/code. Please point out the flaws you see and how I can make this better. Task: Find pairs in an integer array whose sum is equal to 10 (bonus: do it in linear time) Pairs.java //Container class that will hold the indices of the pa...
This question was recently asked: Determining if three numbers are consecutive It intrigued me, even though it was broken. I have the following implementation I thought would be interesting, and I am looking for reviews on readability, usability, and for any edge cases it may miss, etc. /** * Determine whether three <...
The function should get some text on input and return a map in a following format: ("word1" -> 1, "word2" -> 2 ...) The keys are words from text and the values are representing the number of times the word appeared in the text. We take into a count only words which at least 4 characters long. Special chars are ignored...
The following code and test data works, but I have had to add delays between writes to MySQL otherwise it acts funny (especially on the target data set which is over 700 rows). The table is simply a number and value (the number is another table's 'foreign key(?)'. I am looking for suggestions on how I might reorganize...
I am completely re-writing the textbox GUI widget. In order to set the position cursor after the last character in the last line of a text, it is good if you know the exact column of it. So I created a small function that calculates this. It is meant to work sonicly. int get_last_line_length (char *string) { const ...
I was translating a script I had that would automate linear cryptanalysis of SP networks from Python to C++. For those who aren't familiar with cryptography, linear cryptanalysis involves finding relationships between certain input and output bits of a \$1 \rightarrow 1\$ array. What I'm doing is looping over all possi...
Either out of boredom, or my odd fascination with LINQ and SQL, this, thing, was created. Essentially, it provides list querying capabilities. At the moment, you can only query lists based on conditions, and sort them. Here's the source. py_listq.py import operator as oper class QueryableListCondition: """ A ...
I'm new to C programming and I recently challenged myself to writing a Tic-Tac-Toe program. I found that my code becomes lengthy very quickly with so many if statements. This code works as is (and I still wish to add more features). I just think there's probably a more neat/efficient way to program this. Any ideas on h...
I was inspired by this question from @AndyRoid to try and come up with some fast and accurate datetime calculations that didn't involve complex if/else statements. My hammer tool of choice was MySQL, because of its simple syntax and very common use on the web. This could easily be adapted to other DBMS, though. So, I...
The below code is working correctly, however, I am not sure if the combination of while, foreach and implode is really necessary here or if the same can be achieved much simpler. What I do here is fetching some data (text) from a db and the only thing I need is the results as a comma separated string. Now even though t...
In this program, the parent process creates a child process, then the child executes ls -l. The parent process waits for the child process to complete and then returns using return 0;. /*child's output redirected to file*/ /*sps, 6262015*/ /*Headers*/ #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<s...
I've been writing a program that accepts an integer as input and displays the number Pi rounded to that number. The only issue I see is the fact that the Math.Round method can only round up to 15 spaces and there's no try-catch for that ArgumentOutOfRange exception. I'm also not sure how safe it is letting your flow of...
I'm new to JS and trying to improve my code with the use of more organised objects. I have the following procedural code which I have converted to an object. It does an ajax load within main. Aside from grouping the methods (functions) for better organisation, what other advantages does this approach have? Is there a...
I want to read a list of elements and pass a maximum of 99 elements to a function for some logical operations. I have tried this with an array as an example and this code was successful in achieving my purpose. I just want someone to review it and help optimize it. /** */ package com.review.code.java; /** * i> Re...
I'm using Winforms and I find this pattern showing up in my code a lot. It works, but I'm unsure if it's best. The goal is to pass an IList of items through a view interface and then bind that list to a DataGridView in the concrete GUI class. I've been accomplishing this by keeping a private BindingList<T> in the contr...
I'd highly appreciate it if you can: Spot flaws, especially bad practices and suggest a possible alternative method. Spot inefficiencies and suggest how to perform that task efficiently. You may review my HTML/CSS as well. var addRecordFormVisibility = false; var addRecordForm = document.getElementById('addRecord')...
The code will ask for a directory and will then read the CSV file and then generate a file in that directory describing a social network for Pajek. Does anyone know a way to load this CSV file to a Pajek file faster in Java? Here's the csv file i want to load to a Pajek file. It contains 72180 lines, and looks like: ...
I wrote this code to check an internet connection and was wondering if this is the best way to do this check. public static boolean isNetworkAvailable(Context context) { boolean status = false; try { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECT...
Working on my SQL project at last. The concept is easy to use and integrate SQL into C++. ThorsSQL::Connection mysql("mysql://host", "username", "password", "databaseName"); ThorsSQL::Statement bigEarnerStat(mysql, "SELECT ID, Name, Salary FROM Employee WHERE S...
I'm using AngularJS and I have a watch task in my controller that needs to be dried up if possible. Basically it watches for state changes in my front end. I have 3 buttons: add, edit, and delete which will toggle these states. I only want one to be active at once. My buttons: <button ng-click="actions.add === false ? ...
Part 2: (Part 1) Working on my SQL project at last. The concept is easy to use and integrate SQL into C++. ThorsSQL::Connection mysql("mysql://host", "username", "password", "databaseName"); ThorsSQL::Statement bigEarnerStat(mysql, "SELECT ID, Name, Salary FROM...
I'm interested in recursive generation of trees in Python. For my eventual application, it's important that the trees be represented as a list of nodes (rather than say a dictionary, or an edge list, or some other format). Also, in my eventual application, each node of the tree will have between 0 and hundreds of chi...
I wrote my first Ruby gem, which is for testing code in the shortest way possible. Here's a usage example: require 'arrow_test' 1 + 1 # -> 3 arrow_test The code (including RDoc documentation): # Performs the logic of the arrow test. # # Example: # >> helper_arrow_test(["", "1+1 #-> 3"]) # => ["ERROR:\n ...
This method randomly increments or decrements (with equal probability) until either -3 or 3 are reached. I'd like to maintain printing the value of pos on each iteration, and printing the largest positive number max reached at the end of the loop. How can I improve this method using the Random() function? I know this s...
file = open("Speeders.txt", "w") import random, string, time Speeders = [] #Array while True: try: Distance = float(input("Enter a known distance.(Metres ONLY)")) break except ValueError: #Allows ONLY numbers to be inputted, anything else is rejected print ("Invalid input (Numbers ONLY)...
I would like to split a string on multiple conditions such as: After each /;/ After each /{/ or /}/ After each /\w+:/ but not after /\w+:\s+\{/ After each /#\w.*$/ I've found that I can keep a pattern and split before it with /(?=pattern)/ or split after it (if the pattern has a fixed width) /(?<=pattern)/ or split...
How can I improve this code for a dynamic and re-sizable array data structure? Array.h #ifndef _ARRAY_H_ #define _ARRAY_H_ class Array { private: int * m_ArrayContainer;//These two variables int m_Size; //work in pairs. private: void SetSize(int size); void AllocateMemoryOfSize(int siz...
This is one of tasks, which I had to do for the recruitment process at some company. Unfortunately they didn't like it so I've decided to share it here for discussion. CircleArea.h #ifndef CIRCLEAREA_H_ #define CIRCLEAREA_H_ //PI Number, with max precision for double (8 bytes) const double PI = 3.141592653589793115997...
I was writing a game in Swift and Sprite Kit and it is very simple. It works perfectly other than the fact that it gets a bit laggy sometimes. I'd like to use this experience as both a learning tool, and to get the 'lagginess' resolved. My code is relatively short, actually: import SpriteKit import UIKit import Foundat...
These are two of tasks, which I had to do for the recruitment process to be started in some company. Unfortunately they didn't like it so I've decided to share it here for discussion. Add up all the even elements of the Fibonacci sequence below 1000. In my solution it is a method fibSumEven. Write a recursive function...
I'm learning Rust, from a Python background, and while I've used languages like C and C++ in the (distant) past, system languages aren't really my specialty. I would just like to know if my code is sane, if I seem to have the principles roughly right, but I'd be happy to hear any improvements at all, particularly with ...
This is one of tasks, which I had to do for the recruitment process to be started in some company. Unfortunately they didn't like it so I've decided to share it here for discussion. Philo5.h #ifndef PHILO5_H_ #define PHILO5_H_ //Number of philosophers const int PHIL_COUNT = 5; //How many times each philosopher will e...
I am in the process of writing networking code for PHP that is meant to be used in long-running PHP processes. I realize that PHP is supposedly not well suited for long-running processes, however that is not my question, and I already am well aware of the implications. This is meant as an OOP learning exercise for th...
I am trying to calculate the sum of the smallest prime factors of n, where 2 < n < 10**12, and get the remainder of this sum when divided by 10**9: require 'prime' puts "Started at #{Time.now}." num = 10**12 sum = 0 (2..num).each { |n| sum += n.prime_division[0][0] } sum = sum % 10**9 p sum puts "Finished at #{Time.now...
Please give me some feedback on how I could make it better or simpler. public class BinarySearchTree { private static TreeNode root; public static void main(String args[]) { BinarySearchTree bst = new BinarySearchTree(); root = bst.addItem(root, 10); bst.addItem(root, 2); bst.a...
This is a calendar to layout an array of events/classes (from an API) in calendar format: Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday time event | event | event | event | event | event | event time event | event | event | event | event | event | event tim...
I wrote up a script a while back to let me play around with fractals. The idea was to have direct access to the script that creates the fractal. None of that close, edit, then run hassle; just edit then run. renderscript.py contains the GUI: import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveas...
I am new to programming. I saw this Java code with a lot of if-else statements that is copied below. People say that such a code is called 'smelly code', so I wrote my own version of the code below. Can anyone guide me with any improvements to the program (related to style, programming, formatting or anything else)? pa...
My converter converts all CSV files in the subfolders of folders 1, 2 & 3 into Excel workbooks. As of now, I am converting using codes for each folders. I previously tried to combine those into one using for loop, but an error occurred, so I've rolled back to the working code I had before the loop. Can anyone show me h...
I am fairly new to bash (I have about 3 months of experience), and now I've written my first real application (sort of). It's a function inside of ~/.bash_profile, but it has an installer. It is called loginfo and it keeps track of when the terminal was used by the user, and allows them to view this data. It comes with...
I basically have a folder view structure, that each time I call grabs the value of the selected field and gets that specific folder data. I was wondering if there's a better way to do this by caching or something like that. So for example if I was to request that same folder it would be stored in memory, instead of hav...
For an assignment I had to create a highly multi-threaded scoreboard for a multi level game. So every time a user adds a score if the level doesn't exist, it gets created ad-hoc. Important point: a user CANNOT appear twice in the 15 best score. No database or disk persistence was permitted (so everything in memory). Th...
I would like to know if my current jQuery code could be improved? If yes, can you give me improvements? $(document).ready(function($) { $("#bannerPickerToggleIcon").click(function(e) { e.preventDefault(); $("#bannerPicker").slideToggle(); $("this").css({"display": "block"}); $("#...
I implemented a hash table for Coursera's Algorithms and Design class. I am looking for feedback on coding style and other improvements. I want to practice C++ coding but I see myself drifting to C and functional programming a lot. Any advice on switching would be very helpful. The problem is as follows: Given a list ...
So I have committed to making a German translation for the guys over at Rubberduck, which is localized via .resx files. Now these files are basically XML-Files with a certain, rather simple document structure: <root> <!-- Snip --> <data name="Resource_Key"> <value>Resource Value</value> </data> <!-- ...
I have an algorithm that is painfully slow if I use 'pure' mutexes. That's because most of the critical sections are short and far shorter than the work to sleep a thread. However, it is also slower to allow the occasional long critical section cause long spins in other thread(s). This class is intended to provide a ba...
I recently started re-factoring a project I hadn't touched in many months. The original purpose was to be an inventory management system for a game I played, Ogame. In this game you play inside a universe filled with galaxies, which are filled with systems, which are filled with planets. Those planets have a coordinate...
I'm working on a script to backup S3 to GC everyday. I'm not sure if my script has any potential bug or error that might have destroyed anything from both sides? The data is quite sensitive and I don't want to mess it up. Anything is welcomed. #!/bin/sh if hash aws 2>/dev/null; then echo 'awscli is installed.' el...
I'm working on some testing project. For some reason I think I'm doing something wrong with the architecture. I have a simple example to show what I mean. Database class Imports DAO Imports System.Data.SqlClient Public Class PatientDB Dim connectionString As String = "Data Source=GSABBOZMAINPC;Initial Catalog=Tes...
In my task I have to pass some data from one model to another, where each model contains lists: List<VisualProcess> vProcesses = new ArrayList<VisualProcess>(); for (Process process : processList) { VisualProcess vProcess = new VisualProcess(); vProcess.setId(process.getId()); ...
I'm trying to create a "perfect" generic solution structure for MVC (5.2.3.0) projects using MEF. Currently my solution looks like this. Core layer contains generic classes that could be used in any project Data layer contains a ApplicationContext (: DbContext) and models Repositories layer contains Repository classe...
This is practically my first time using async in my code. I read about dos-and-donts but I wanted to get some feedback on what I've written. I'm using a repository pattern and I'm inserting asynchronously into the database. An explanation of the models involved: I have one DomainModel and three tblModels (tblModel1, tb...
I am trying to implement lock by which I want to avoid reads from happening whenever I am doing a write. My requirements are: Reads block until all three maps have been set for the first time. Now second time, If I am updating the maps, I can still return all the three old maps value(before the updates are done on all...
If I have a one liner method that looks like this: str.toLowerCase.replaceAll("[^\\w']", " ").split(" ").filter(word => word.trim.length >= 1).groupBy(word => word).mapValues(_.size) What is the best way to avoid long lines of code and split it into multiple lines? Here are the options that I see: Assign part of the ...
For an assignment, I wrote a minimal HashTable implementation (it only supports additions; no deletions). To resolve collisions, it uses Linear Probing (required by the assignment). I'm looking for general feedback regarding style, practice, and these things specifically: I've gotten out of the habit of using null to ...
As my question Modular arithmetic was hard to review and terribly long, I've added a few comments to the easier part, namely IntModulus. The code uses Guava and Lombok. As usual, feel free to ignore my slightly deviating coding conventions. My concerns are speed and correctness. The whole code including the test can be...
My assignment was to make a "Lending Library" that keeps track of items. We were advised to create two classes and a main method. What I am unsure of is if any of my code would be considered bad practice or unnecessary, especially when it comes to declaring objects and instantiating classes. Also, our professor sugge...
This is my first time writing a Swing+Groovy application that successfully inserts data to SQL tables. It may look like example code, but it is more test code, as I will eventually expand this to a much bigger application, and would like to see if I can improve it before expanding it. What it does when you run it is b...
I've implemented the beginnings of a Python preprocesser I plan to implement sometime in the future, and the below code is my simple prototype. At the moment, it only converts until and unless statements. py_preproc.py """ A simple Python utility that converts non-valid Python code, like `until`, and `unless` blocks to...
I was trying to find out if a string contained a capitalized letter and if it did I wanted to know the position of the character and its ASCII code. I might have refactored a little to much. Given an input such as: (is-capitalized "Meow mEow kItus kaTus") My function returns: ((18 . 84) (11 . 73) (6 . 69) (0 . 7...
I have implemented a heap data structure for Coursera's algorithms course. The problem I have to solve is: The goal of this problem is to implement the "Median Maintenance" algorithm. The text file contains a list of the integers from 1 to 10000 in unsorted order; you should treat this as a stream of numbers, ar...
This was a very fun and thought provoking problem, and I'm quite proud of the way I was able to pull it off. I broke it down into 2 parts, testing and comparing. Testing each group of cards for a playable hand. This returns a boolean value depending on if the cards meet the criteria for the hand. A set of cards may...
I copy addresses from the endpoints to an array that should only hold the endpoint addresses. This works but it seems so old school :/ Can I make this faster, better, more sexy (LINQ)? public static EndpointAddress[] Find() { EndpointAddress[] endpointAddresses = null; var discoveryClient = new DiscoveryClient...
I'm a fairly new developer (well, engineer really, but currently working on a software project). In the Android project I'm working on, I read a node representation of a map into my app and interpret the tab-separated information as Node objects (defined below) which are then inserted into a Map<Integer, Node>. Among t...
I created a post carousel (it's being used on a WordPress theme initially), but I've adapted it to just HTML/CSS/JS one. CodePen var $carousel = $('.post_excerpt_carousel'); $carousel.each(function(){ var $this = $(this); var outer_width = $(window).outerWidth(); var container_width; if (outer_width...
I have a class that I'm trying to determine a good name for. I don't know if this concept comes up a lot in programming or not, but I'm wondering if I can get some suggestions for a good name for the class. Basically, this is how the class functions: The first time its Get() method is called, it returns value A. Every...
This is an Enigma Machine Simulator written in Java: Enigma.java package enigma; import java.io.*; import java.awt.*; import java.awt.event.*; import java.io.IOException; import enigma.rotor.LargeRotor; import enigma.rotor.MedRotor; import enigma.rotor.SmallRotor; public class Enigma extends Frame { String FileEx...
I have some working code, but it seems a bit clunky. I need to get data from a service. The service will hold the data in local storage if possible (to make it speedier), but if it's not been accessed before, it will need an http GET to a web server. The example contains only one GET, but there could be many in the fut...
I am just trying to rewrite hours; say 1:24PM, if 24 > 30 then it is 2PM, otherwise it is 1PM. I really doubt that I am doing it right, first I am sure it looks so amateur, second I am not sure if it is optimised. Can you provide me a better approach to this? hours = ["3:42am", "6:37pm", "1:24pm", "2:11am", "8:30am", "...
I have a scenario to design a class structure to creates different types of derived class objects and set some of their common base class properties. Here is the final pattern I came up with to solve the problem. Can someone please take a look and advise if this a good design or can it be improved? The domain model's C...
I had posted this previously as part of Generic container similar supporting PeekMax, PeekMin, Sum, and PeekNextToMax but I think it was to big a morsel for people to chew on. So I'm splitting it up. As part of another project (involving portfolio optimization) I'm using an algorithm that requires a data structure supp...
I have written up a data structure in Java that supports the following features: get(i) set(i, e) add(e) remove(e) contains(e) size Elements must remain in order and iteration needs to be as fast as possible. The code does not require thread safety. I am looking for ways to improve the speed further. It is critical t...
I'm replaced character strings with numeric codes in R. I find myself doing a lot of copying and pasting, so there's probably a better solution with apply, sapply, or ddply that I'm missing. Here's an example: example <- data.frame(matrix(nrow = 20, ncol = 20)) example[,1] <- 30:49 example[,10] <- 10:29 example[,2] ...
I've recently started teaching myself Python but have no prior programming experience or formal training. I've successfully created a program that outputs what I wanted it to output, but I'm looking for guidance on design/efficiency. Is there an overall design that would have been more efficient? Any pieces of code tha...
[update: keeping this around for posterity, but we ultimately went to a pub/sub pattern, using Amplify.js. Amplify isn't strictly necessary to implement pub/sub, but it has some nice features and syntax] I have a REST API, which naturally you can just use HTTP calls (mainly Ajax) in order to send and receive data. I a...
This function arguably has little use as it's so simple, but I'm writing a web application with a lot of SQL statements littered all over the place and I thought this function might reduce code duplication and improve readability. I'm wondering if what I'm doing is a good idea, what the "best practice" is here, and any...
Some of my functions use a "fail_silently" flag. It is used in the following way: def test(a, b, c=1, fail_silently = False) try: return int(a) + c except: if fail_silently: return None raise Therefore, if there is an error, we catch it and fail gracefully. The key here is tha...
I have some very illogical jQuery code and I want to see if someone finds a better way to do the exact same thing: jQuery: $(".col-md-3 img").hover(function() { $(this).parent().children(".search").show(); $(this).parent().children(".photo").css("opacity","0.4"); }, function(){ $(this).parent().children(".sear...
I'm trying to focus on learning so I can get an entry level position and the best way for me to learn right now is to have someone review and provide areas of improvement. This project isn't entirely complete but almost. I am going to include the code for some of the classes but not all of them. Just a few button actio...
K caterpillars are eating their way through N leaves, each caterpillar falls from leaf to leaf in a unique sequence, all caterpillars start at a twig at position 0 and falls onto the leaves at position between 1 and N. Each caterpillar j has as associated jump number Aj. A caterpillar with jump number j eats ...
A different approach than this question, this time without using arithmetic progression. The README specs both sumOfMultiples and sumOfMultiplesDefault and the code passes the test suit. module SumOfMultiples (sumOfMultiples ,sumOfMultiplesDefault ) where sumOfMultiples :: [Integer] -> Integer -> Integer s...
Before I used reflection to invoke a state based on the string, it looked like this: public void setState (String state) { try { this.state = (State) Class.forName("state"+state).getConstructor().newInstance(); } catch (Exception e) { System.out.println ("Tried to set state to " + state.toString...
Given a list of tuples of the form, (a, b, c), is there a more direct or optimized for calculating the average of all the c's with PySpark? Below is what I have, but I feel like there is a more direct/optimized approach? Classic movie recommendation example, where each tuple is (userID, movieID, rating). How do we get ...
I made this really simple "attribute container" class that allows you to store arbitrary data to an object at will, sorta like in python how you can just assign attributes to arbitrary objects, but in C#. My gut is telling me it's a terrible idea, but I just want to get a group opinion. public class AttributeContainer ...
This method takes an ArrayList<String> s and int k , then creates k copies of each element. public static void copyStrings(ArrayList<String> s, int k) {         if (k <= 0) {             s.clear();         } else { int limit = s.size(); for(int i = 0; i < limit; i++) { for( int j...
Original Problem Statement Problem Analysis Task: Given a sentence, mangle each word and output the result. Clarifications: Mangling will be defined as a word with its characters in case-insensitive order. The case of the original character is preserved at the same location in the resulting mangled word (e.g., ...
One of the remarks in this answer to my question concerning IntModulus says What's more problematic is that you don't have matching argument symmetry for add and subtract. You should have long versions of those. and the reason for this part missing is that I hoped to get something faster than the trivial public int a...
Question 7 from Lab 3 of Berkeley's CS61A course says: The following examples of recursive functions show some examples of common recursion mistakes. Fix them so that they work as intended. [...] def even_digits(n): """Return the percentage of digits in n that are even. >>> even_digits(23479837) # 3 / 8 0...
I am working on yet another toy project that I named SGL (for "Standard Generic Library" since it mimics some features of C++'s STL as well as a few more utilities from the C++ standard library). Since the library is not meant to be used in real code, I decided that I would have fun and tried to implement a setjmp/long...
Below is the problem taken from Berkeley's Cs61A page here Question 9: Insect Combinatorics* Consider an insect in an M by N grid. The insect starts at the bottom left corner, (0, 0), and wants to end up at the top right corner, (M-1, N-1). The insect is only capable of moving right or up. Write a function paths that ...
I implemented Luhn's algorithm explained on Wikipedia to validate a credit card number, in Bash. Does this code follow good practices? #!/bin/bash getchecknumber(){ # get the last digit of the cc number str=$1 checknum=$(echo ${str: -1}) } getrest(){ # get the rest of the numbers in the sequence str=$(echo ...