Recent Entries 10
- pattern minor 112d agoCursor module for a text-editorA few weeks ago, I had started to write a text-editor in C++ using SFML library. The work is now paused pretty much because I am a lazy freak. So, I thought I might use this passive time to get reviews on what I have done so far. As of now, I want to get reviews on the cursor module (for displaying a blinking cursor), I wrote for the text-editor. I am posting the code as it was written and it was written without many comments. (I am not sure if I am supposed to add comments before putting it up for review on the site.) Cursor.h: ``` #ifndef CURSOR_H_INCLUDED #define CURSOR_H_INCLUDED #include #include class Cursor{ private: sf::Color color; sf::RectangleShape cursorLine; sf::Clock clock; int col, line; int txtX, txtY; int maxCol; float thickness, length; int blinkPeriod, lastTime; bool visible; public: float getCol(); float getLine(); float getLength(); float getThickness(); void move(int, int); void setPosition(int,int); void setDefaultValues(); Cursor(); Cursor(float, float, float, float, int, int, int); void draw(sf::RenderWindow *); void update(); }; #endif // CURSOR_H_INCLUDED ``` Cursor.cpp: ``` #include "Cursor.h" void Cursor::setDefaultValues(){ col = 1; line = 1; lastTime = 0; thickness = 2; length = 20; blinkPeriod = 400; visible = true; color = sf::Color(0,255,0); } Cursor::Cursor(){ setDefaultValues(); } Cursor::Cursor(float x, float y, float len, float thick, int txX, int txY, int maxCol){ setDefaultValues(); this->maxCol = maxCol; txtX = txX; txtY = txY; col = x; line = y; length = len; thickness = thick; } float Cursor::getCol(){ return col; } float Cursor::getLine(){ return line; } float Cursor::getLength(){ return length; } float Cursor::getThickness(){ return thickness; } void Cursor::move(int dx, int dy){ if(dx>0){ if(col+dx0) col +=dx; else{
- pattern minor 112d agoBitex - Cryptocurrency Exchange API Framework for PythonBitEx is a Python module I've been working on for a little over 9 months now, as a side project. It was published 6 months ago on GitHub, and as I edge closer to my 1.0 release, I wanted to take the opportunity to present my code on here, in order to straighten it out. What it solves and offers It's designed to eliminate the need to get into the gory details of REST APIs of crypto exchanges, and offer a homogeneous and intuitive interface for all supported APIs. It takes care of authentication procedures, and offers a standardized set of methods (with identical method signature) for all commonly used methods at an exchange (polling order book & tickers, placing and cancelling orders, amongst others), as well as all other specific methods (or as many as I had the time to implement thus far). It comes, essentially, as two sub packages: `bitex.api` is the backend taking care of setting up http requests via the `requests` module, as well as handling authentication specifics. It can be seen as wrapper for `requests` and technically could be used all on its own to send and receive data to/from exchanges. The other is `bitex.interfaces`, which offers the above mentioned homogenous, standardized methods for all implemented exchanges. In addition to offering identical method signatures, it also aims to standardize method's return values. As these can differ significantly from exchange to exchange, these methods take care of data formatting, via the help of formatters found in `bitex.formatters` and the `return_json` decorator. It relies on `bitex.api`. Why I am submitting this for review Ever since I started this project, I've rewritten the base code several times significantly. It took me a long time to figure out how to lay out the structure (which is mostly due to my learning curve over the past year as a first year software development apprentice). Over the past two months, however, I've become rather fond and proud of the current structure and deem it quite prese
- pattern minor 112d agoSimple JavaScript Module "Loader"I have written a simple JS module "loader" (loader is in quotes because it doesn't actually load the files) that is designed to resolve simple dependencies between modules. It is heavily inspired by module.js and takes some of it's design from it. Here is the code itself: `(function() { function create() { var definitions = {}, instances = {}; // Returns whether or not a module with the provided id is defined. var defined = function(id) { return definitions.hasOwnProperty(id); }; // Define a module with the provided id and definition. var define = function(id, definition) { if(defined(id)) { throw new Error('module already defined: ' + id); } definitions[id] = definition; }; // Undefine a module with the provided id. var undefine = function(id) { if (!defined(id)) { throw new Error('module not defined: ' + id); } delete definitions[id]; delete instances[id]; }; // Require a module with the provided id. var require = function(id) { var stack = []; var internalRequire = function(id) { if(!defined(id)) { throw new Error('module not defined: ' + id); } // If we have already seen this id on the require stack, we've got // some form of cyclic dependency. if (stack.indexOf(id) !== -1 && stack.push(id)) { throw new Error('cyclic dependency: ' + stack.join(' -> ')); } else { stack.push(id); } // If we already have an instance for this module, return it. if (instances.hasOwnProperty(id)) { return instances[id]; } else if (typeof(definitions[id]) === 'function') { // Otherwise if our definition is a function, call it and pass the // require method to it. return instances[id] = definitions[id].call(null, internalRequire); } else { // Otherwise just return the definition
- pattern minor 112d agoStatus display moduleI've developed a template to modularize JavaScript code I write for client work. The example below is a simple class with 1 attribute and 3 functions. Rationale: - Standardized constructor to add or modify settings/ options - Functions as variables used later to return only "public" functions, all else are private - Using local "call" variable to easily replace functions in unit testing Are there any improvements you can recommend or general best practices to look for in terms of improvement? ``` var dataStatus = function( constructorOptions ) { "use strict"; var options = { displayId: 'dataStatus', statii: { 'settingUp': { tooltip: 'Setting Up...', color: '808080' }, 'loading': { tooltip: 'Data Loading...', color: '99ee90' }, 'loaded': { tooltip: 'Data Loaded', color: '006400' }, 'changed': { tooltip: 'Data Changed', color: '8b0000' }, 'saving': { tooltip: 'Saving...', color: 'ffd700' } }, defaultStatus: 'settingUp' }; var local = { status: false }; var init = function( optionsToSet ) { jQuery.extend( options, optionsToSet); call.setStatus( options.defaultStatus ); return this; }; var inject = function (functionToReplace, injectedFunction) { call[functionToReplace] = injectedFunction; return injectedFunction; }; var getStatus = function() { return local.status; }; var setStatus = function( status, signal ) { local.status = status; if (typeof signal == 'undefined' || signal != false){ call.signal( call.getStatus() ); } }; var signal = function ( status ){ if (status in options.
- pattern minor 112d agoModularised Document ConstructionThe goal: A set of configurable options, combined with a standardised data source, to produce a standardised Report. This question: One module of said document, with accompanying code. Input: (Dropdown selection): An Attitude To Risk (ATR) Value. 1 to 5. Business Logic: Select from pre-configured descriptions and hardcoded text sections. Insert relevant name into introduction text. Format as appropriate. Output: An attitude to risk description and overview. Printable. Input: Hardcoded Text: Pre-Configured Descriptions: Output: Considering this document is likely to span to ~30 sections or more, is my current approach sufficiently modularised and self-contained? Have I chosen a bad way to go about this? (I considered building it in Word, but Word is, well, messy). How's my naming? Is it okay to hard-code Named Ranges like that? How easy is it to follow my code? Any other feedback is, of course, welcomed. Code: ``` Option Explicit Public Sub BtnMakeSelections_OnClick() DisableApplicationSettings FillAtrSheet ResetApplicationSettings End Sub Public Sub FormatAsPlainText(ByRef formatRange As Range) formatRange.Font.Size = 12 formatRange.Font.Bold = False formatRange.Font.ColorIndex = 0 End Sub Public Function GetAtrNum() As Long Dim atrRange As Range Set atrRange = wsInputs.Range("ATR_Selection") Dim atrNum As Long atrNum = CLng(atrRange.value) GetAtrNum = atrNum End Function Public Sub CopyPasteCell(ByRef copyCell As Range, ByRef pasteCell As Range, Optional ByVal pasteRowHeights As Boolean = False) copyCell.Copy pasteCell.PasteSpecial xlPasteAll If pasteRowHeights Then Dim sourceRowHeight As Long sourceRowHeight = copyCell.rowHeight pasteCell.rowHeight = sourceRowHeight End If End Sub Public Sub FindAndFormatAsHeading(ByRef targetCell As Range, ByVal targetString As String) If HasCharacters(targetCell) Then Dim targetCharacters As Characte
- pattern minor 112d agoPerl recursive copy and move functionsI know a module like this already exists on CPAN, but I wanted to write my own simplified version that accepts wildcards in the input. I don't write many Perl modules so I figured I would post the code here and see if anyone could give me advice on how to make this code more efficient or user friendly. I also included some POD documentation so you can use perldoc for usage information. Please let me know what you think and leave some feedback on how this code could be improved! ``` package File::Copy::Recursive; # Use statements use File::Basename; use File::Copy; use File::Path qw(make_path remove_tree); use strict; use warnings; # Link the version number with CVS our ($VERSION) = (q$Revision: 1.1 $ =~ m{([0-9.]+)}); # Exporter require Exporter; our @ISA = qw( Exporter ); # Declare exportable routines our @EXPORT_OK = qw( recursive_copy rcopy recursive_move rmove ); # Aliases to subroutines sub rcopy { recursive_copy(@_); } sub rmove { recursive_move(@_); } # Recursive copy function sub recursive_copy { my ($source, $destination) = @_; for my $path (glob $source) { if (-d $path) { make_path($destination.'/'.basename($path)); recursive_copy($path.'/*', $destination.'/'.basename($path)); } else { copy($path, $destination); } } } # Recursive move function sub recursive_move { my ($source, $destination) = @_; for my $path (glob $source) { if (-d $path) { make_path($destination.'/'.basename($path)); recursive_move($path.'/*', $destination.'/'.basename($path)); remove_tree($path); } else { move($path, $destination); } } } 1; __END__ =head1 NAME File::Copy::Recursive - Recursive copy and move functions. =head1 VERSION $Revision: 1.1 $ =head1 SYNOPSIS use File::Copy::Recursive; # Recursively copy a directory recursive_copy('input', 'output'); # Recursively copy al
- pattern minor 112d agoCombat simulator - single page JavaScript with requirejs from a Java AppletSingle-page web app from Applet I'm seeking feedback on my first single-page web app using RequireJS and a web worker. I converted it from a Java applet, and the code is up on GitHub. It's a combat simulator based on the old-school (1977) game of Melee. The RequireJS design is based on jrburke's single page app template. Here's what the whole design looks like in UML: Feedback I'm seeking I'm an experienced Java programmer who, upon realizing Java applets don't run in browsers anymore (I know I'm late to that party!), decided to bite the bullet and move to JavaScript. The result I have seems to work well and in some ways is probably better than my Java applet originally was. I'm curious for feedback on my approach to converting the applet and the use of RequireJS, web workers, etc. - I tried as best I could to reproduce the Java Swing GUI in HTML 5 and BootStrap. I'm not 100% happy with an HTML Select with multiple option to reproduce a Java `JList`. It's not great in mobile versions of Chrome (Android), as it remains "closed" until you tap on it. There's no easy way to select all, for example (you have to tap once on each item!). But it works great in desktop browsers. You can try the "live" version of the simulator. - Since HTML 5 web workers have almost 100% separate memory space from the main thread, I intentionally didn't use the same class with RequireJS in two separate threads (see the UML diagram). Probably this isn't a hard an fast rule. But in an early design, one of my classes (`HeroesSingleton`) was being loaded twice (once in the main, once in the web worker) and so it wasn't actually a singleton. That seems to be a gotcha with RequireJS and threads. - I followed a few templates for RequireJS class designs for the "objects" in the simulator, e.g., `Hero`, `Weapon`, etc. In the simulator, only `Hero` and `Game` objects are objects that change state (not immutable). I'm pretty sure the methods (getters) I have there are overkill since there is no
- pattern minor 112d agoRSS parser for Node.JSI would like someone to review this code and tell if it can be done better, or if the code is elegant and simple enough for the task at hand. I used code climate and I got 4/4 and my test coverage is 96%, yet I would like a professional opinion about it. ``` 'use strict'; var cheerio = require('cheerio'); var FeedParser = require('feedparser'); var http = require('http'); var PromisePolyfill = require('promise'); var urlEncode = require('urlencode'); /** * Extracts a valid url from the RSS Feed Item, taking into account exception urls * @param {string} content - the item to be analyzed * @returns {string} - the valid url inside the item */ function getValidURL(content) { var $ = cheerio.load(content), responseUrl; $('a').each(function(i, e) { if ( $(e).attr('href').indexOf('reddit.com') === -1 && $(e).attr('href').indexOf('imgur.com') === -1 ) { responseUrl = $(e).attr('href'); } }); return responseUrl; } /** * Parses a RSS stream into an Object * @param {string} rssUrl - RSS url to fetch the stream * @returns {Object} - the Object with meta and item information */ exports.parseRss = function(rssUrl) { var responseObject = { title: '', link: '', image: '', items: [] }; return new PromisePolyfill(function(resolve, reject) { http.get(rssUrl, function(resGet) { resGet.pipe(new FeedParser({})) .on('error', function(error) { reject(error.message); }) .on('meta', function(meta) { responseObject.title = meta.title; responseObject.link = meta.link; }) .on('readable', function() { var stream = this, item, validUrl = ''; while ((item = stream.read())) { validUrl = getValidURL(item.description);
- pattern minor 112d agoProject Euler moduleI use Project Euler to teach me programming and not to submit any results. As such I look up the expected return values to double check my solutions. To organise my files I use the following folder structure: ``` main.py \euler # The problem files __init__.py # empty e001.py e002.py ... \input # Additional input files 8.dat 11.dat ... ``` My `main.py` file is the common entry point. It can either run all the solved examples so far or a specific one. This second option is added that I don't need to add an `if __name__ == '__main__'` guard in every file. The file looks as follows: ``` TOP_LEVEL = "euler" def run_module(num): """Run specific Problem""" mod = importlib.import_module('%s.e%0.3i' % (TOP_LEVEL, num)) start = time.time() ist = mod.run() print(" %5i | %6.3f | %s | %i" % \ (num, time.time() - start, "ox"[ist == mod.SOLL], ist)) if __name__ == '__main__': N_MAX = 67 # Pre Header print('Problem | Time | x/o | Solution') print("--------+--------+-----+---------") global_time = time.time() # Run over all problems if len(sys.argv) == 2: run_module(int(sys.argv[1])) else: for num in range(1, N_MAX + 1): run_module(num) # End Header print("--------+--------+-----+---------") print("Total: %.3f s" % (time.time() - global_time)) ``` I'll show now two example files to show the source files and how old code can be reused. `e018.py`: ``` """By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below""" SOLL = 1074 def run(file = "input/18.dat"): # Parse File with open(file) as fid: tri = [[int(num) for num in line.split(' ')] for line in fid.read().split('\n')] # From bottom's up find the maximal value for row
- principle minor 112d agoStrategy to reduce duplicate code in many similar modulesThe Situation I have created some code in the form of modules that each represent a medical questionnaire (I'm calling them `Catalog`s). Each different questionnaire has its own module as they may differ slightly in their content and associated calculations, but are essentially made up of simple questions that have boolean/numeric possible responses. Here is an example. These `Catalog` modules are included in an `Entry` class that collects responses matching the question names. Each questionnaire is transformed into a `DEFINITION` which is used in the `Entry` to do things like: - Validate inputs - Check completeness - Calculate scoring There are 2 examples for reference at the bottom that illustrate the problem of duplication... much of the code is similar but not exactly the same. The Problem There is a lot of duplication here, but I'm not sure about the best strategy to remove it. There are a few things that make it difficult for this particular problem and make me lean towards accepting some duplication as opposed to a system that is too strict to work. The system needs to remain flexible enough to accommodate currently unknown medical questionnaires of a similar nature so I need to be careful (the reason I've gone with a `Module` system so far) Here are some examples: - Each `Catalog` can have slightly different scoring requirements and custom grouping of questions that represent one "score" - Potentially many `Catalog`s are included in an `Entry` class and can't step on each other - Some `Catalog`s incorporate things like "Current Weight" for calculations, breaking the 1-5 or 1-10 paradigm and not fitting very nicely into simple `sum` reductions. - One `Catalog` requires a week of previous entries in order to be valid, a sort of weird custom validation. The Question: What strategies might be employed here to reduce duplication overall? I'm not looking for tweaks cut out a few lines from these specific examples. Implementation cost is a considerat