instruction
stringlengths
71
71.9k
I am working on an interview question from Amazon Software: Design an algorithm to take a list of strings as well as a single input string, and return the indices of the list which are anagrams of the input string, disregarding special characters. I was able to design the algorithm fine. What I did in psuedocode was:...
I am trying to make an additional option in my beginning calculator program, which is based on the BigDecimal class: the simultaneous solution for the entire operation by order of operations. I want to create methods by myself, however it took me a long time just to create a sketch, and for a moment I wonder if I chose...
This code is supposed to asynchronously load a queue from a generating function. #include <queue> #include <functional> #include <thread> #include <mutex> #include <condition_variable> #include <iostream> #include <stdexcept> using namespace std; template <typename Container> struct LoadAsync { LoadAsync( size_t...
I was doing Project Euler #8, which asks: The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 125406987...
I've got this Python code: import os, re def clnFile(file): inputFile = open(file, 'r') filename = file + '.tmp' outputFile = open(filename, 'w') code = inputFile.read() pattern = re.compile('\n\t') code = pattern.sub('\n', code) outputFile.write(code) inputFile.close() outputFile.c...
This is part of a growing "primitive" tools collection here on github, and is the initial use-case for the IntArray for review here. Often, when processing data, you encounter unique values that you need to use as keys in a lookup system. These keys could be anything from IP addresses, times, identifiers, etc. A standa...
Is it possible to call multiple metaboxes in Wordpress with less duplicate functions? For instance, these are my current metaboxes (3 of them, one is a checkbox and two others are text input fields): /* * STICKY POSTS * */ function add_sticky_metabox(){ add_meta_box( 'sticky_post_metabox', 'Sticky Post',...
I have an array of dates as input in the form "YYYY-mm-dd"=>category_id.0 (category_id counting from 0). $days =array ( '2014-10-15' => 49, '2014-10-16' => 49, '2014-10-17' => 49, '2014-10-18' => 0, '2014-10-19' => 0, '2014-10-20' => 0, '2014-10-21' => 0, '2014-10-22' => 0, '2014-10-23' => 0, '2014-...
I'm just playing about with Go, and am trying to solve some project euler problems to get used to it. I've created a generator function for Pythagorean triples, using a channel which returns a set of 3 integers for the sides, like so (HCF implements Euclid's algorithm for finding greatest common divisor or highest comm...
I have implemented a trie in Java and I would request you to review it and suggest improvements or new features. The code is split into 3 files. TrieNode (individual nodes in the trie) import java.util.HashMap; class TrieNode { private char value; private HashMap<Character, TrieNode> children ; public Tr...
This jQuery actually autocomplete when the onkeydown class is present and load the autocomplete with corresponding variable. This is working but I want to make it shorter. var autocomp_opt = { source: "<?php echo base_url();?>description/get_description", minLength: 1, select: function(evt, ui) { th...
I have a program which basically manages batch runs of some underlying Fortran programs, and at the end, I want to move all the related files into a different directory. At the moment, there is something along the lines of this: private void finalClean() throws Exception{ Script.move(file1, calcDir); Script.move(fi...
This is the first program I have written in Rust and I would like to know what some Rust experts think of it. I must be doing some stuff wrong, such as breaking code style, etc. The code differentiates simple expressions. Two points of interest: there are verbose Box structures everywhere, and it makes the code less re...
I am using netty to connect to multiple servers, query for an item, and aggregate the results in my Client. The code below works, but I am unsure if it is the best way of achieving my goal. Also, I'm not sure how I should be closing the futures. Could anyone provide guidance? I am using Netty 4.0.25.Final. public vo...
I am relatively new to programming and came across an if statement that I believe to be a bit verbose. I have tested my code and it appears to work without any issues, but I am wanting to know if there is a more efficient means or better shorthand of an if statement checking "day". NSDate *now = [[NSDate alloc] init]; ...
I am very inexperienced at C++. I wrote a Hash Map which uses chaining for collision resolution. I intentionally did not use smart-pointers, as the objective of this was to learn and showcase. I have tested the code and removed all bugs I came across. I am hoping to get feedback on bad practices and potential risks...
;(function update_tree(jsonml) { for(i = 1; i < jsonml.length; i++) { if(jsonml[i][0] === 'para' && typeof jsonml[i][1] === "string" && jsonml[i][1].match(/"/g)) { // some code } if(jsonml[i][0] === 'hr') { // some code } if(jsonml[i][0] === 'h2') { // some code } } })(tr...
I'm trying to create a lost password function on my site. When a user enter their email it updates 2 columns in the users table with that email called: new_password_key and new_password_requested (int, using PHP time()), I then send them a link with that password key to a page where they may change their password. It s...
Given a single start and stop, numpy.arange is a good solution for building a NumPy array of evenly spaced values. However, given an array of start and an array of stop values, I would like to build an array of concatenated evenly spaced values, and do so in C speed (no looping). Here is my current solution, though I...
I created a class TabController to handle opening and closing of tabs. It needs some data from my viewModel, so should I pass in the viewmodel via the constructor or is that overkill? It really only needs the parameters browserCollection and activeWindow, so I could just pass those two in if that's better. I'm just sta...
I've a small assignment to do: style a given HTML file with CSS. My result looks exactly as it should. But I'm not really satisfied with my style sheet. I'm sure there are better ways to achieve the same. The different sizes are not specified. I had just an image as template. How would a real web design solve this task...
The other day I was intrigued by this question (originally from here): Write a program that answers YES/NO search queries containing * placeholders. Example: if the data you have is (hazem, ahmed, moustafa, fizo), then you should answer as follows for: ahmed: YES m**stafa: YES fizoo: NO fizd: NO *****: YES **: ...
I've wanted to write a C++11 class for making IPv4 TCP connections and figured that it probably could be done with just one static function using some shared_ptr and lambda "magic". The following code seems to work - but I'm not entirely sure that it's safe and completely bug-free: void Client::connect(boost::asio::io_...
I have a series of tables and queries I run a process against and at times this process can take hours - if not multiple days - depending on the date range I select. I am running PostgreSQL 9.4. In reviewing the below queries, does it make sense to Have a temp table and/or Should I have a nested query? Is there a bet...
Have recently been writing a few puzzle solvers in Java, this is my latest attempt. It solves the "Word-Target" puzzle found in some newspapers. You may have seen it before: Words must be found by using any of the letters in the grid in any order, however each word must contain the centre letter, and must be at least ...
I have two conditions that need to traverse the same data but inside the traversal the logic changes slightly for each respective condition and in different places. If it was the same place that would be easy to factor out, but what's the best approach if it's not all in the same place for every condition? I seem to ru...
I've recently (an hour ago) started a project for making a wrapper for Imgur's API using the REST client Retrofit. I've only implemented a single endpoint so far as I'm questioning my design. While I've been programming in Java for some time now, I'm only now taking my first class in high school, so I've been kinda win...
For my CS2 project, I am supposed to implement a spell-checker. It is supposed to follow the following: Prompt the user for the name of the file containing the dictionary of correctly spelled words Read in the name of their dictionary file Open an input file stream on their filename If their filename successful...
I have a strange programming prompt. I managed to complete an algorithm to solve smaller test entries (which i'll post). One of my test cases has to complete a 200,000 int input and my algorithm isn't practical. I'll post the prompt and my algorithm. How should I go about optimizing the performance to handle large inpu...
I'm trying to develop a simple program to evaluate integral powers of a complex number \$z\$ , that is, \$z^n\$, where \$z\$ is in the algebrical form \$a+i b\$ and \$n \in \mathbb{Z} ^{*} _{+}\$. How I was trying to proceed: First, I defined a product function, and next I intended to define a exponentiation function ...
I need to read HTML files and ignore the input until reaching the following tag <a class="member-modal" then print the characters between that and the closing <div> tag. Below is the extracted line of the file of interest. <a class="member-modal" href="https://website.net/users/membercard/890520">Phil Jankins<...
This is probably silly, but I feel like there should be a much more elegant way to do this simple thing. I have two known strings, whichever one is passed in in the parameter I want to return the opposite. Current code: def matching_sub(subscription_type) if subscription_type == "maths" "reading" else "math...
I'm a beginner in MVC programming, repository, and UOW using Entity framework. I tried to calling my existing SP in my MVC project using UOW and EF. Here is my code to mapping my SP in myDbContext file: modelBuilder.Entity<Applicant>().MapToStoredProcedures( s => s.Insert( i => i.HasName("In...
This program takes scores for each student from a .txt file and calculates their averages, as well as the average for each assignment and the class overall. This program works properly, just curious if I can make it look more professional. Scores.txt 5 6 95.2 89.1 98.0 78.9 100 67 100 99.6 100 100 90.1 82.2 100 85.5 85...
I realize this is very beginner code, but I just today grasped the basic concepts of private variables, constructors, and such. I wrote this very simple class, and a class to test it. Any and all input welcome. Calculate.java import java.lang.Math.*; public class Calculate { private final double num1, num2; ...
I have a localization manager class which can change app language on the fly. It's using ReactiveCocoa and my main concern is that I'm not using some of RAC parts correctly. First (in - (void)configureSignals): + (instancetype)sharedInstance { static i2KRLMLocalizationManagerObject *sharedInstance = nil; stati...
I know there are many great plugins on the Net nowadays. But due to safety issues, external plugin are restricted. Thus, I wrote some JavaScript for an interactively searchable HTML table. The main features I need are a vertically scrollable table and interactive filtering. Since the window size is not fixed, I also ad...
The purpose of the code is to see if a form element would get data from internal react components and it did. It was also to see how clean I could make an autocomplete component. The autocomplete has 4 states and I use bind excessively (is this bad?). I also added a function updateSpecificState, because I found it inco...
I have a CLI wrapper for https://yakuake.kde.org/. Python 3.4.*. #! /usr/bin/env python # coding: utf-8 import click import subprocess def get_postfix(title): file_path = '/tmp/yakuake_{}_postfix'.format(title) try: with open(file_path, 'r') as f: postfix_number = int(f.readline()) ...
Is this a good solution for the Number to Roman Numerals Kata in Javascript? function toRomans(n) { var nString = n.toString(); var result = ""; var allLetters = [["I", "V", "X"], ["X", "L", "C"], ["C", "D", "M"], ["M"]]; var letterSet = nString.length - 1; for (var index in nString) { resul...
In order to solve a equation where the left hand side appears under an integral on the right hand side: $$ B(p^2) = C\int_0^{p^2}f_1\left(B(q^2),q^2\right)\mathrm{d}q^2 + C\int_{p^2}^{\Lambda^2} f_2\left(B(q^2),q^2\right)\mathrm{d}q^2 $$ I have written the following code to do solve this equation iteratively: import nu...
We're given a char[] containing characters A-Z. (For more characters this can easily be extended). Now we're asked to remove all duplicates in the char[]. For example, in: \$['B','A','A']\$, out \$['B','A']\$. The algorithm: public void removeDuplicates(final char[] s) { if (s == null || s.length < 2) { return; ...
I've been playing around with writing a simple static blog generator in Haskell (mostly for experience, since there's probably more than a few already made choices that fit my needs). I don't have very much experience with functional programming, but I've been doing a lot of C++ lately, so using typeclasses as "interfa...
I have this code which is working fine but I would like to use Java 8 NIO in order to optimize the code performance. public static HashMap<String, HashMap<String, Integer>> getTemp() throws IOException { HashMap<String, HashMap<String, Integer>> usageData = new HashMap<>(); File directory = new Fil...
I would like a review of the following application, esp with how I'm registering and selecting the controllers. First I defined a generic Repository interface and implementation using EF 6.1.2: public interface IRepository { Task DeleteEntity(int id); } public interface IORepository<out TEntity> : IRepository w...
I'm working on an event manager, and I am wanting it to be a tool developers use. It is lightweight and it uses annotations to register events. I've tried to set up synchronization, and I'd like to ask if I'm doing it right so far. It's on GitHub. The main class that I would worry about for synchronization would be the...
Suppose we are given a C++ vector. We want to specify a variable amount of indices and select elements from a vector being indexed. I have two implementation: (A) one relies on C++11 initializer lists, and the second one (B) on va_list and macro mess. Arrangement B is however funkier to type because it requires no typ...
I've been optimizing my code and I always tend to cache common selectors like this (jQ): function init(){ var ob = $('#ob'), fg = ob.find('.fg'); win = window, s1 = $('#s1'), s1em = s1.find('em'), bodyHtml = $('body,html'), fboxFirst = ob.find('.first'), _continue = $('#cont...
Here is an implementation of Graham Scan algorithm for computing the convex hull of a finite set of points: data Point = Point { xcoord :: Double, ycoord :: Double } deriving (Show) data Direction = ToRight | Straight | ToLeft deriving (Show, Eq) distance :: Point -> Point -> Double distance a b = sqrt (((xcoord...
I am trying to learn Socket.io and develop a multiplayer tic tac toe game. Right now, I have developed a game that plays well when hosted locally, but I cannot seem to transmit game moves between the client(s) and the server. How can I improve my game? Index.html (with client-side JS) <body> <h1 id="title">Let's Play ...
I am trying to get the scores and average for all assignments for records in a MYSQL database. The code below works but seems to take quite a bit of time to run because of the nested while loop. Any suggestions on how to combine the queries into one? $query4 ="SELECT studentsisid,coursename,learningoutcomeid,learningou...
I was recently rejected from what looked like a really promising string of interviews. I did very well in a questionnaire style review, and then they handed me this assignment (more or less): Design a coffee machine which makes different beverages based on set ingredients. The initialization of the recipes for each dr...
Based off of another SO reply by kennebec, I had problems following the code so I rewrote it to give myself a better understanding of what is being accomplished. I would be very grateful if you could critique it or point out any problems I have caused or could modify to improve it. Tested with IE8/9/10/11, FF, Chrome, ...
The code included below was written in response to a programming exercise that was sent to me by a company that I am applying to. The purpose of the code is explained at this link. This code passes 89% of all correctness tests for finding valid meeting locations as specified within the programming exercise information...
This is my second program in Python. I am aware that globals are a bad idea, but that is what I have learned so far in my course. Right now the program is doing what it's supposed to do, my only concern is that it might be too long for nothing. I'm asking you to help me figure out where I could make it simpler. import ...
A common task I often face is ordering a collection of items according to some predefined model, typically expressed as an ordered list of ranks. For example, credit agencies might rate financial products as: AAA (excellent investment) AA (very good investment) B (not so good investment) BB (poor investment) BBB (why ...
I'm working on simple a 16/24/32-bit bitmap reader for fun, however, the method I am using to go about reading the DIB header seems odd. All this does is read a simple Windows Compatible Bitmap from a file and stores it in memory. The idea here was that I wanted to auto-populate members of a struct with the correspondi...
I'm teaching myself data structures and would really appreciate some feedback on my stack implementation. A couple of things I'm not sure if I should be doing: creation of the array and pointer using new style // Implement 3 stacks with one array #include <iostream> class SingleArrayStacks{ private: ...
I need to pass some int32_t values into and later retrieve them from a local storage API that uses void* and size_t parameters. Nothing else interprets the void* values. I hand-made some simple functions to translate back and forth between the types, which work, but I wonder if anyone would care to let me know if they ...
I ran the following code through Sonar, a static analysis tool. Original file: public interface LegRepository extends CustomRepository<Leg, Long> { final String FIND_START_LEG_BY_TRANSPORTMISSION_ID = "SELECT ll.* " + "FROM T_Movement_Leg ll " + "INNER JOIN " + "(SELECT l.Transp...
I wrote some extension methods to read CSV-styled text directly into a datatable or dataset or write them to this format. Is it right to use the methods as extensions or should I create a separate class that contains this functionality, and so on? Formats explained: The ReadFromCsv and WriteToCsv will work with a norma...
I'm building a small MPL module in one of my utility libraries for fun and learning experience. One of the problems I'm trying to solve is getting a list of all indices where a sequence of types appears inside another sequence of types. Example: static_assert(is_same < List<int, char, int, int, char, int, double, ...
C code: uint32_t pcg32_random_r(pcg32_random_t* rng) { uint64_t oldstate = rng->state; rng->state = oldstate * 6364136223846793005ULL + rng->inc; uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u; uint32_t rot = oldstate >> 59u; return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); } Attemp...
I wrote a simple animation of a ball moving across the screen. I was wondering if I used the static variable correctly. If not, how could I make it non-static so I could instantiate it in the main method whilst being able to access its getter methods in the listener inner class? Also, did I use the SwingUtilities.invok...
I was learning my way on designing real world OOP problems and I was trying to solve this problem in the OOP way. The problem statement is as follows: The conference has multiple tracks each of which has a morning and afternoon session. Each session contains multiple talks. Morning sessions begin at 9am and must fini...
After reading Designing a coffee machine yesterday, I decided I could also give the same problem a try. I have used the following problem statement (copied from the given question): Design a coffee machine which makes different beverages based on set ingredients. The initialization of the recipes for each drink should...
I am building a small mobile app using ionic framework and angularJS. It will consume a Restful Web Service that requires authentication (User token). This means I need to keep my users token by myself. Could anyone tell me if there is room for improvement in my code? Specifically regarding to my "Session" service whic...
A few days ago, I've made a code to equally distribute a set of numbers and retrieve them randomly. Today, I've rewritten the code (most of it, at least). I've followed most of the advice and tried to keep it clean, but also as fast as possible. The new code has a few more comments than the last one (they were needed) ...
Given a set of values (points on a graph) find all the max/min points such that there is no max is followed by a max (i.e. the max and min points alternate) there is some minimum amount of change (C) between each max and min (.4 for this data set) the value of the minimums must be lower than the adjacent maximums He...
What this command line utility does is to take a text file and update the content a bit before turning it into Markdown. For example, the first for loop searches all the straight quotes and replace them for curly quotes. The second loop searches for hr tags and replace them for * * *, then adds the noind class to the p...
Further to my previous post for a user login script I've been learning PDO in order to migrate from mysql_* functions. As before with mysql_*, I wanted to wrap the PDO code into wrapper functions, so this is what I've done here. I've created two functions: db_connect(), which creates a connection and will be called at...
I've written the following object pool class, and because this is my first encounter with synchronization primitives, I need reinsurance from an expert that this code is safe. I've tested it myself using 100 threads on a pool with a capacity of 4, and an expansion limit of 128, it appeared to be fully functional so far...
I'm currently filtering a list based on several conditions, which may or may not be present: def requests = Request .list() .findAll { if (exportFrom) { it.tsCreated.millis >= exportFrom.millis } else { it } } .findAll { if (exportTo) { it.tsCreated.millis <= exportTo.millis } else { it } }...
I have a library with two methods: one takes an object and vararg strings, the other takes a default value as well. They are currently implemented as: export default class koalaesce { static get(base, ...steps) { return koalaesce.getDefault(base, null, ...steps); } static getOrThrow(base, ...steps...
I'm trying to improve my OOP skills in PHP. One of my projects requires me to get user info from one API and send it to another API with a different structure. I will use a simplified situation, but basically I have a big user array from one API. I need to break this into sub objects (customer and address) and serializ...
I wrote a simple calculator which uses orders of operations. I would like to know, do you see any serious flaws in logic and what do you think about this solution? It is my second approach to a problem, and the code passes tests (with integers and decimals) for basic operations: ^,|(i used this sign for root square), *...
My Goal: To efficiently move data from Amazon S3 to Amazon Redshift. Basically, I am moving all CSV files on my S3 to Redshift using the below code. I parse through part of the file, build a table structure and then use the copy command to load data into redshift. ''' Created on Feb 25, 2015 @author: Siddartha.Reddy ...
I've written a function that works however I'm sure there is a better way. I need to parse specific tags from an xml document (Microsoft Word docx document.xml). Here is the general structure of the xml in question. //A ton of crap ... <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t>Data_I_want</w...
I'm working in an application where there's a long unordered list of items that have to be paginated. New items are added to the list regularly, and the items come from a database. The only control I have is via the front end. I cannot control how they are all loaded in the DOM before page load. I was able to work this...
I'm using JavaScript to handle breakpoints in a single page, non-scrollable application. I want to do various things when changing viewports, such as fire off animations with a JavaScript animation library. I've assigned the viewports like so: CodePen HTML: <div class='box'></div> CSS: .box { width: 300px; height:...
Is this C appender safe, and reasonably optimal? #define REALLOC_BUFFER_SIZE 4096 char *append(char *orig_str, size_t *orig_str_size, const char *append_str) { // no action required if appending an empty string if (append_str[0] == 0) { return orig_str; } // does the current char* have enough ...
I can't seem to get fieldset's to react properly when using display:table and display:table-cell even if I reset the default values, it just reacts oddly in a variety of ways in different browsers/devices, so as a result I have actually removed all fieldset's and replaced them with div's. Is this a semantically accurat...
I have opened a puzzle at Programming Puzzles and Code Golf. The question is not perceived well (yet) and one of the reasons is that no reference implementation is provided. To mitigate this shortcoming, I have implemented a (non-golfed and documented) reference solution. I'd like your feedback about Correctness acco...
I wrote a class to represent a set of lights in a 2D game that raycast in order to find shadows. The draw method does a lot of calculations and takes a lot of time. Mainly, the adding of areas and clipping takes from 1 to 12 milliseconds per loop. Is there any way to speed up this method? The whole project is on Github...
This is my initial class. (I am not trying to reinvent state-flows again, just practicing) As you can see straight forward, it dynamically generates methods like .recommend,.recommend!, .recommendation_sent? class Project < ActiveRecord::Base STATUS_TRANSITIONS = { initial: :not_started, not_started: { val...
How can I simplify this code? <?php class smth { protected static $MARK_UNDEFINED = 'Undefined'; protected static $MARK_F = 'ECTS-F'; protected static $MARK_FX = 'ECTS-FX'; protected static $MARK_E = 'ECTS-E'; protected static $MARK_D = 'ECTS-D'; protected static $MARK_C = 'ECTS-C'; prot...
The following function is basically asking the user to input a file name for a file that the calling program is going to do something with. If the user enters an invalid file name, I want the program to loop back and give them another chance. The code works, but is this the proper way to accomplish this? Also, are t...
Some very common tasks that keep popping up from time time: Find the most frequent something in a collection of things ... or the count of that thing ... or both (the item and its count) Get the list of distinct items, with their counts, sorted by their counts Get the N most frequent items, with their counts To avoid...
I have a timestamp (searchTimestamp) which I need to check to see whether it is less than 10 minutes old or not: long currentTimestamp = System.currentTimeMillis(); long searchTimestamp = getTheTimestampFromURL();// this also gives me back timestamp in 13 digit (1425506040493) long difference = Math.abs(currentTimest...
I have been challenged by @nhgrif to write a Fraction class to better my understanding of OOP. I have found an interesting challenge here (I apologize that the source is not mentioned, I was not able to find it either). Problem statement: Create a class named Fraction having two integer data members named for a frac...
I'm really new to PHP, and a little less so in WordPress. I've created a working function that spits out some static HTML into a page template in WordPress. I'd like to know if there is a best practice for this, perhaps someone can help. function my_html_function() { echo '<h4>Title</h4> <ul class="ref-list...
After doing a whole bunch of research on Onion Architecture, I have made an attempt at implementing this in a new system that we are developing. We have the Layers as per below: Domain Domain.Entities Domain.Interfaces Infrastructure Infrastructure.Data Infrastructure.DependencyResolution Infrastructure.Interfaces ...
This is my RedisDataSource code. What I am mainly interested in is how the retry policy could be improved and if using WindowsAzure Trainsient Fault Handling this case (using Redis Azure Cache) makes sense. using System; using System.Threading.Tasks; using AB.Common.Helpers; using AB.SiteCaching.CacheCon...
I was recently learning about nodes and how they work in lists, and to test myself, I decided to write my own LinkedList implementation in Java. Then I decided, that since there is already a LinkedList out there, why not make it sorted? So now it is a SortedList. import java.util.Arrays; import java.util.Collection; im...
Please check this PHP script. This script is for Login authentication Some pre-defined constants to indicate the login state define('LOGIN_NOERROR',0); define('LOGIN_USER_CREDENTIALS',-1); define('LOGIN_USER_EXISTS',-2); define('LOGIN_USER_NONEXISTS',-3); define('LOGIN_PASSWORD_LINKSENT',-4); define('LOGIN_PASSWORD_BAD...
Problem statement: Create and maintain a Complete Binary Tree in C. Include the following operations. Insert a given key and perform inorder Replace ALL occurrences of the given key with the then Last Element of the Tree. Then Remove the last node. Query -> return number of occurrences of the key Size -> Given a ke...
Below is implementation 1 of data abstraction for rational number using functional paradigm written in Python: #Use def mulRational(x, y): """Violate abstraction by using other than constructor and selectors""" return Rational(getNumer(x)*getNumer(y), getDenom(x)*getDenom(y)) #x and y are abstract data def add...
I need to reduce the latency in creating a circular gradient of arbitrary radius that's then mapped to the current mouse position. Though the project uses OpenGL for video-card interaction, alas, for legacy reasons, currently uses aggdraw for drawing (with Pillow wrapping PIL). However, PySDL2 runs the rest of the UI,...
In my team at work we have traditionally used VB, starting with 6 and moving to .NET. However, other teams in the company use C#. So, armed only with Programming C# 4.0 and VS 2013, I thought I'd have a go at it. A relatively simple piece of functionality that I tend to use as a starter project to get used to a new lan...
Based on this source, I've made the following universal get / set function, to make it possible to work on OrderedDict trees for example. def nested_expand_and_get(d, keys): intermediate = d for key in keys: intermediate = intermediate.setdefault(key, d.__class__()) return intermediate def nested_...