texts: Modelling employees in Go as a basic OOP exercise

texts:
I am learning Go and have the following working code:

$GOPATH/src/mvctest/main.go

package main

import (
    "fmt"
    "mvctest/model"
)

func main() {
    // Initialise the data model
    employees := model.NewPeople("Employee")

    // Populate the model
    employees.Add(model.NewPerson("Joe", 99))
    employees.Add(model.NewPerson("Sue", 45))
    employees.Add(model.Person{Name: "Tom", Age: 22}) // break encaps a bit

    // Test retrieval from model
    fmt.Printf("You have %d employees.\n", employees.Count())

    for i := 0; i < employees.Count(); i++ {
        f, err := employees.Person(i)
        if err != nil {
            fmt.Printf("Unable to get employee %d because %v", i, err)
            return
        }
        fmt.Printf("Employee %d is %s\n", i+1, f)
    }

    // Test error handling for impossible values
    test(employees, -1)
    test(employees, 42)

}

// Tests whether a person can be retrieved using an index value
func test(ppl *model.People, i int) *model.Person {
    p, err := ppl.Person(i)
    if err != nil {
        fmt.Printf("Unable to get %s %d because %v\n", ppl.Group(), i, err)
        return nil
    }
    return p
}

$GOPATH/src/mvctest/model/model.go

package model

import (
    "errors"
    "fmt"
)

// ------------------------------------------------------

type Person struct {
    Name    string
    hatsize int
    Age     int
}

func (p *Person) String() string {
    return fmt.Sprintf("%s aged %d.", p.Name, p.Age)
}

func NewPerson(name string, age int) Person {
    return Person{name, 0, age}
}

// ------------------------------------------------------

type People struct {
    group string
    list  []Person
}

func (ppl *People) SetGroup(g string) {
    ppl.group = g
}

func (ppl *People) Group() string {
    return ppl.group
}

func (ppl *People) Add(p Person) {
    ppl.list = append(ppl.list, p)
}

func (ppl *People) Count() int {
    return len(ppl.list)
}

func (ppl *People) Person(i int) (*Person, error) {
    n := len(ppl.list)
    if i < 0 || i >= n {
        return nil,
            errors.New(fmt.Sprintf("%s index %d is out of range %d-%d.",
                ppl.group, i, 0, len(ppl.list)-1))
    }
    return &ppl.list[i], nil
}

func NewPeople(group string) *People {
    ppl := new(People)
    ppl.group = group
    return ppl
}

Output

You have 3 employees.
Employee 1 is Joe aged 99.
Employee 2 is Sue aged 45.
Employee 3 is Tom aged 22.
Unable to get Employee -1 because Employee index -1 is out of range 0-2.
Unable to get Employee 42 because Employee index 42 is out of range 0-2.

I'd appreciate any comments but a few things that I am uncertain about or which bother me.

I'm not sure whether defining constructing NewPerson and NewPeople is the right thing to do. I can't have two functions called New in the same file / package and I can't make these into methods of different structs (i.e. different object types) since the caller doesn't yet have an instance to use.
I'm wondering if there is a simple way to allow iterating using range rather than the for loop in main.go?


texts: How might we make this Python Merge Sort implementation more Pythonic?

texts:
I've implemented a (version of) Merge Sort algorithm in Python. My goal here is two-fold:

Improve understanding of Merge Sort and recursion in a language agnostic way.
Improve understanding of Python conventions and idioms.

The implementation recursively splits the given sequence into left and right sequences and then merges the two subsequences back together sorted in ascending order.

All suggestions for improvement are welcome. I'd especially like feedback on the following:

looping through total length of sequence and the unused variable.
use of try-except blocks.
use of indexing and slicing.

class MergeSort(object):

def sort(self, seq):
    '''
    Sorts a sequence of integers.

    @param seq: an unsorted tuple or list.
    @return:    a new tuple with elements in @seq sorted in ascending order.
    '''
    if(len(seq) <= 1):
        return seq
    else:
        return self._merge(leftSortedSeq=self.sort(seq[0:(len(seq) / 2)]),
                           rightSortedSeq=self.sort(seq[(len(seq) / 2):]))

def _merge(self, leftSortedSeq, rightSortedSeq):
    if(len(leftSortedSeq) == 0):
        return rightSortedSeq
    elif(len(rightSortedSeq) == 0):
        return leftSortedSeq

    leftPointer = 0
    rightPointer = 0
    mergedSeq = []
    mergedSeqLength = len(leftSortedSeq) + len(rightSortedSeq)
    for elementNumber in range(mergedSeqLength):

        try:
            smallestInLeft = leftSortedSeq[leftPointer]
        except IndexError:
            mergedSeq += rightSortedSeq[rightPointer:]
            return tuple(mergedSeq)

        try:
            smallestInRight = rightSortedSeq[rightPointer]
        except IndexError:
            mergedSeq += leftSortedSeq[leftPointer:]
            return tuple(mergedSeq)

        if(smallestInLeft < smallestInRight):
            mergedSeq.append(leftSortedSeq[leftPointer])
            leftPointer += 1
        else:
            mergedSeq.append(rightSortedSeq[rightPointer])
            rightPointer += 1

    return tuple(mergedSeq)


texts: jQuery Plugin, multiple instances/elements with different options

texts:
I was having some real issues creating a jQuery plugin that could handle multiple instances with different config options. I came up with this, but am not sure if it follows best practices. I used some sample boilerplate, but it didn't handle exactly what I wanted, though the core of that still remains.

Here's a fiddle: https://jsfiddle.net/nvyxjpwu/9/

I wanted something that can be called like this:

$('#me').testPlugin();
$('#metoo').testPlugin({ backgroundColor: 'red' });
$('#methree').testPlugin({ backgroundColor: 'yellow' });

$("#me").testPlugin('makeDoThing', 35);
$("#metoo").testPlugin('makeDoThing', 50);

javascript

(function ( $ ) {

    var Plugin = function(el){

        var plugin = {};

        var config = {
            backgroundColor: 'blue'
        }

        plugin.el = el;
        var $el = $(el);
        var $elSpan;

        plugin.methods = {
            init: function(options){
                $elSpan = $el.find('span');
                $.extend(config, options);
                $el.css(config);
            },
            makeDoThing: function(size){
                $el.css({ fontSize: size+'px' });
                $elSpan.html('HELLO');
            }
        }

        return plugin;
    }

    var INSTANCES = {};

    $.fn.testPlugin = function(input){

        var EL   = this;
        var ARGS = arguments;

        this.each(function(){

            var id = $(this).attr('id');

            if(!INSTANCES[id]){
                INSTANCES[id] = new Plugin(EL);
            }

            var plugin = INSTANCES[id];

            if ( plugin.methods[input] ) {
                return plugin.methods[input].apply( plugin.el, Array.prototype.slice.call( ARGS, 1 ));
            } else if ( typeof input === 'object' || !input ) {
                plugin.methods.init(input);
            } else {
                $.error( 'Method ' +  input + ' does not exist on jQuery.narratorsGrid' );
            }
        });
    }

}(jQuery));


texts: Thread Safe Circular Queue Implementation

texts:
#pragma once

#include <atomic>
#include <memory>

template <typename T> class RingBuffer {
public:

    explicit RingBuffer(std::size_t capactiy) : _buffer_capacity(capactiy){
        std::unique_ptr <T[], RingBufferFree> buffer_ptr(new T[capactiy]);
        _ring_buffer_array = std::move(buffer_ptr);
    }

    ~RingBuffer() {

    }

    void Push(T val) {
        while (!TryPush(val));
    }

    T Pop() {
        T val;
        while (!TryPop(&val));
        return val;
    }

private:

    //Private Struct to ensure allocated memory is freed.
    struct RingBufferFree{
        void operator()(T * ring_buffer_memory) { delete[] ring_buffer_memory; }
    };

    //Private Member Functions
    bool TryPush(T & val) {
        const std::size_t current_write = write_position.load(std::memory_order_acquire);
        const std::size_t current_read = read_position.load(std::memory_order_acquire);
        const std::size_t next_write = increment_index(current_write);

        if (next_write == current_read) { return false; }

        _ring_buffer_array[current_write] = val;
        write_position.store(next_write, std::memory_order_release);

        return true;
    }

    bool TryPop(T * val) {
        const std::size_t current_write = write_position.load(std::memory_order_acquire);
        const std::size_t current_read = read_position.load(std::memory_order_acquire);

        if (current_read == current_write) { return false; }

        *val = _ring_buffer_array[current_read];

        const std::size_t next_read = increment_index(current_read);
        read_position.store(next_read, std::memory_order_release);

        return true;
    }

    std::size_t increment_index(std::size_t index) {
        return (index + 1) % _buffer_capacity;
    }

    //Private Member Variables
    std::atomic<std::size_t> read_position = 0;
    std::atomic<std::size_t> write_position = 0;

    std::size_t _buffer_capacity;
    std::unique_ptr<T[], RingBufferFree> _ring_buffer_array;
};

I have tested my code and it appears to work, but I would like some second opinions on what I did. This first time I have tried lock free programming with atomic variables and so I would appreciate it if I had more experienced programmers provide feed back.


texts:
I need a class to read and store directory structure. This is my first step in Objective C so I ask to you to say what you think.

Header file:

#import <Foundation/Foundation.h>

@interface FileStructureRepresentation : NSObject

- (id)initWithPath:(NSString *)path;
-(NSMutableDictionary*) parse;

@end

Code:

#import "FileStructureRepresentation.h"

@implementation FileStructureRepresentation

NSFileManager *fileManager = nil;
NSString *startPath;

- (id)initWithPath:(NSString *)path
{
    self = [super init];
    if (self) {
        fileManager = [NSFileManager defaultManager];
        startPath = path;
    }
    return self;
}

-(NSMutableDictionary *) parse {
    return [self parseDirectory:startPath];
}

-(NSMutableDictionary *) parseDirectory:(NSString *)path {
    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    NSMutableArray *collectionOfFilesAndDirectories = [[NSMutableArray alloc] init];
    NSError *error = nil;
    NSArray *listOfFiles = [fileManager contentsOfDirectoryAtPath:path error:&error];

    if(error.code != 0) {
        NSLog(@"Error code:%d, Description:%@", error.code, error.description);
    }

    for(NSMutableString *s in listOfFiles) {
        NSString *temporaryPath = [NSString stringWithFormat:@"%@/%@", path, s];
        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:temporaryPath
                                                                     error:&error];
        NSString *fileType = [fileAttributes valueForKey:NSFileType];
        if([fileType isEqualToString:@"NSFileTypeRegular"])
            [collectionOfFilesAndDirectories addObject:s];
        else
            [collectionOfFilesAndDirectories addObject:[self parseDirectory:temporaryPath]];
    }

    [result setObject:collectionOfFilesAndDirectories forKey:path];

    return result;
}

@end

Example:

FileStructureRepresentation *fileStructure = [[FileStructureRepresentation alloc] initWithPath:@"/Users/demas/temporary/tst"];
NSMutableDictionary *structureModel = [fileStructure parse];


texts: A text editor driven file renamer in Ruby

texts:
I wrote the following Ruby script several years ago and have been using it often ever since.

It opens a text editor with the list of files in current directory. You can then edit the file names as text. Once you save and exit the files are renamed.

The renamer allowed me to maintain spreadsheet-like file names thanks to the powerful column editing capabilities of vi (emacs also has those).

Here is how one such directory looks:

I would like to use it as an example for a Ruby workshop. Could you please suggest best-practice and design pattern improvements?

#!/usr/bin/ruby

RM = '/bin/rm'
MV = '/bin/mv'

from = Dir.entries('.').sort; from.delete('.'); from.delete('..')
from.sort!

from.delete_if {|i| i =~ /^\./} # Hidden files

tmp = "/tmp/renamer.#{Time.now.to_i}.#{(rand * 1000).to_i}"

File.open(tmp, 'w') do |f|
  from.each {|i| f.puts i}
end

ENV['EDITOR'] = 'vi' if ENV['EDITOR'].nil?
system("#{ENV['EDITOR']} #{tmp}")

to = File.open(tmp) {|f| f.readlines.collect{|l| l.chomp}}
`#{RM} #{tmp}`

if to.size != from.size
  STDERR.puts "renamer: ERROR: number of lines changed"
  exit(1)
end

from.each_with_index do |f, i|
  puts `#{MV} -v --interactive "#{f}" "#{to[i]}"` unless f == to[i]
end


texts: Using Entity Framework to Call an Oracle Stored Procedure with Multiple Cursors

texts:
I wrote the following code to use Entity Framework 6 and Managed Oracle Providers to call an Oracle stored procedure that returns multiple cursors.

Would like some input about the code I used to open and close the database connection. Please note that the open and close code is a workaround for a possible bug in the Oracle library that occurs every time using is used. Doing that instead of the workaround would throw the following exception:

 System.ObjectDisposedException: 'Cannot access a disposed object.Object name: 'OracleConnection'.'

Would also like some input on the way I am getting the multiple cursors and whether or not there might be a better way.

Working Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using Oracle.ManagedDataAccess.Client;
using System.Data.Entity.Infrastructure;

namespace MyCompany
{
    public class MyClass
    {
        private MyDbContext dbContext = new MyDbContext();

        public MyItems GetMyItems(string id)
        {
            var sqlQuery = "";
            var oracleParameters = new List<OracleParameter>();
            var oneEntityList = new List<OneEntity>();
            var twoEntityList = new List<TwoEntity>();
            var threeEntityList = new List<ThreeEntity>();

            sqlQuery = @"

BEGIN

MY_PACKAGE.GetMyItems(:id, :p_cursor1, :p_cursor2, :p_cursor3);

END;

";
            oracleParameters = new List<OracleParameter>
            {
                new OracleParameter("p_id", id),
                new OracleParameter("p_cursor1", OracleDbType.RefCursor, ParameterDirection.Output),
                new OracleParameter("p_cursor2", OracleDbType.RefCursor, ParameterDirection.Output),
                new OracleParameter("p_cursor3", OracleDbType.RefCursor, ParameterDirection.Output)
            };

            var connection = dbContext.Database.Connection;
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = sqlQuery;
            command.Parameters.AddRange(oracleParameters.ToArray());
            using (var reader = command.ExecuteReader())
            {
                oneEntityList = ((IObjectContextAdapter)dbContext).ObjectContext
                                                                            .Translate<OneEntity>(reader)
                                                                            .ToList();
                reader.NextResult();

                twoEntityList = ((IObjectContextAdapter)dbContext).ObjectContext
                                                                            .Translate<TwoEntity>(reader)
                                                                            .ToList();
                reader.NextResult();

                threeEntityList = ((IObjectContextAdapter)dbContext).ObjectContext
                                                                            .Translate<ThreeEntity>(reader)
                                                                            .ToList();
            }
            connection.Close();

            return new MyItems { OneEntity = oneEntityList, TwoEntity = twoEntityList, ThreeEntity = threeEntityList };

        }
    }
}


texts: Create player according to chosen difficulty

texts:
I am coding a 2D board game. I let the user choose the difficulty level in the beginning, which influences the skills points of the player.

Here is the code I wrote for the Player class:

package model;

public class Player {

    // VARIABLES ---------------------------

    private Position position;
    private int score = 0;
    private int stepsLeft;
    private int fightingSkill;
    private int jokingSkill;
    private int visionScope = 2;
    private String skillChoice;

    // CONSTRUCTOR --------------------------

    public Player(Position position, int difficultyLevel) {
        this.position = position;

        switch(difficultyLevel) {
        case 1:
            this.stepsLeft = 150;
            this.fightingSkill = 5;
            this.jokingSkill = 5;

        case 2:
            this.stepsLeft = 150;
            this.fightingSkill = 2;
            this.jokingSkill = 2;

        case 3:
            this.stepsLeft = 100;
            this.fightingSkill = 2;
            this.jokingSkill = 2;

        case 4:
            this.stepsLeft = 10;
            this.fightingSkill = 1;
            this.jokingSkill = 1;
        }
    }

    public Player(int stepsLeft, int fightingSkill, int jokingSkill) {
        this.stepsLeft = stepsLeft;
        this.fightingSkill = fightingSkill;
        this.jokingSkill = jokingSkill;
        this.position = new Position(1,1);
        this.score = 0;
    }

    // METHODS ------------------------------

    public void move(Position destination) {
        setPosition(destination);
        stepsLeft -= 1;
    }

    public void increaseScore(int bonus) {
        score += bonus;
    }

    public void increaseStepsLeft(int bonus) {
        stepsLeft+= bonus;
    }

    public void increaseFightingSkill(int bonus) {
        fightingSkill += bonus;
    }

    public void increaseJokingSkill(int bonus) {
        jokingSkill += bonus;
    }

    // GETTERS

    public Position getPosition() {
        return position;
    }

    public int getXPosition() {
        return position.getX();
    }

    public int getYPosition() {
        return position.getY();
    }

    public int getScore() {
        return score;
    }

    public int getStepsLeft() {
        return stepsLeft;
    }

    public int getFightingSkill() {
        return fightingSkill;
    }

    public int getJokingSkill() {
        return jokingSkill;
    }

    public String getSkillChoice() {
        return skillChoice;
    }

    public int getVisionScope() {
        return visionScope;
    }

    // SETTERS

    public void setPosition(Position position) {
        this.position = position;
    }

    public void setSkillChoice(int choice) {
        switch(choice) {
        case 0:
            this.skillChoice = "joke";
            break;
        case 1:
            this.skillChoice = "fight";
            break;
        case 2:
            this.skillChoice = "magic";
            break;
        default:
            ;
        }
    }

    public String toString() {
        return "play \t"+position+"\t"+stepsLeft+"\t"+jokingSkill+"\t"+score+"\n";
    }
}

My questions

I chose to use a switch statement in the constructor, to create my player with features according to the difficulty level. I have the feeling that is maybe not the good practice to have such a switch in a constructor but can't really say why, and don't find a better way. Is there a better way to do this?
Any other comments about that class? I've programmed scientific code but am quite new to OOP and Java. Any comment is welcome.


texts:
I have a Cython function that takes a list of weights/probabilities (double) and returns a random index into the list.

For example:

choose_one(np.array([0.1, 0.4, 0.2, 0.3]), 4)

Returns 0 with probability 0.1, 1 with probability 0.4 etc.

The Cython code is:

cdef extern from "stdlib.h":
    double drand48()
    void srand48(long int seedval)

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.nonecheck(False)
def choose_one(np.ndarray[double, ndim=1] weights, Py_ssize_t length):
    cdef Py_ssize_t idx, i
    cdef double cs
    cdef double random
    random = drand48()
    cs = 0.0
    i = 0
    while cs < random and i < length:
        cs += weights[i]
        i += 1
    return i - 1

I profiled some complex simulation code and found that about 50% of the execution time is spent in this function which is called approximately 3.5 million times. Because it is such a time hog, and such an important utility, I'd like to speed it up if possible.

One of the problems is that the input arrays are often very large with thousands of entries.

I tried various methods from Numpy in Cython and none of them come close to as fast as what I have written in Cython. I am a Cython newbie and am curious if there is something else I need to do to speed this up.


texts:
I've written a couple of functions to check if a consumer of the API should be authenticated to use it or not.

Have I done anything blatantly wrong here?

Config

API_CONSUMERS = [{'name': 'localhost',
                  'host': '12.0.0.1:5000',
                  'api_key': 'Ahth2ea5Ohngoop5'},
                 {'name': 'localhost2',
                  'host': '127.0.0.1:5001',
                  'api_key': 'Ahth2ea5Ohngoop6'}]

Exceptions

class BaseException(Exception):

    def __init__(self, logger, *args, **kwargs):
        super(BaseException, self).__init__(*args, **kwargs)
        logger.info(self.message)

class UnknownHostException(BaseException):
    pass

class MissingHashException(BaseException):
    pass

class HashMismatchException(BaseException):
    pass

Authentication methods

import hashlib
from flask import request
from services.exceptions import (UnknownHostException, MissingHashException,
    HashMismatchException)

def is_authenticated(app):
    """
    Checks that the consumers host is valid, the request has a hash and the
    hash is the same when we excrypt the data with that hosts api key

    Arguments:
    app -- instance of the application
    """
    consumers = app.config.get('API_CONSUMERS')
    host = request.host

    try:
        api_key = next(d['api_key'] for d in consumers if d['host'] == host)
    except StopIteration:
        raise UnknownHostException(
            app.logger, 'Authentication failed: Unknown Host (' + host + ')')

    if not request.headers.get('hash'):
        raise MissingHashException(
            app.logger, 'Authentication failed: Missing Hash (' + host + ')')

    hash = calculate_hash(request.method, api_key)

    if hash != request.headers.get('hash'):
        raise HashMismatchException(
            app.logger, 'Authentication failed: Hash Mismatch (' + host + ')')

    return True

def calculate_hash(method, api_key):
    """
    Calculates the hash using either the url or the request content,
    plus the hosts api key

    Arguments:
    method  -- request method
    api_key -- api key for this host
    """
    if request.method == 'GET':
        data_to_hash = request.base_url + '?' + request.query_string
    elif request.method == 'POST':
        data_to_hash = request.data

    data_to_hash += api_key
    return hashlib.sha1(data_to_hash).hexdigest()


texts: Identifying numeric substrings of an alphanumeric string, and summing them

texts:
I am going through the CodingBat exercises for Java. Here is the task I have just completed:

  Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row.

And here is my code:

public int sumNumbers(String str){
    int total = 0;

    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            StringBuilder appendNums = new StringBuilder();
            appendNums.append(str.charAt(i));
            for (int j = i+1; j < str.length(); j++) {
                if (Character.isDigit(str.charAt(j))) {
                    appendNums.append(str.charAt(j));
                } else {
                    break;
                }
            }
            String appendNums2String = appendNums.toString();
            total += Integer.parseInt(appendNums2String);
            i += appendNums2String.length()-1;
        }
    }
    return total;
}

The questions I have are:

Are there any parts of this code you find to be poor practise or
poor quality?
Is it acceptable to append one digit before the (conditional) digits that proceed it, or should I be identifying the entire block
first, and then append?
What is a more concise way of solving this?
For this question I relied heavily on Eclipse's debugger until I got it right. Is this good or bad practise?
Is it a better idea to use a while loop instead of the second for loop, because the characters tested are relative to i rather than the string's length? (I played around with this but couldn't figure it out.)


texts: Code review of code to strip 0 from decimal series

texts:
The following code would strip 0 (all numbers ending with 0, it can contain 0, eg: 105 can be is valid but 150 should be eliminated) and return a number in decimal series if all numbers ending with 0 were stripped.
 Example : 0 -> 1, 10 -> 11, 19 -> 22.
I would just appreciate any code reviews.

  public static int getStrippedNumber(int num) {
    int setId = (num / 10) + 1;
    int newNum = num + setId;
    int newNumSetId = (newNum / 10) + 1;
    int numberToReturn = num + newNumSetId;
    return numberToReturn % 10 ==0 ? numberToReturn + 1 : numberToReturn;
    }


texts:
I am looking for the fastest way to find document distance. How can I improve this?

Split each document into words. replaceAll() is faster than replace()

String.prototype.replaceAll = function(search, replacement) {
    return this.replace(new RegExp(search, 'g'), replacement);
};

Creating word array here:

const wordsFromDocument = doc => {
    //we care only about alphanumeric characters and space
    return doc.replaceAll(/[^a-zA-Z0-9 ]/g, ``).split(` `);
};

count word frequencies (document vectors)

const wordFrequencies = words => {
    const wordFrequencyMap = new Map();
    for (const word of words) {
        const lowerCaseWord = word.toLowerCase(); //We don't care about case sensitivity. What is faster way to achieve this?
        if (!wordFrequencyMap.has(lowerCaseWord)) {
            wordFrequencyMap.set(lowerCaseWord, 1);
        } else {
            wordFrequencyMap.set(lowerCaseWord, wordFrequencyMap.get(lowerCaseWord) + 1);
        }
    }
    return wordFrequencyMap;
};

Compute dot product (& divide).

const dotProduct = (wordFrequencyMapOne, wordFrequencyMapTwo) => {
    let sum = 0;
    const wordOneSize = wordFrequencyMapOne.size;
    const wordTwoSize = wordFrequenciesTwo.size;

    if (wordOneSize < wordTwoSize) {
        for (let key of wordFrequencyMapOne.keys()) {
            if (wordFrequencyMapTwo.has(key)) {
                sum = sum + wordFrequencyMapOne.get(key) *
                    wordFrequencyMapTwo.get(key);
            }
        }
    } else {
        for (let key of wordFrequenciesTwo.keys()) {
            if (wordFrequenciesOne.has(key)) {
                sum = sum + wordFrequencyMapOne.get(key) *
                    wordFrequencyMapTwo.get(key);
            }
        }
    }
    return sum;
};

vector angle = (dot(1, 2)) / Sqrt (dot(1, 1) * dot(2, 2))

const vectorAngle = (wordFrequencyMapOne, wordFrequencyMapTwo) => {
    const numerator = dotProduct(wordFrequencyMapOne, wordFrequencyMapTwo);
    const denominator = Math.sqrt(dotProduct(wordFrequencyMapOne, wordFrequencyMapOne) * (dotProduct(wordFrequenciesTwo, wordFrequenciesTwo)))
    return numerator / denominator;
}


texts: HTML/JavaScript temperature converter with rounding

texts:
I am looking to improve the performance of my code through best practices and cleaner code.
My goal here is just to perform a conversion whenever there is a keyup.
But I noticed that my code looks very repetitive. In your view, what should I do to simplify it?

window.oninput = function(event) {
  var campo = event.target.id;

  // DECIMALS
  var i = document.getElementById("decimalTemp").value;
    ºC.value = (ºC.value * 1).toFixed(i);
    ºK.value = (ºK.value * 1).toFixed(i);
    ºF.value = (ºF.value * 1).toFixed(i);
    ºRa.value = (ºRa.value * 1).toFixed(i);
  // TEMPERATURE
  if (campo == "ºC") {
    ºK.value = (ºC.value * 1 + 273.15).toFixed(i);
    ºF.value = (ºC.value * 1.8 + 32).toFixed(i);
    ºRa.value = ((ºC.value * 1 + 273.15) * 1.8).toFixed(i);
  } else if (campo == "ºK") {
    ºC.value = (ºK.value * 1 - 273.15).toFixed(i);
    ºF.value = (ºK.value * 1.8 - 459.889).toFixed(i);
    ºRa.value = (ºK.value * 1.8).toFixed(i);
  } else if (campo == "ºF") {
    ºC.value = ((ºF.value * 1 - 32) / 1.8).toFixed(i);
    ºK.value = ((ºF.value * 1 + 459.67) / 1.8).toFixed(i);
    ºRa.value = (ºF.value * 1 + 459.67).toFixed(i);
  } else if (campo == "ºRa") {
    ºC.value = (ºRa.value / 1.8 - 273.15).toFixed(i);
    ºK.value = (ºRa.value / 1.8).toFixed(i);
    ºF.value = (ºRa.value * 1 - 459.67).toFixed(i);
  }

};

Temperature <input type="number" min="0" max="12" value="0" id="decimalTemp" name="decimal" placeholder="Decimal"> Decimals

Celsius (ºC) <input id="ºC" type="number" min="-273.15" value="20">

 Kelvin (K) <input id="ºK" type="number" min="0" value="293">

 Farenheit (ºF) <input id="ºF" type="number" min="-459.67" value="68">

 Rankine (ºRa) <input id="ºRa" type="number" min="0" value="528">

Complete code on JSFiddle


texts:
Problem

Given the following data:

[
  {
    "users": [
      {
        "id": "07bde76f-aff0-407d-9241-a12b323d4af8",
        "transactions": [
          {
            "category": "purchase"
          },
          {
            "category": "unknown"
          }
        ]
      },
      {
        "id": "40aa040f-7961-4e06-a31b-32052be67fcc",
        "transactions": [
          {
            "category": "sale"
          },
          {
            "category": "unknown"
          }
        ]
      }
    ],
    "groups": [
      {
        "id": "00c61181-b133-4be9-9d44-dc3c224b3beb",
        "transactions": [
          {
            "category": "atm"
          },
          {
            "category": "cash"
          }
        ]
      },
      {
        "id": "eb959ff1-da1d-41e5-b5b7-45fef3dbc2df",
        "transactions": [
          {
            "category": "atm"
          },
          {
            "category": "cash"
          }
        ]
      }
    ]
  },
  {
    "users": [
      {
        "id": "af095f1c-fe43-43fb-9571-dabe2dd56bcf",
        "transactions": [
          {
            "category": "bill"
          }
        ]
      }
    ],
    "groups": [
      {
        "id": "c5bafe16-c5ec-428e-8c7c-30cbd9963750",
        "transactions": [
          {
            "category": "fee"
          },
          {
            "category": "cash"
          }
        ]
      }
    ]
  }
]

... I want to produce the following output:

{
  "groups_atm": 2,
  "groups_fee": 1,
  "groups_cash": 3,
  "users_purchase": 1,
  "users_unknown": 2,
  "users_bill": 1,
  "users_sale": 1
}

Implementation

I've approached this by first mapping over transactions and summing their occurrences:

const sum = (transactions) =>
    transactions.map((transaction) => transaction.category).reduce((acc, transactionCategory) => {
        return {
            ...acc,
            [transactionCategory]: (acc[transactionCategory] || 0) + 1,
        };
    }, tally);

... then aggregating by scope ("user", "group") per element of the data list and merge the counts by category:

const aggregate = (datum, tally) =>
    ['user', 'group'].reduce((acc, scope) => {
        const aggregates = datum[`${scope}s`].reduce(
            (agg, data) => sum(agg, data.transactions),
            {},
        );

        return {
            ...acc,
            [scope]: acc[scope] ? merge(acc[scope], aggregates) : aggregates,
        };
    }, tally);

const difference = (arrA, arrB) => arrA.filter((x) => !arrB.includes(x));
const intersection = (arrA, arrB) => arrA.filter((x) => arrB.includes(x));

const merge = (objA, objB) => {
    const acc = {};
    const aKeys = Object.keys(objA);
    const bKeys = Object.keys(objB);
    intersection(aKeys, bKeys).forEach((key) => (acc[key] = objA[key] + objB[key]));
    difference(aKeys, bKeys).forEach((key) => (acc[key] = objA[key]));
    difference(bKeys, aKeys).forEach((key) => (acc[key] = objB[key]));
    return acc;
};

... then re-reducing over the whole dataset:

const aggregates = data.reduce((acc, datum) => aggregateScope(datum, acc), {});

... and finally reformatting the aggregates to match the expected output:

const format = (aggregates) =>
    Object.keys(aggregates).reduce((acc, scope) => {
        Object.keys(aggregates[scope]).forEach((category) => {
            acc[`${scope}_${category}`] = aggregates[scope][category];
        });
        return acc;
    }, {});

Questions

what are alternative ways of breaking down the problem?
what is it's Big O complexity? Can it be reduced?
can merge be avoided?
are there language features (JS/ES6) that can make this more idiomatic?
is "aggregation" the correct terminology?


texts: Using multiple dropdowns that have a single source of options

texts:
This code works as is but I'd like to learn if there's any way it could be simplified or cleaner looking.

There are 3 dropdowns. Each dropdown's list of options are based on a single array of options.

If DD1 is set to 'A', DD2 is set to 'B', and DD3 is set to 'C' - while the options are ['A', 'B', 'C', 'D']  - One dropdown cannot select an option that is already in use by another dropdown.

In this situation, for example, DD1 would only allow you to choose from 'A' or 'D' because the other letters are already being used.

Parent

<ManageContactOrder options={['A', 'B', 'C', 'D']} order={{1: 'A', 2: 'B', 3: 'C'} action={this.getUpdatedOrder}/>

Child

class ManageContactOrder extends Component {

  constructor(props){
    super(props)
    let config = this.updateDropdownOptions();

    this.state = {
      order: config[0],
      availableOptions1: config[1],
      availableOptions2: config[2],
      availableOptions3: config[3]
    }
  }

  updateDropdownOptions(orderPassedIn){
    let options = this.props.options;
    let order = orderPassedIn ? orderPassedIn : this.props.order;

    let availableOptions1 = options.filter(option => !Object.values(order).includes(option));
    availableOptions1.push(order[1]);

    let availableOptions2 = options.filter(option => !Object.values(order).includes(option));
    availableOptions2.push(order[2]);

    let availableOptions3 = options.filter(option => !Object.values(order).includes(option));
    availableOptions3.push(order[3]);

    return [order, availableOptions1, availableOptions2, availableOptions3]
  }

  onChange = async (e, contactNumber) => {
    let selectedValue = e.target.value;
    let order = this.state.order;
    order[contactNumber] = selectedValue;
    let config = this.updateDropdownOptions(order);
    this.props.action(order);
    this.setState({
      order: config[0],
      availableOptions1: config[1],
      availableOptions2: config[2],
      availableOptions3: config[3]
    });
  }

  render() {
    const { order, availableOptions1, availableOptions2, availableOptions3 } = this.state;

    return (
      <>
         <DropDown
          options={availableOptions1}
          name='contact-order-one'
          id='contact-order-one'
          onChange={e => this.onChange(e, 1)}
          fieldValue={order[1]}
          data-testid='contact-order-one'
        />
          <DropDown
          options={availableOptions2}
          name='contact-order-two'
          id='contact-order-two'
          onChange={e => this.onChange(e, 2)}
          fieldValue={order[2]}
          data-testid='contact-order-two'
        />
        <DropDown
          options={availableOptions3}
          name='contact-order-three'
          id='contact-order-three'
          onChange={e => this.onChange(e, 3)}
          fieldValue={order[3]}
          data-testid='contact-order-three'
        />
      </>
    )
  }
}


texts: Using c++11 random header to generate random numbers

texts:
I'm new to programming. I have a question regarding the usage of c++11 random header to generate random numbers.
I tried to learn it, but was unsuccessful.
Recently, I've tried the following approach and it worked. Any advice on how to improve it. Is there a good source to learn more about this?
Here's the code:
#include <iostream>
#include <random>
#include <ctime>
int main()
{
   std::default_random_engine random_engine(time(0));
   for (int i = 1; i <= 100; i++)
   {
    std::uniform_int_distribution<int> num(1, 100);
    std::cout << i << "==> " << num(random_engine) << std::endl;
   }
    return 0;
}


texts: Is there a better way to code this text adventure game?

texts:
This is my first attempt with a basic text adventure game, and I was wondering if there was a way to make it more efficient (or any other things I could add to make the game better).  It isn't totally finished yet, but if there is a way to make it better, please post in the comments.

#lets me use the exit function
import sys
#Lets me use the time function
import time
#Want to play loop

    #asks for name
name = raw_input('What is your name, adventurer? ')
print 'Nice to meet you, '+name+'. Are you ready for your adventure?'
while True:
    ready = raw_input('y/n ')
if ready == 'y':
    print 'Good, let us start our great adventure!'
    break
elif ready == 'n':
    print 'That is a real shame...'
    time.sleep(1)
    print 'Exiting program in 5 seconds:'
    time.sleep(1)
    print '5'
    time.sleep(1)
    print '4'
    time.sleep(1)
    print '3'
    time.sleep(1)
    print '2'
    time.sleep(1)
    print '1'
    time.sleep(1)
    sys.exit('Exiting Game...')
    break
else:
    print 'That is not a valid answer... Try again'
    time.sleep(2)

#First level loop
while True:
print 'You awaken on the ground of a great forest. You can see two possible things to         do, enter the cabin to your left, or wander through the woods.'
print ' '

print 'Where do you want to go?'
FirstDecision = raw_input('cabin/woods ')
    #Cabin option
if FirstDecision == 'cabin':
    print 'You approach the door to the cabin, luckily it is unlocked.'
    Cnt = raw_input('Enter < to continue')
    print 'You open the door and walk through, only to hear a dry and shaky voice say:'
    print '\"Get out.\"'
    Cnt = raw_input('Enter < to continue')
    print 'What do you do?'
    FirstCabin = raw_input('leave/fight ')
    if FirstCabin == 'leave':
        print 'As you run out the door, the voice shoots and kills you.'
        Cnt = raw_input('Enter < to continue')
        print ' '
        FirstRetry = raw_input('Try again? (y/n)')
        if FirstRetry == 'y':
            print 'Restarting back at checkpoint...'
            time.sleep(2)
        elif FirstRetry == 'n':
            print 'That\'s a shame...'
            time.sleep(1)
            print 'Exiting program in 5 seconds:'
            time.sleep(1)
            print '5'
            time.sleep(1)
            print '4'
            time.sleep(1)
            print '3'
            time.sleep(1)
            print '2'
            time.sleep(1)
            print '1'
            time.sleep(1)
            sys.exit('Exiting Game...')
            break
    elif FirstCabin == 'fight':
        print 'You turn to where the voice came from and you bluntly say \"No.\"``


texts:
Morris Inorder traversal - an algorithm for in-order traversal, of a tree, without recursion of extra memory. Looking for code review, optimizations and best practices.

public class MorrisInOrder<T> {

    TreeNode<T> root;

    /**
     * Takes in a BFS representation of a tree, and converts it into a tree.
     * here the left and right children of nodes are the (2*i + 1) and (2*i + 2)nd
     * positions respectively.
     *
     * @param items The items to be node values.
     */
    public MorrisInOrder(List<? extends T> items) {
        create(items);
    }

    private void create (List<? extends T> items) {
        root = new TreeNode<T>(null, items.get(0), null);

        final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode<T> current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode<T>(null, items.get(left), null);
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode<T>(null, items.get(right), null);
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode<T> {
        TreeNode<T> left;
        T item;
        TreeNode<T> right;

        TreeNode(TreeNode<T> left, T item, TreeNode<T> right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    /**
     * Returns the inorder traversal of the tree.
     *
     * @return list containing inorder traversal of elements
     * @throws NoSuchAlgorithmException
     */
    public List<T> inOrder() throws NoSuchAlgorithmException {
        if (root == null) throw new NoSuchAlgorithmException("The root is null.");

        final List<T> list = new ArrayList<T>();
        TreeNode<T> current  = root;

        while (current != null) {
            if (current.left == null) {
                list.add(current.item);
                current = current.right;
            } else {
                TreeNode<T> predecessor = current.left;
                /*
                 * found the in-order predecessor.
                 */
                while (predecessor.right != null && predecessor.right != current) {
                    predecessor = predecessor.right;
                }

                if (predecessor.right == null) {
                    // hook it up.
                    predecessor.right = current;
                    current = current.left;
                } else {
                    list.add(current.item);
                    predecessor.right = null;
                    current  = current.right;
                }
            }
        }
        return list;
    }
}

public class MorrisInOrderTest {

    @Test
    public void testBalancedTree() throws NoSuchAlgorithmException {
        final MorrisInOrder<Integer> morrisInOrder1 = new MorrisInOrder<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        assertEquals(Arrays.asList(4, 2, 5, 1, 6, 3, 7), morrisInOrder1.inOrder());
    }

    @Test
    public void testUnBalancedTree() throws NoSuchAlgorithmException {
        final MorrisInOrder<Integer> morrisInOrder2 = new MorrisInOrder<Integer>(Arrays.asList(1, 2, 3, 4, 5, null, null));
        assertEquals(Arrays.asList(4, 2, 5, 1, 3), morrisInOrder2.inOrder());
    }
}


texts:
For classifying error reports, I need to generate an ID from an exception. That ID should be

(more or less) unique
a short alpha numeric string
equal for equivalent exceptions (even on different systems)

The following code seems to do the job:

    public static string GetExceptionID(this Exception ex)
    {
        if (ex == null) return "0000";

        int hash = 31;
        var innerException = ex;
        while (innerException != null)
        {
            hash ^= GetHash(innerException.GetType().ToString());

            hash ^= innerException.StackTrace
                                  .Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                                  // If *.pdb file is provided, the file and line no. (e.g. "... in C:\Path...") is part of the stacktrace.
                                  // The next line cutting off that part
                                  .Select(line => line.Substring(0, line.IndexOf(" in ") < 0 ? line.Length : line.IndexOf(" in ")))
                                  .Aggregate(31, (currentHash, val) => currentHash ^= val.GetHash());

            innerException = innerException.InnerException;
        }

        return Convert.ToBase64String(BitConverter.GetBytes(hash))
            .Replace('+', 'P')
            .Replace('-', 'M')
            .Replace("=", "")
            .ToUpper();
    }

    // https://en.wikipedia.org/wiki/Jenkins_hash_function
    private static int GetHash(this string str)
    {
        if (str == null) return 1;

        int hash = 31;
        foreach (char c in str)
        {
            unchecked
            {
                hash += c;
                hash += hash << 10;
                hash ^= hash >> 6;
            }
        }

        hash += hash << 3;
        hash ^= hash >> 11;
        hash += hash << 15;

        return hash;
    }

Do you see any problems with the code?


texts:
I am building a web service that gets data via Stored Procedures from a db and provides the result as JSON. The solution is built as a MVC 4 Web API project. I have to retrieve the data via Stored Procedures for several reasons (security, SQLAnywhere db, etc).

It is a relatively small scale project so I have opted for not defining a Model in the Web Service layer to save work (and possibly performance). There will likely be models in the front end application (which will be a MVC 4 Web Application).

The reasons why I am including an extra layer in the form of a Web Service is to a) add extra security, and b) that there will likely be a iPhone app for part of the application which then can utilize the same web service as the site.

It is working as I want it to, so what I want feedback on is

What do you think of the general approach to build a MVC 4 Web API solution without explicit models?
Do you have any comments on how to improve the details of the implementation?

One potential thought I have had is to skip the dataset and make a direct call to the Stored Procedure and loop over a datareader, which could potentially be faster. The other potential change is to loop over the datatable and build up the JSON manually instead of using the serializer.

What I like about the current solution is that it can be done on very few lines of code and that I do not have to manually name each JSON object since it is inherited from the datatable within the dataset.

I define a dataset called dsProducts that is loaded with a TableAdapter.

    // GET api/products
    public string Get()
    {

        string result = "";

        dsProductTableAdapters.GetProductsTableAdapter taTemp = new dsProductsTableAdapters.GetProductsTableAdapter();
        dsProducts dsTemp = new dsProducts();

        try {
            taTemp.Fill(dsTemp.GetProducts);
            result = jsonHelper.convertJSONString(dsTemp.GetProducts);
        } catch (Exception ex) {
            result = "{\"error\":\"1\"}";
        }

        return result;

    }

The convertJSONString and its help functions are defined as:

    public static string convertJSONString(DataTable table)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(table.ToDictionary());
    }

    static Dictionary<string, object> ToDictionary(this DataTable dt)
    {
        return new Dictionary<string, object> {
            { dt.TableName, dt.convertTableToDictionary() }};
    }

    static object convertTableToDictionary(this DataTable dt)
    {
        var columns = dt.Columns.Cast<DataColumn>().ToArray();
        return dt.Rows.Cast<DataRow>().Select(r => columns.ToDictionary(c => c.ColumnName, c => r[c]));
    }


texts: Reduce the redundancy in my pandas highlight function

texts:
After a lot of browsing and experimenting I have managed to achieve to read excel file as a Dataframe, apply some style to it and export it to html. My main concern is that the highlight_max function looks a bit redundant. The rows I want to highlight are already predetermined and are not just simply minimum or maximum. I tried to do it with list comprehension but it did not work. Is it possible to return the style value with just one line?

import pandas as pd

def highlight_max(s):
    truth = []
    for i in (df.index):
        truth.append(i in [634, 636, 638, 640, 642, 644, 648, 649, 650, 651, 656])
    return ['background-color: yellow' if v else '' for v in truth]

df = pd.read_excel('N:\Temp\filename.xlsx', index_col=False)
df.reset_index(drop=True, inplace=True)
html = df.style.set_table_styles([{'selector': 'th,td', 'props': [('border-style','solid'),
('border-width','1px')]}]).apply(highlight_max).hide_index().render(index=False)
with open('N://temp//test.html', 'w') as f:
    f.write(html)


texts:
I have the following piece of code:

for (var i = 0, len = legend.allItems.length; i < len; i++) {
    (function (i) {
        var item = legend.allItems[i].legendItem;

        item.on('mouseover', function (e) {
            var posLeft = 0,
            posTop = 0,
            parentWidth = chart.chartWidth;

            var html = '' +
                MetricsTooltips.get(chart.series[i].options.tooltipKey) +
            '';

            labelElement = chart.renderer.label(html, posLeft, posTop, 'callout', null, null, true, false, 'legend-tooltip').attr({zIndex: 10}).add();

            if(legend.group.alignOptions.align == 'center') {
                // _legendItemPos[0] returns the offset (left) for current legend item
                posLeft = legend.group.translateX + legend.allItems[i]._legendItemPos[0];
                // Subtract some "offset" as we don't want tooltips to overlap the legend
                posTop = legend.group.translateY - 30;

                // Make sure that tooltip won't overflow its parent
                if ((legend.allItems[i]._legendItemPos[0] + labelElement.width) > parentWidth) {
                    posLeft = parentWidth - labelElement.width;
                }

                labelElement.destroy();
            } else if (legend.group.alignOptions.align == 'right') {
                posTop = (legend.group.translateY + legend.allItems[i]._legendItemPos[1]);
                posLeft = (parentWidth - legend.group.alignOptions.width) - labelElement.width;

                if(legend.scrollGroup.translateY && legend.currentPage > 1) {
                    // Handle the case when legend group have too many metrics and paging appears in
                    posTop -= Math.abs(legend.scrollGroup.translateY);
                }

                labelElement.destroy();
            } else {
                // handle this if needed
            }

            labelElement = chart.renderer.label(html, posLeft, posTop, 'callout', null, null, true, false, 'legend-tooltip').css({zIndex: 10}).add();

        }).on('mouseout', function (e) {
            labelElement.destroy();
        });
    })(i);
}

Basically, it attach event listeners on all legend items when chart is loaded (the for is located inside onload callback), and later, when mouseenter event occurs, we display simple "tooltip" to the user.

It's working very well, but I'm looking for some refactoring hints.


texts:
[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 am building a layer of abstraction on top of the raw REST API for JavaScript Developers. I already use jQuery in the project, so I am using $.ajax(). I feel like I have arrived at a good pattern, but I'm not absolutely certain.

var ta = ta || {};

$.ajaxSetup({
  cache: false
});

ta.api = {
  heartbeat: function(successCallback, errorCallback) {
    var callType = "heartbeat";
    // if no custom handlers are provided, wire up the default callbacks or blank callback methods
    successCallback = ta.utils.setDefaultIfNeeded(successCallback, ta.callbacks[callType].success);
    errorCallback = ta.utils.setDefaultIfNeeded(errorCallback, ta.callbacks[callType].error);

    var url = '/rs/heartbeat';

    $.ajax({
      url: url,
      success: function(data) {
        successCallback(data);
      },
      error: function(xhr) {
        errorCallback(xhr);
      }
    });
  },
  version: function(successCallback, errorCallback) {
    var callType = "version";
    // if no custom handlers are provided, wire up the default callbacks or blank callback methods
    successCallback = ta.utils.setDefaultIfNeeded(successCallback, ta.callbacks[callType].success);
    errorCallback = ta.utils.setDefaultIfNeeded(errorCallback, ta.callbacks[callType].error);

    var url = '/rs/version';

    $.ajax({
      url: url,
      success: function(data) {
        successCallback(data);
      },
      error: function(xhr) {
        errorCallback(xhr);
      }
    });
  }
}

ta.utils = {
  setDefaultIfNeeded: function (providedHandler, defaultHandler) {
    var checkedHandler = providedHandler;
    if (typeof (providedHandler !== "undefined")) {
      if (typeof (providedHandler) !== "function") {
        if (typeof (defaultHandler) === "function") {
          checkedHandler = defaultHandler;
        } else {
          checkedHandler = function () { /* intentionally empty */ };
        }
      }
    } else {
      checkedHandler = function () {  /* intentionally empty */ };
    }
    return checkedHandler;
  }
};

So, the API can accept success and error handlers on a per-call basis. The setDefaultIfNeeded will do a few pieces of logic, but one of those pieces is an optional phase of using handlers from a callback object. So the callback object is optional, but it's a handy place to store and organize callbacks:

ta.callbacks = {
  heartbeat: {
    success: function(data) { console.log(data) },
    error: function(xhr) { console.log(xhr.statusText) }
  },
  version: {
    success: function(data) { console.log(data) },
    error: function(xhr) { console.log(xhr.statusText) }
  }
}

Another addition I plan to make but haven't tested yet is to have the functions return the jqXhr. It's already being made, so why not return it? But I haven't tested that yet so I didn't want to provide sample code that might be broken.

So, there are now a few options for using the API, depending on your needs:

Make calls to ta.api methods and supply success and error handlers as needed. I.e. you would define them in the methods that ultimately call the REST API.
Make void calls to ta.api, but the success and error handlers are supplied in the ta.callbacks object.
You can still continue to make calls to the REST service with whatever other arbitrary methods you choose.
*planned - define a variable against ta.api which becomes a jqXhr. You then have full access to the XHR and can do with it as you please.

I have a suspicion that some of you will recommend deferred/promises API, and I am not against it. But if I'm being honest, I can't visualize a strong way to encapsulate the various moving parts and have them extremely readable for other devs.


texts: Lagrange Interpolation over quadrilateral points

texts:
I've been working on a program which calculates, given a point and 4 surrounding points, the Lagrange polynomial, in order to interpolate a value. Consider that I'm not a mathematician and I better understand code than formulas.

I've came up with the following code, which works, but I really don't think is general (and it's pretty ugly to me).

using System;
using System.Collections.Generic;
using System.Linq;

namespace LagrangeInterpolation
{
    public class Point : ICloneable
    {
        public double X { get; set; }

        public double Y { get; set; }

        public double Value { get; set; }

        public Point Clone()
        {
            return (Point)this.MemberwiseClone();
        }
    }

    public static class Lagrange
    {
        public static Point Interpolate(Point[] controlPoints, Point point)
        {
            var A = -controlPoints[0].X - controlPoints[1].X + controlPoints[2].X + controlPoints[3].X;
            var B = -controlPoints[0].X + controlPoints[1].X + controlPoints[2].X - controlPoints[3].X;
            var C = +controlPoints[0].X - controlPoints[1].X + controlPoints[2].X - controlPoints[3].X;
            var X = 4 * point.X - controlPoints.Sum(x => x.X);

            var D = -controlPoints[0].Y - controlPoints[1].Y + controlPoints[2].Y + controlPoints[3].Y;
            var E = -controlPoints[0].Y + controlPoints[1].Y + controlPoints[2].Y - controlPoints[3].Y;
            var F = +controlPoints[0].Y - controlPoints[1].Y + controlPoints[2].Y - controlPoints[3].Y;
            var Y = 4 * point.Y - controlPoints.Sum(x => x.Y);

            var r = (X / 4 - B * Y / 4 * E) / (1 - D / 4 * E);
            var s = (Y - D * r) / E;

            var prevR = 0d;
            var prevS = 0d;
            const double precision = 0.00000001;
            while (!(prevR - r < precision && prevS - s < precision))
            {
                prevR = r;
                prevS = s;
                r = (X - B * s) / (A + C * s);
                s = (Y - D * r) / (E + F * r);
            }

            // Interpolate value
            var result = point.Clone();
            result.Value = ((1 - r) * (1 - s) * controlPoints[0].Value + (1 - r) * (1 + s) * controlPoints[1].Value + (1 + r) * (1 + s) * controlPoints[2].Value + (1 + r) * (1 - s) * controlPoints[3].Value) / 4;

            return result;
        }
    }
}

The input parameters are:

controlPoints: the 4 points, each one with its Value.
point: the point for which we want to calculate the interpolated value

The returned Point is a clone of the Input point with the Value property set.
Every instance of Point have X and Y normalised within range -1..1 (I subtract the quadrilateral center from each point).

Example:

controlPoints = new [] {
    new Point() { X = -0.033675000000000566, Y = -0.02564999999999884, Value = 1.2787 },
    new Point() { X = -0.035524999999999807, Y = 0.024329999999999075, Value = 1.329 },
    new Point() { X = 0.03370499999999943, Y = 0.02564999999999884, Value = 1.3376 },
    new Point() { X = 0.035494999999999166, Y = -0.024329999999999075, Value = 1.302 }
}

point = new Point() { X = 0.018148174616284152, Y = -0.014201699949808244 }

Expected result is Point.Value = 1.3044829106888913

Can someone suggest a better way (formally and mathematically) to perform this calculation?


texts:
Trying to generate fractals image with given IFS equations. I have two classes:

Shape - Gives co-ordinate to form a shape.
Ifs - Takes the given IFS equations and generates a fractal image.

Code:
ifs.py
class Shape:
    @staticmethod
    def square():
        x1 = np.concatenate(
            (
                np.linspace(0, 1, 100),
                np.ones(100),
                np.linspace(0, 1, 100),
                np.zeros(100),
            )
        )
        y1 = np.concatenate(
            (
                np.zeros(100),
                np.linspace(0, 1, 100),
                np.ones(100),
                np.linspace(0, 1, 100),
            )
        )
        return x1, y1

    @staticmethod
    def triangle():
        x1 = np.concatenate(
            (
                np.linspace(0, 1, 100),
                np.linspace(1, 0.5, 100),
                np.linspace(0.5, 0, 100),
            )
        )
        y1 = np.concatenate(
            (np.zeros(100), np.linspace(0, 1, 100), np.linspace(1, 0, 100))
        )
        return x1, y1

    @staticmethod
    def line():
        x1 = np.linspace(0, 1, 100)
        y1 = np.zeros(100)
        return x1, y1

class Ifs:
    def __init__(self):
        self._equationList = []

    def AddEquations(self, EqnLst):
        for eqn in EqnLst:
            *coef, e, f = eqn
            self._equationList.append((np.array(coef), np.array([e, f])))

    def __str__(self):
        out = ""
        for idx, (coef, intercept) in enumerate(self._equationList, 1):
            a, b, c, d = coef
            e, f = intercept
            out = (
                out
                + f"""equation = {idx}: [[a = {a} b = {b}]   [e = {e}
               [c = {c} d = {d}]]   f = {f}]\n\n"""
            )
        return out

    def deterministic(self, shape=Shape.square(), iterations=6):
        arr = np.column_stack(shape)
        for i in range(iterations):
            allEquations = []
            for coef, intercept in self._equationList:
                coef_ = coef.reshape(-1, 2)
                transformed_arr = (coef_ * arr[:, None]).sum(
                    axis=2
                ) + intercept[None, :]
                allEquations.append(transformed_arr)
            arr = np.vstack(allEquations)
        self.Values = arr
        return arr

    def plot(self):
        x, y = zip(*self.Values)
        plt.scatter(x, y, 1)
        plt.show()

Sample run:
I have given equations of Sierpinski Gasket

python3 ifs.py for what it's worth, this is how I run my code.

i = Ifs()

# There are 6 values in each equation a, b, c, d, e and f.
# where [a, b, c, d] is called coef
#[e, f] is called intercept

lst = [
       [ 0.5, 0, 0, 0.5, 0, 0],
       [0.5, 0, 0, 0.5, 0.5, 0],
       [0.5, 0, 0, 0.5, 0, 0.5]
      ]

i.AddEquations(lst)
i.deterministic(Shape.triangle())
i.plot()
print(i)

Output to console:
equation = 1: [[a = 0.5 b = 0.0]   [e = 0
               [c = 0.0 d = 0.5]]   f = 0]

equation = 2: [[a = 0.5 b = 0.0]   [e = 0.5
               [c = 0.0 d = 0.5]]   f = 0.0]

equation = 3: [[a = 0.5 b = 0.0]   [e = 0.0
               [c = 0.0 d = 0.5]]   f = 0.5]

Image of fractal generated:

I feel there's a lot of room to improve this code. I looking for suggestions to improve the Ifs class be it a way of storing equations or improving deterministic function. Shape is written by another user I might not have the power to change it but I can put forward your valuable suggestions to the author.


texts: Passing variable pointer as string to another function

texts:
With Delphi 7 I need to create a TStream variable and use/free it in another part of the code. Unfortunately it cannot be passed as "normal" parameter.

I created a simple application for testing what I need, using some examples I found on Google and some help from SOF (I am not used to pointers).

Here is what I got so far (it uses an Edit, a Memo e 3 Buttons):

function IsObject(Address: Pointer): Boolean; assembler;
asm
  MOV     EAX, [Address]
  CMP     EAX, EAX.vmtSelfPtr
  JNZ     @False
  MOV     Result, True
  JMP     @Exit
@False:
  MOV     Result, False
@Exit:
end;

procedure TForm1.btnSetMem1Click(Sender: TObject);
var
  Stm: TStream;
begin
  Stm := TMemoryStream.Create;
  edtMemID1.Text := IntToStr(Integer(Stm));
end;

procedure TForm1.btnSaveMem1Click(Sender: TObject);
var
  Stm: TStream;
begin
  Stm := Pointer(StrToInt(edtMemID1.Text));
  if IsObject(Stm) then
  try
    memStm1.Lines.SaveToStream(Stm);
    btnSaveMem1.Enabled := False;
    btnLoadMem1.Enabled := True;
    memStm1.Clear;
  except
    FreeAndNil(Stm);
  end;
end;

procedure TForm1.btnLoadMem1Click(Sender: TObject);
var
  Stm: TStream;
begin
  Stm := Pointer(StrToInt(edtMemID1.Text));
  if IsObject(Stm) then
  try
    Stm.Position := 0;
    memStm1.Lines.LoadFromStream(Stm);
  except
    FreeAndNil(Stm);
  end;
end;

procedure TForm1.btnFreeMem1Click(Sender: TObject);
var
  Stm: TStream;
begin
  Stm := Pointer(StrToInt(edtMemID1.Text));
  if IsObject(Stm) then FreeAndNil(Stm);
  btnSaveMem1.Enabled := False;
  btnLoadMem1.Enabled := False;
  edtMemID1.Clear;
end;

procedure TForm1.edtMemID1Change(Sender: TObject);
begin
  btnSaveMem1.Enabled := (Trim(edtMemID1.Text) <> '');
  btnFreeMem1.Enabled := (Trim(edtMemID1.Text) <> '');
end;

The ASM function I found here and seems to be working. I also tested with FastMM and there is no memory leak (if btnFreeMem is used).

Please review this code and maybe give some tips to make it better or avoid problems (memory leaks).


texts: Finding an equilibrium of an index of an array

texts:
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. P is an index of an array A.

Input:

A[0] = -1
A[1] =  3
A[2] = -4
A[3] =  5
A[4] =  1
A[5] = -6
A[6] =  2
A[7] =  1

Output:

1
3
7

1 is an equilibrium index of this array, because:

A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]

3 is an equilibrium index of this array, because:

A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]

7 is also an equilibrium index, because:

A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0

My solution for review:

def isEquilibrium(alist, ind):
    listLen = len(alist)
    left = getSum(0, ind, alist)
    right = getSum(ind+1, listLen, alist)
    # print left, right
    if left == right:
        return True

def getSum(start, end, lis):
    tot = 0
    for i in xrange(start, end):
        tot = tot + lis[i]
    return tot

def solution(alist):
    for i in xrange(0, len(alist)):
        result = isEquilibrium(alist, i)
        if(result):
            print i

solution([-1,3,-4,5,1,-6,2,1])


texts: An algorithm that finds the number of "lined up columns"

texts:
I found this question in an old exam in computer science. I solved it in a good way, but I'm not convinced that my solution is the best solution. I believe that there's a better way to solve it.

  Given N Columns that are lined up, The horizontal distance
  between two adjacent columns (The lower edges) is exactly 1 meter. The
  columns heights are different, and they can only be positive integers
  (In meters). Let's call a Pair of columns (not necessarily adjacent)
  "A Good Pair" if the imaginary line that connects their upper edges creates a gradient of 45 degrees relatively with the ground. The
  slope can go from Left to Right, or from Right to Left. I have to
  write an algorithm that will count all the "Good Pairs" of columns
  that exist. Notice that 1 column could participate in more than 1
  "Good Pair".

  The algorithm must be written in the most efficient way, and have the
  best performance (The less Run-Time possible).

  It's input:

  N, Which represents the number of columns, 5 < N < 500,000 followed by a list of N positive integers that
  represent the heights of the columns, as the 1st number in the list is
  the 1st column's height and the 2nd is for the 2nd column, and so on.
  The algorithm has to print the number of "Good Pairs" that exist
  in the list.

  Example:

  N = 6, and the list of numbers: 3, 5, 5, 3, 4, 1. (The most left number represents the 1st columns height).

  The algorithm should print 5 because there are 5

  "Good Pairs":

  Column 1 and column 3
  Column 2 and column 4
  Column 2 and column 6
  Column 4 and column 5
  Column 4 and column 6

Here's my solution:

static void Main(string[] args)
{
    int n, count = 0; int[] heightList;
    Console.WriteLine("Enter the number of columns");
    n = int.Parse(Console.ReadLine());
    heightList = new int[n];

    Console.WriteLine("Enter the list of heights");
    for (int i = 0; i < heightList.Length; i++)
    {
        heightList[i] = int.Parse(Console.ReadLine());
    }

    for (int i = 0; i < heightList.Length; i++)
    {
        for (int j = i+1; j < heightList.Length; j++)
        {
            //Checking if the pair creates a gradient of 45 degrees with the ground.
            if (Math.Abs(heightList[j] - heightList[i]) == Math.Abs(j - i))
            {
                count++;
            }
        }
    }

    Console.WriteLine(count);
    Console.ReadLine();
}

Is there any better way to solve this question?


texts:
I implemented an algorithm to find the modular multiplicative inverse of an integer. The code works, but it is too slow and I don't know why. I compared it with an algorithm I found in Rosetta Code, which is longer but way faster.

My implementation:

def modinv1(a, c)
  raise "#{a} and #{c} are not coprime" unless a.gcd(c) == 1
  0.upto(c - 1).map { |b| (a * b) % c }.index(1)
end

Rosetta Code's implementation:

  def modinv2(a, m) # compute a^-1 mod m if possible
  raise "NO INVERSE - #{a} and #{m} not coprime" unless a.gcd(m) == 1
  return m if m == 1
  m0, inv, x0 = m, 1, 0
  while a > 1
    inv -= (a / m) * x0
    a, m = m, a % m
    inv, x0 = x0, inv
  end
  inv += m0 if inv < 0
  inv
end

Benchmark results (used benchmark-ips):

Warming up --------------------------------------
        Rosetta Code   141.248k i/100ms
                Mine   462.000  i/100ms
Calculating -------------------------------------
        Rosetta Code      2.179M (± 6.5%) i/s -     10.876M in   5.022459s
                Mine      4.667k (± 3.7%) i/s -     23.562k in   5.055259s

Comparison:
        Rosetta Code:  2179237.4 i/s
                Mine:     4667.4 i/s - 466.90x  slower

Why is mine so slow? Should I use the one I found in Rosetta Code?


texts: Core-data object with relationships conforming protocol in swift

texts:
I have a situation where I have to use protocol to be conformed by NSManagedObject which has relationships with other entities.

My protocol is like:

protocol Account {
  var accountId: String { get }
  var isValidAccount: Bool { get }
}

Here is that entity:

class AccountMO: NSManagedObject {
  @NSManaged var uid: String!
  @NSManaged var anotherEntity: AnotherEntity?

  private (set) var storedMOC: NSManagedObjectContext!
  override var managedObjectContext: NSManagedObjectContext? {
    return storedMOC
  }

  override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
    super.init(entity: entity, insertInto: context)
    storedMOC = context!
  }
  init(moc:NSManagedObjectContext) {
    //I'm using this method to init AccountMO
    let mEntity = NSEntityDescription.entity(forEntityName: "Account", in: moc)
    super.init(entity: mEntity!, insertInto: moc)
  }
  func addAnotherEntity() {
    //this method creates AnotherEntity
    //and this method will be called after particular event has happened
  }
}

Extension which is conforming protocol:

extension AccountMO: Account {

  var accountId: String {
    return uid!
  }
  var isValidAccount: Bool {
    return anotherEntity != nil
  }
}

Whenever I want Account properties, I uses DB interface to fetch and return AccountMO as:

class DBInterface {
  //initialization methods
  var mainThreadMOC: NSManagedObjectContext?

  func createNewAccount(uid: String) {
    //create and save account to database
  }
  func getAccount() -> Account {
    //this method abstracts database implementations from outside classes
   //in future if I wanted to replace core-data by another database, I've to change this method only
    let privMOC = privateMOC()//this is child of mainThreadMOC
    let accountMO = fetchAccountEntity(moc: privMOC)
    return accountMO as Account
  }
}

This works fine!

But what I felt is storedMOC in AccountMO is something odd man out!
If I don't store MOC in AccountMO object, then it crashes on

return anotherEntity != nil

this line.
Apparently this is caused because AccountMO looses it's managedObjectContext once returned from getAccount() method.

So, to prevent AccountMO from losing it's managedObjectContext I've added that extra property to it.

Please feel free to tear this implementation down if needed!


texts: Find Index of SINGLE odd / even number in array

texts:
So I was doing some challenges on codewars.com and came across the following challenge (I managed to close the browser so could not submit my answer and therefore could not see the best possible solutions).

Given an array of at least 3 integers, all the elements in the array are either even or oneven EXCEPT for 1 element -->

[2, 4, 0, 100, 4, 11, 2602, 36]

OR:

[160, 3, 1719, 19, 11, 13, -21]

All the elements are either even or oneven except for one where it is the other way around. Return the element that is the odd one out, so:

findOutlier([2, 4, 0, 100, 4, 11, 2602, 36]) //should return 11

findOutlier([160, 3, 1719, 19, 11, 13, -21]) //should return 160

I got a working solution but there has to be a better way of doing this.. My solution:

function findOutlier(integers){
  let evenCount = 0;
  let oddCount = 0;
  for(let i = 0; i < integers.length; i++) {
    if(integers[i] % 2 === 0) {
      evenCount += 1;
    } else {
      oddCount += 1
    }
  }
  let idx = integers.find(function(index) {
    if(evenCount > 2) {
      return index % 2 === 1
    } else {
      return index % 2 === 0
    }
  })
  return idx
}

```


texts: Finding the nth Fibonacci number using recursive technique

texts:
EDIT

So I've been working on this according to the challenge @PeterTaylor gave me. I'm not very good at math, so I've been doing a lot of reading and found this link on the Binet form. Fibonacci algorithms

Unfortunately, when I use this in Ruby, it typically returns Infinity above 1000 or so for n. It works well for smaller equations, but not so much for very large numbers.

Here is the code I wrote for it.

a = (1 + Math.sqrt(5))/2

b = (1 - Math.sqrt(5))/2
#here, n == 5
f = ((a**5) - (b**5))/(a-b)

When you round f.to_i, it returns 5.

Back to the drawing board.

Original post below

Practicing recursion some more, and I'm wondering if this is the proper solution for this exercise I'm doing.

First, my code in Ruby:

def fibonacci(num, fact=[1,1])
  x = fact[fact.length-1]
  y = fact[fact.length-2]
  if fact[num-1]
    return fact[num-1]
  else
    fibonacci(num, fact.push(x+y))
  end
end

p fibonacci(5)
p fibonacci(12) == 144
p fibonacci(20) == 6765
p fibonacci(8200)

The exercise is this: Write a recursive method that computes the nth Fibonacci number, where nth is an argument to the method.

So, the 12th fibonacci number (which would be fact[11] due to indexing) is 144.

I know that I am returning the correct number, and that the recursion stops once fact[num-1] returns true. I can't help but feel that this is not the best way to do this, or even the proper way to do this.

Thoughts? Any advice?


texts: Counting subtrees where all nodes have the same value

texts:
A unival tree (which stands for "universal value") is a tree where all
  nodes under it have the same value.

  Given the root to a binary tree, count the number of unival subtrees.

  For example, the following tree has 5 unival subtrees:

   0
  / \
 1   0
    / \
   1   0
  / \
 1   1

class DailyCodingProblem8 {

    public static void main(String args[]) {

        BinaryTree tree = new BinaryTree();
        tree.root = new Node(0);
        tree.root.left = new Node(1);
        tree.root.right = new Node(0);
        tree.root.right.left = new Node(1);
        tree.root.right.right = new Node(0);
        tree.root.right.left.left = new Node(1);
        tree.root.right.left.right = new Node(1);
        int res = tree.countUnivalTrees(tree.root);
        System.out.println(res);

        /*
              5
             / \
            4   5
           / \   \
          4   4   5

        */

        tree = new BinaryTree();
        tree.root = new Node(5);
        tree.root.left = new Node(4);
        tree.root.right = new Node(5);
        tree.root.left.left= new Node(4);
        tree.root.left.right= new Node(4);
        tree.root.right.right = new Node(5);
        res = tree.countUnivalTrees(tree.root);
        System.out.println(res);

    }

}

class Node {
    public int value;
    public Node left, right;

    Node(int value) {
        this.value = value;
        this.left = this.right = null;
    }
}

class BinaryTree {
    Node root;

    int countUnivalTrees(Node root) {
        if (root == null) {
            return 0;
        }
        int count = countUnivalTrees(root.left) + countUnivalTrees(root.right);
        if (root.left != null && root.value != root.left.value) {
            return count;
        }

        if (root.right != null && root.value != root.right.value) {
            return count;
        }

        // if whole tree is unival tree
        return count + 1;
    }

}

What is the best way to supply binary tree as input? Should I be creating a insert  method and insert nodes? Will the interviewer feel that I am deviating from the actual problem if I do so?


texts: Can this coffeescripts method be simplified?

texts:
I'm new to coffeescripts. Can the getSum method be simplified more? Thanks

MyObject =
  checkCondition: (num) ->
    return true if num is 5

  getSum: (num) ->
    total = 0
    total += i for i in [1..num] when @checkCondition i
    total

I tried removing the last total but coffeescripts compiler goes nut :-/

Any help greatly appreciate.


texts: Am I multiplying two matrices together correctly?

texts:
I just wanted to know if I'm doing this right.  Note that all the matrices are int[16]s.

for (int i= 1; i <= 3; i++){
    for (int j= 1; j <= 3; j++){
        int sum = 0;
        for (int h = 1; h <= 3; h++){
           sum = sum + position[i*4+h]*projection[h*4+j];
        }

        modelview[i*4+j] = sum;
    }
}


texts: Word VBA Code to Automate Table Captioning

texts:
I have a Word VBA script that auto-generates a table caption based on user input & a previous heading. Its purpose is to speed up editing & formatting of massive software documents (like the 1000+ page test procedure I'm currently reviewing). At this point, it's slightly quicker than scrolling back up, copying the heading manually, creating a caption, and pasting it in, but it lags a little. So, I'm looking for advice on optimizing & speeding it up.

I should note that this is only for my use (which might be obvious by the less than serious user prompts) and that I'm a tech writer who dabbles in VBA,  rather than someone with a programming background.

Here's the script itself:

Sub TestTableCaption()

Dim strCaption As String
Dim intTableType As Integer
Dim strTableType As String

strTableType = InputBox("Enter 1 for Test Requirements Matrix, 2 for Test Status, or 3 for Test Steps")
intTableType = Val(strTableType)

Select Case intTableType

Case 1
    strTableType = "Test Requirements Matrix"

Case 2
    strTableType = "Test Status"
Case 3
    strTableType = "Test Steps"
Case Else
    strTableType = ""
    MsgBox ("Entry needs to be 1, 2, or 3. Learn to follow directions, then try again.")
    Exit Sub

End Select

strCaption = FindHeading("Heading 3") & " " & strTableType
strCaption = Replace(strCaption, vbCr, "")

strCaption = Replace(strCaption, Chr(150), "")
strCaption = Replace(strCaption, "  ", " ")
'In theory, Gets rid of dash from title. Doesn't actually work.

'MsgBox (strCaption)
Call GenerateCaption(strCaption, "Table")
End Sub

And here's the FindHeading function:

Function FindHeading(strHeadLevel As String) As String
'Gets the heading level as an input and finds the closest heading of that level before the selection.

Dim rngSelection As Range
'the initial selection

Dim rngPrev As Range
'The current paragraph to be evaluated.

Set rngSelection = Selection.Range

Set rngPrev = rngSelection.Previous(wdParagraph, 1)

'MsgBox (rngPrev.Text)

Do While rngPrev.Style <> strHeadLevel

    If ActiveDocument.Range(0, rngPrev.Paragraphs(1).Range.End).Paragraphs.Count > 1 Then

        Set rngPrev = rngPrev.Previous(wdParagraph, 1)
        'MsgBox ("rngPrev Style =  " & rngPrev.Style & vbCr & "Text = " & rngPrev.Text)
    Else

        'MsgBox ("Heading not found")
        Exit Do

    End If

Loop

If rngPrev.Style = strHeadLevel Then
    FindHeading = rngPrev.Paragraphs(1).Range.Text
Else
    FindHeading = "No heading found"
End If

End Function


texts: Unit test with Moq callback anonymous function

texts:
I have the following unit test that is testing predicate logic in a repository (Note: mockOpportunityRepository.Setup):

[Test]
public void GetFollowedByUserIdShouldGetTheUsersFollowedOpportunitiesFromOpportunityFollowRepositoryAndThenGetThoseFollowedOpportunities()
{
    const int ExpectedOpportunityId = 9;

    var testOpportunities = new List<Domain.EF.Opportunity>()
    {
        OpportunityBuilder.Default().WithId(1).Build(),
        OpportunityBuilder.Default().WithId(2).Build(),
        OpportunityBuilder.Default().WithId(ExpectedOpportunityId).Build(),
    };

    var actualOpportunities = new List<Opportunity>();

    var expectedOpportunityFollows = new List<OpportunityFollow> { new OpportunityFollow { OpportunityFollowId = 1, OpportunityId = ExpectedOpportunityId, UserId = UserId } };
    mockOpportunityFollowRepository.Setup(x => x.GetByUserId(UserId)).ReturnsAsync(expectedOpportunityFollows);

    mockOpportunityRepository.Setup(
        s =>
            s.GetAsync(
                It.IsAny<Expression<Func<Domain.EF.Opportunity, bool>>>(),
                It.IsAny<Func<IQueryable<Domain.EF.Opportunity>, IOrderedQueryable<Domain.EF.Opportunity>>>(),
                It.IsAny<int?>(),
                It.IsAny<int>()))
        .Callback<
            Expression<Func<Domain.EF.Opportunity, bool>>,
            Func<IQueryable<Domain.EF.Opportunity>,
            IOrderedQueryable<Domain.EF.Opportunity>>,
            int?,
            int>((queryParam, sortParam, takeParam, skipParam) =>
            {
                var func = queryParam.Compile();
                actualOpportunities = testOpportunities.Where(func).ToList();
            });

    var results = sut.GetFollowedByUserId(UserId);

    mockOpportunityFollowRepository.Verify(x => x.GetByUserId(UserId), Times.Once);
    actualOpportunities.Count.Should().Equals(1);
    actualOpportunities[0].OpportunityId.Should().Equals(ExpectedOpportunityId);
}

I have several tests like this all utilising the same bulky mockOpportunityRepository.Setup and wanted to refactor it into one re-useable place. Essentially the setup has a callback which runs an anonymous function. The anon function compiles the query parameters and executes them against a test list of opportunities. The outer test function needs the result of this filter to Assert the predicate logic.

If I try to move the mockOpportunityRepository.Setup into a separate function and try to output the actualOpportunities by reference I get a compiler error that ref and out parameters are not allowed in anonymous method body. I'm not very knowledgeable on functions and am sure it can be done.

Can anyone refactor this and suggest a way of moving the mockOpportunityRepository.Setup out of the test to make it reusable yet somehow get the results of the anonymous function (actualOpportunities) back to the calling test?


texts: Selecting data from a table based on value in another table (SQL server)

texts:
I am using the northwind example database  to brush up my SQL server skills.

I want to select all the products ordered by the customer with the customer id 'Folko'.

My idea is to join the Orders table with the OrderDetails table on OrderID and then join the Products table with the OrderDetails table on ProductID.
Then insert the WHERE clause (i.e. where Orders.CustomerID = 'FOLKO')

Here is the query:

select Products.ProductName from [Order Details]
inner join Orders on [Order Details].OrderID = Orders.OrderID
inner join Products on [Order Details].ProductID = Products.ProductID
where Orders.CustomerID = 'FOLKO'

I have also managed to get the same information with the following query:

select Products.ProductName from [Order Details], Orders, Products
where Products.ProductID = [Order Details].ProductID
and Orders.OrderID = [Order Details].OrderID
and Orders.CustomerID = 'FOLKO'

I am getting the result that I want but I wonder if these are the preferred ways (or if one or the other is better) or if it should be done in a different way altogether?


texts:
I have to protect really sensitive information and I have to do it both ways: encryption and decryption. How safe is it?

function encrypt($mprhase) {
     $MASTERKEY = "KEY PHRASE!";
     $td = mcrypt_module_open('tripledes', '', 'ecb', '');
     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     mcrypt_generic_init($td, $MASTERKEY, $iv);
     $crypted_value = mcrypt_generic($td, $mprhase);
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     return base64_encode($crypted_value);
}

function decrypt($mprhase) {
     $MASTERKEY = "KEY PHRASE!";
     $td = mcrypt_module_open('tripledes', '', 'ecb', '');
     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     mcrypt_generic_init($td, $MASTERKEY, $iv);
     $decrypted_value = mdecrypt_generic($td, base64_decode($mprhase));
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     return $decrypted_value;
}


texts:
I want to show how to interact with C from C++ and chose a simple and small library to demonstrate. zlib's gzopen, gzwrite and gzclose looked like a reasonably closed set of funtions.

Does anyone see anything fundamentally wrong with my presentaion? The main code I present here is in class GzWrite.

Intro section:

#include <string>
#include <vector>
#include <fstream> // ifstream
#include <stdexcept> // runtime_error
#include <iostream> // cerr
// C-Headers:
#include <zlib.h> // gzXyz; sudo aptitude install libz-dev
#include <string.h> // strerror
#include <errno.h> // errno
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
using std::ifstream; using std::ofstream; using std::string; using std::vector;
namespace {

constexpr size_t BLOCK_SZ = 256*1024;
constexpr int LEVEL = Z_DEFAULT_COMPRESSION;

Core class

struct GzWrite { // RAII-Wrapper
    gzFile gz_ ; // C-Struct aus zlib.h
    explicit GzWrite(const string& filename)
        : gz_{gzopen(filename.c_str(),"wb9")} // 'w': write, 'b':binary, '9':level
    {
        if(gz_==NULL) throw std::runtime_error(strerror(errno));
    }
    ~GzWrite() {
        gzclose(gz_);
    }
    int write(const char* data, size_t len) {
        return gzwrite(gz_, data, len);
    }
    GzWrite(const GzWrite&) = delete; // no copy
    GzWrite& operator=(const GzWrite&) = delete; // no assign
};

Helper functions

vector<char> read(const string& infn) {
    ifstream inf{ infn, ifstream::binary };
    if(!inf) throw std::runtime_error("open error");
    inf.seekg(0, inf.end); // go to end of file
    const auto laenge = inf.tellg(); // current pos is file size
    if(laenge > 1024*1024*1024) throw std::runtime_error("<1GB please");
    inf.seekg(0, inf.beg); // back to begin
    vector<char> data(laenge); // make room
    inf.read(data.data(), laenge); // read all at once
    return std::move(data); // make doubly sure data is not copied
}

void pack(const string& infn, const string& outfn) {
    vector<char> indata = read(infn); // read input
    GzWrite gz{outfn}; // init output
    auto res = gz.write(indata.data(), indata.size());
    if(res==0) throw std::runtime_error("write error");
}

} // namespace

Main function:

int main(int argc, const char* argv[]) {
    try {
        const vector<string> fnamen {argv+1, argv+argc};
        for(auto fname : fnamen) {
            std::cout << "packing " << fname << "... ";
            pack(fname, fname+".gz");
            std::cout << fname << ".gz"<< "\n";
        }
    } catch(std::runtime_error exc) {
        std::cerr << "Error: " << exc.what() << "\n";
    }
}


texts:
I have created canvas (800x400) - and filled it with a grid. It works but the rendering of the grid (lines) takes around 3 seconds, which seems excessively long. Am I doing something wrong?

var drawGrid = function(w, h, id) {
    var canvas = document.getElementById(id);
    var ctx = canvas.getContext('2d');
    ctx.canvas.width  = w;
    ctx.canvas.height = h;

    for (x=0;x<=w;x+=20) {
        for (y=0;y<=h;y+=20) {
            ctx.moveTo(x, 0);
            ctx.lineTo(x, h);
            ctx.stroke();
            ctx.moveTo(0, y);
            ctx.lineTo(w, y);
            ctx.stroke();
        }
    }

    };

    drawGrid(800, 400, "grid");
<canvas id="grid"></canvas>


texts: Copy directories while changing Unicode filenames to ASCII

texts:
I created a short Perl 6 script copyfnameascii.pl to copy a file hierarchy I have, applying an URL Decoding to the names of folders and removing non-ASCII characters from the names of files.

$ cd workingdirectory
$ perl6-m ../copyfnameascii.pl project copy

It is best illustrated by the following diagram:

                             $ tree
                             .
                             ├── copy
                             │   ├── folder 1
$ tree                       │   │   ├── cr.txt
.                            │   │   └── es.txt
└── project                  │   └── folder 2
    ├── folder%201           │       ├── ai.txt
    │   ├── čř.txt           │       └── zy.txt
    │   └── ěš.txt   ~*>     └── project
    └── folder%202               ├── folder%201
        ├── áí.txt               │   ├── čř.txt
        └── žý.txt               │   └── ěš.txt
                                 └── folder%202
                                     ├── áí.txt
                                     └── žý.txt

I just started using Perl. I'd like to hear your advice how to make the code generally better; more readable, idiomatic, and so on. The script does work; there is just a few things I am not satisfied with.

use Inline::Perl5;
my $p5 = Inline::Perl5.new;
$p5.use('Text::Unidecode');

sub transformdirname($dirname is copy) {
  $dirname.=subst( /:i \%(<[0..9A..F]>**2) /, { chr(:16(~$0)) }, :g ); # undo URL encoding
  $dirname.=subst( /\//, '_', :g ); # make it a valid UNIX filename
  return $dirname;
}

sub transformfilename($filename) {
  return $p5.call('Text::Unidecode::unidecode', $filename); # make it ASCII at all costs
}

sub MAIN($fromdir, $todir) {
  for dir($fromdir) -> $subdir {
    unless $subdir ~~ :d {
      next;
    }
    my $tosubdir = $todir ~ '/' ~ transformdirname($subdir.basename);
    say $tosubdir;
    mkdir($tosubdir);
    for dir($subdir) -> $file {
      my $tofile = $tosubdir ~ '/' ~ transformfilename($file.basename);
      if $tofile.path ~~ :e {
        die("Will not overwrite $tofile");
      }
      copy($file, $tofile);
    }
  }
}


texts:
What is the most efficient and productive way to cut each N symbol from a string?
For instance,

n = 5;
str = '1234A1234B1234C';
result: "123412341234"

This is my approach:
def delete_each_n(str, n)
  i = n

  str.length/n.times do
    str.slice!(i-1)
    i += (n - 1)
  end

  str
end


texts:
I created a solution for the car pooling algorithm.
Problem:
You are driving a vehicle that has capacity empty seats initially available for passengers.  The vehicle only drives east (ie. it cannot turn around and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off.  The locations are given as the number of kilometers due east from your vehicle's initial location.
Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false

Example 2:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true

My solution:
var carPooling = function(trips, capacity) {
    if(!trips || trips.length === 0)    return true;

    trips.sort((a,b) => a[1]-b[1]);
    let dropOff = new Map();
    let seated = 0;
    while(trips.length > 0) {
        const trip = trips.shift();
        const pickup = trip[1];
        for(const [key, value] of dropOff) {
            if(key <= pickup) {
                seated -= value;
                dropOff.delete(key);
            }
        }
        if(seated + trip[0] > capacity)
            return false;
        seated += trip[0];
        if(!dropOff.has(trip[2]))
            dropOff.set(trip[2], trip[0]);
        else
            dropOff.set(trip[2], dropOff.get(trip[2]) + trip[0]);
    }

    return true;
};

Is the time complexity O(N^2logN)? I sort the input array which gives me O(NlogN). Then, I have a nested loop N^2? I'm not sure about this nested loop because it is a loop inside my hash table.
By the way, do you guys have any idea about how to get a better performance?


texts:
I have an HTML table representing a database table and a sidebar which holds different anchors ready to perform CRUD operations on click.

Because the hrefs in the anchors aren't general valid for all columns I have written a script which automatically inserts the id of a selected column into the hrefs:

/localhost/image/var/edit => /localhost/image/4/edit

The code I have written works but it isn't very clean and smart.  Could somebody take a look and say where I have space of improvement?

<script type="text/javascript" src="{{ asset('bundles/acme/js/jquery.js'></script>
<script type="text/javascript">
$('table tr').click(function(){
    $('.selected').removeClass('selected');
    $(this).addClass('selected');
    var name = $(this).find('td:nth-child(2)').html();

    $('.image_bar ul li a').each(function(){
        var oldUrl = $(this).attr('href');
        var newUrl = oldUrl.replace('var', name);
        $(this).attr('href', newUrl);
    });
});
</script>


texts: Quicksort implementation with pivotal calculated as middle element

texts:
I read quick sort algorhitm and implemented in like this:

public List<Integer> sort(List<Integer> list) {
    if (list.size() <= 1) {
        return list;
    }

    int pivotalValue = list.get(list.size() / 2);

    List<Integer> left = new ArrayList<>();
    List<Integer> pivotalValues = new ArrayList<>();
    List<Integer> right = new ArrayList<>();
    for (Integer element : list) {
        if (element < pivotalValue) {
            left.add(element);
        } else if (element > pivotalValue) {
            right.add(element);
        } else {
            pivotalValues.add(element);
        }
    }
    List<Integer> sortedLeft = sort(left);
    List<Integer> sortedRight = sort(right);
    sortedLeft.addAll(pivotalValues);
    sortedLeft.addAll(sortedRight);
    return sortedLeft;

}

What do you think about my implementation?


texts: Simple Chaining Implementation of HashMap

texts:
I'm practicing writing my own simple version of a Java HashMap. I don't have much experience with generics in Java.

public class HashMap<K, V> {
    private class Entry<K, V> {
      private K key;
      private V value;
      private Entry next;

      Entry(K key, V value) {
            this.key = key;
            this.value = value;
      }

      public K getKey() {
            return key;
      }

      public V getValue() {
            return value;
      }
    }

    private final static int TABLE_SIZE = 32;
    private Entry[] table;

    public HashMap() {
          table = new Entry[TABLE_SIZE];
    }

    private int hash(K key) {
        return Math.abs(key.hashCode() % TABLE_SIZE);
    }

    public V get(K key) {
        int index = hash(key);
        Entry curr = table[index];
        while (curr != null) {
            if (curr.getKey().equals(key)) {
                return (V) curr.getValue();
            }
            curr = curr.next;
        }
        return null;
    }

    public V remove(K key) {
        int hash = hash(key);
        Entry curr = table[hash];
        if (curr == null) {
            return null;
        }
        if (curr.getKey().equals(key)) {
            V temp = (V) curr.getValue();
            table[hash] = curr.next;
            return temp;
        }
        while (curr.next != null) {
            if (curr.next.getKey().equals(key)) {
                V temp = (V) curr.next.getValue();
                curr.next = curr.next.next;
                return temp;
            }
        }
        return null;
    }

    public void put(K key, V value) {
        int hash = hash(key);
        Entry curr = table[hash];
        if (curr == null) {
            table[hash(key)] = new Entry(key, value);
        } else {
            while (curr.next != null) {
                curr = curr.next;
            }
            curr.next = new Entry(key, value);
        }
    }
}


texts:
I was given 15 minutes to write the code to reverse a singly-linked list.

What do you think of the code style here?

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LinkedListQuestions
{
    [TestClass]
    public class ReverseLinkedList
    {
        [TestMethod]
        public void ReservseLinkedListTest()
        {
            Node<int> head = new Node<int>();
            Node<int> two = new Node<int>();
            Node<int> three = new Node<int>();
            Node<int> four = new Node<int>();
            head.Value = 1;
            head.Next = two;
            two.Value = 2;
            two.Next = three;
            three.Value = 3;
            three.Next = four;
            four.Value = 4;
            LinkedListHandler.Reserve(ref head);
            Assert.AreEqual(4, head.Value);
            Assert.AreEqual(3, head.Next.Value);
            Assert.AreEqual(2, head.Next.Next.Value);
            Assert.AreEqual(1, head.Next.Next.Next.Value);
        }
    }

    public class LinkedListHandler
    {
        public static void Reserve(ref Node<int> head)
        {
            Node<int> current = head;
            Node<int> previous = null;
            while (current != null)
            {
                Node<int> temp = current.Next;
                current.Next = previous;
                previous = current;
                current = temp;
            }
            head = previous;
        }
    }

    public class Node<T>
    {
        public T Value { get; set; }
        public Node<T> Next { get; set; }
    }
}