<commit_before>
"use strict";

import ListController from './controllers/ListController';
import Navigation from './services/Navigation';
import Authentication from './services/Authentication';
import Language from './services/Language';
import Report from './services/Report';
import './directives/angular';
import './components/angular';
import 'ng-lollipop';

angular.module('monad.ng', ['ng', 'ngRoute', 'ngSanitize', 'ngAnimate', 'ngResource']);
angular.module('monad.externals', ['gettext', 'ui.bootstrap', 'lollipop']);
angular.module('monad', ['monad.ng', 'monad.externals', 'monad.directives', 'monad.components', 'monad.templates'])
    // No HTML5 mode please
    .config(['$locationProvider', $locationProvider => {
        $locationProvider.html5Mode(false);
    }])
    // Bare bones routing
    .config(['$routeProvider', $routeProvider => {
        $routeProvider.
            when('/', {
                template: '<noop></noop>',
                controller: ['moLanguage', '$location', (moLanguage, $location) => {
                    $location.path('/' + moLanguage.current + '/');
                }]
            }).
            when('/:language/', {
                templateUrl: '/monad/templates/home.html'
            });
    }])
    // Set defaults (these can/should be overridden)
    .run(['$rootScope', $rootScope => {
        $rootScope.languages = ['en', 'nl'];
        $rootScope.title = 'Default generic administrator';
        $rootScope.liveReload = undefined;
    }])
    // Set default language
    .run(['$rootScope', 'moLanguage', ($rootScope, moLanguage) => {
        moLanguage.current = $rootScope.languages[0];
        $rootScope.Language = moLanguage;
    }])
    // Register route reset handler
    .run(['$rootScope', '$route', '$cacheFactory', ($rootScope, $route, $cacheFactory) => {
        $route.reset = () => {
            let caches = $cacheFactory.info();
            for (let cache in caches) {
                if (cache == 'templates') {
                    continue;
                }
                $cacheFactory.get(cache).removeAll();
            }
            $route.reload();
            $rootScope.$broadcast('monad:reset');
        };
    }])
    // Register navigation service
    .run(['$rootScope', 'moNavigation', ($rootScope, moNavigation) => {
        $rootScope.Navigation = moNavigation;
    }])
    // Initialize session
    .run(['$rootScope', 'Authentication', ($rootScope, Authentication) => {
        $rootScope.$on('$routeChangeStart', () => Authentication['status']());//.then(() => Navigation.clear()));
        $rootScope.Authentication = Authentication;
    }])
    // Normalize HTTP data using ng-lollipop
    .run(['normalizeIncomingHttpData', 'postRegularForm', (a, b) => {}])

    // Extend default $resource service with save method on queried array.
    // In Monad, we want to be able to easily append a new item to an array of
    // queried resources. This exposes a `save` method on the array.
    .factory('moResource', ['$resource', $resource => {
        return (url, paramDefaults = {}, actions = {}, options = {}) => {
            let res = $resource(url, paramDefaults, actions, options);
            let query = res.query;
            res.query = (parameters, success, error) => {
                let found = query.call(res, parameters, success, error);
                found.save = function (data, success, error) {
                    return res.save({}, data, success, error);
                };
                return found;
            };
            return res;
        };
    }])

    // Default controllers
    .controller('moListController', ListController)

    .service('moNavigation', Navigation)
    .service('Authentication', Authentication)
    .service('moLanguage', Language)
    .service('moReport', Report)
    ;

<commit_msg>revive our models<commit_after>
"use strict";

import ListController from './controllers/ListController';
import Navigation from './services/Navigation';
import Authentication from './services/Authentication';
import Language from './services/Language';
import Report from './services/Report';
import './directives/angular';
import './components/angular';
import 'ng-lollipop';
import Model from './classes/Model';

angular.module('monad.ng', ['ng', 'ngRoute', 'ngSanitize', 'ngAnimate', 'ngResource']);
angular.module('monad.externals', ['gettext', 'ui.bootstrap', 'lollipop']);
angular.module('monad', ['monad.ng', 'monad.externals', 'monad.directives', 'monad.components', 'monad.templates'])
    // No HTML5 mode please
    .config(['$locationProvider', $locationProvider => {
        $locationProvider.html5Mode(false);
    }])
    // Bare bones routing
    .config(['$routeProvider', $routeProvider => {
        $routeProvider.
            when('/', {
                template: '<noop></noop>',
                controller: ['moLanguage', '$location', (moLanguage, $location) => {
                    $location.path('/' + moLanguage.current + '/');
                }]
            }).
            when('/:language/', {
                templateUrl: '/monad/templates/home.html'
            });
    }])
    // Set defaults (these can/should be overridden)
    .run(['$rootScope', $rootScope => {
        $rootScope.languages = ['en', 'nl'];
        $rootScope.title = 'Default generic administrator';
        $rootScope.liveReload = undefined;
    }])
    // Set default language
    .run(['$rootScope', 'moLanguage', ($rootScope, moLanguage) => {
        moLanguage.current = $rootScope.languages[0];
        $rootScope.Language = moLanguage;
    }])
    // Register route reset handler
    .run(['$rootScope', '$route', '$cacheFactory', ($rootScope, $route, $cacheFactory) => {
        $route.reset = () => {
            let caches = $cacheFactory.info();
            for (let cache in caches) {
                if (cache == 'templates') {
                    continue;
                }
                $cacheFactory.get(cache).removeAll();
            }
            $route.reload();
            $rootScope.$broadcast('monad:reset');
        };
    }])
    // Register navigation service
    .run(['$rootScope', 'moNavigation', ($rootScope, moNavigation) => {
        $rootScope.Navigation = moNavigation;
    }])
    // Initialize session
    .run(['$rootScope', 'Authentication', ($rootScope, Authentication) => {
        $rootScope.$on('$routeChangeStart', () => Authentication['status']());//.then(() => Navigation.clear()));
        $rootScope.Authentication = Authentication;
    }])
    // Normalize HTTP data using ng-lollipop
    .run(['normalizeIncomingHttpData', 'postRegularForm', (a, b) => {}])

    // Extend default $resource service with save method on queried array.
    // In Monad, we want to be able to easily append a new item to an array of
    // queried resources. This exposes a `save` method on the array.
    .factory('moResource', ['$resource', $resource => {
        return (url, paramDefaults = {}, actions = {}, options = {}) => {
            let res = $resource(url, paramDefaults, actions, options);
            let query = res.query;
            let get = res.get;
            res.query = (parameters, success, error) => {
                let found = query.call(res, parameters, success, error);
                found.save = function (data, success, error) {
                    return res.save({}, data, success, error);
                };
                found.$promise.then(() => {
                    found.map((item, i) => found[i] = new Model(item));
                    return found;
                });
                return found;
            };
            res.get = (parameters, success, error) => {
                let found = get.call(res, parameters, success, error);
                return new Model(found);
            };
            return res;
        };
    }])

    // Default controllers
    .controller('moListController', ListController)

    .service('moNavigation', Navigation)
    .service('Authentication', Authentication)
    .service('moLanguage', Language)
    .service('moReport', Report)
    ;

<|endoftext|>


<commit_before>function selectElementsStartingWithA(n) {
  var array = [];
  for (var i = 0; i < n.length; i++) {
    var a = n[i].split('');
    if (a[0] == 'a') {
      array.push(n[i]);
    }
  }
  return array;
}

function selectElementsStartingWithAVowel(vowel) {
  array = [];
  volArr = ['a', 'e', 'i', 'o', 'u']

  for (var i = 0; i < vowel.length; i++) {
    var a = vowel[i].split('');
    for (var j = 0; j < volArr.length; j++) {
      if (a[0] === volArr[j]) {
        array.push(vowel[i]);
      }
    }
  }
  return array;
}

function removeNullsFromArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] === null) array.splice(i, 2);
  }
  return array;
}

function removeNilsAndFalseFromAnArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] == null || array[i] == false) array.splice(i, 3);
  }
  return array;
}

function reverseElementsInArray(array) {
  var arr = []
  for (var i = 0; i < array.length; i++) {
    var a = array[i].split("").reverse().join("");
    arr.push(a);
  }
  return arr;
}

function allElementsExceptFirstThree(array) {
  return array.splice(-4);
}

function addElementsToBeginningOfArray(array) {
  array.unshift(1);
  return array
}

function sortWordsByLastLetter(array) {
  var arr = [];
  var arrTwo = [];

  for (var i = 0; i < array.length; i++) {
    var a = array[i].split("").reverse().join("");
    arr.push(a);
    arr.sort();
  }

  for (var j = 0; j < arr.length; j++) {
    var b = arr[j].split("").reverse().join("");
    arrTwo.push(b);
  }
  return arrTwo;
}

function getFirstHalfOfString(string) {
  var a = string.match(/[a-zA-Z]/g).length;
  var b = Math.round(a / 2);
  return string.substr(0, b);
}

function makeNumberNegative(a) {
  return Math.abs(a);
}

function separateNumbersIntoEvenAndOdd(array) {
  var evens = []
  var odds = []
  for (var i = 0; i < array.length; i++) {
    if ((array[i] % 2) === 1) {
      odds.push(array[i]);
    } else {
      evens.push(array[i]);
    }
  }
  return ([evens, odds]);

}

function countNumberOfPalindromes(array) {

}

function shortestWordInArray() {
  // code here
}

function longestWordInArray() {
  // code here
}

function totalOfNumbers(arr) {
  var i = arr.length;
  var sum = 0;
  while (--i) sum += arr[i];
  return arr;
}

function doubleArray() {
  // code here
}

function getElementsUntilGreaterThanFive() {
  // code here
}

function getAllLetters() {
  // code here
}

function removeCapitaLetters() {
  // code here
}

function roundUp(number) {

}

function roundDown(number) {

}

function formatDateNicely() {
  // code here
}

function getDomainName() {
  // code here
}

function titleizeString() {
  // code here
}

function getSquareRoot(number) {

}
<commit_msg>countNumberOfPalindromes<commit_after>function selectElementsStartingWithA(n) {
  var array = [];
  for (var i = 0; i < n.length; i++) {
    var a = n[i].split('');
    if (a[0] == 'a') {
      array.push(n[i]);
    }
  }
  return array;
}

function selectElementsStartingWithAVowel(vowel) {
  array = [];
  volArr = ['a', 'e', 'i', 'o', 'u']

  for (var i = 0; i < vowel.length; i++) {
    var a = vowel[i].split('');
    for (var j = 0; j < volArr.length; j++) {
      if (a[0] === volArr[j]) {
        array.push(vowel[i]);
      }
    }
  }
  return array;
}

function removeNullsFromArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] === null) array.splice(i, 2);
  }
  return array;
}

function removeNilsAndFalseFromAnArray(array) {
  for (var i = 0; i < array.length; i++) {
    if (array[i] == null || array[i] == false) array.splice(i, 3);
  }
  return array;
}

function reverseElementsInArray(array) {
  var arr = []
  for (var i = 0; i < array.length; i++) {
    var a = array[i].split("").reverse().join("");
    arr.push(a);
  }
  return arr;
}

function allElementsExceptFirstThree(array) {
  return array.splice(-4);
}

function addElementsToBeginningOfArray(array) {
  array.unshift(1);
  return array
}

function sortWordsByLastLetter(array) {
  var arr = [];
  var arrTwo = [];

  for (var i = 0; i < array.length; i++) {
    var a = array[i].split("").reverse().join("");
    arr.push(a);
    arr.sort();
  }

  for (var j = 0; j < arr.length; j++) {
    var b = arr[j].split("").reverse().join("");
    arrTwo.push(b);
  }
  return arrTwo;
}

function getFirstHalfOfString(string) {
  var a = string.match(/[a-zA-Z]/g).length;
  var b = Math.round(a / 2);
  return string.substr(0, b);
}

function makeNumberNegative(a) {
  return Math.abs(a);
}

function separateNumbersIntoEvenAndOdd(array) {
  var evens = []
  var odds = []
  for (var i = 0; i < array.length; i++) {
    if ((array[i] % 2) === 1) {
      odds.push(array[i]);
    } else {
      evens.push(array[i]);
    }
  }
  return ([evens, odds]);

}

function countNumberOfPalindromes(array) {
  arr = []
  for (var i = 0; i < array.length; i++) {
    if (array[i] == array[i].split("").reverse().join("")) {
      arr.push(array[i]);
    }
  }
    return arr.length;
}

function shortestWordInArray() {
  // code here
}

function longestWordInArray() {
  // code here
}

function totalOfNumbers(arr) {
  var i = arr.length;
  var sum = 0;
  while (--i) sum += arr[i];
  return arr;
}

function doubleArray() {
  // code here
}

function getElementsUntilGreaterThanFive() {
  // code here
}

function getAllLetters() {
  // code here
}

function removeCapitaLetters() {
  // code here
}

function roundUp(number) {

}

function roundDown(number) {

}

function formatDateNicely() {
  // code here
}

function getDomainName() {
  // code here
}

function titleizeString() {
  // code here
}

function getSquareRoot(number) {

}
<|endoftext|>


<commit_before>// Hayoo returns separate results for definitions, modules, packages, and other search queries
// we will just show "functions" results for now (which means everything that isn't a module or a package)
// we also won't show any "did you mean..." stuff, because it's not generally that helpful
function ddg_spice_hayoo(res) {
  if (res['hits'] > 0) {
    var items = new Array();
    var item = new Array();

    // the individual function's json
    var info = res['functions'][0];

    // build some nice output
    var snippet = document.createElement('span');
    snippet.innerHTML += '' + info['name'] + ' :: ' + info['signature'] + '
'; // answer
    if (info['description'] != '') {
      // Hayoo uses scripts to fill empty  tags
      var description = info['description'].replace(//g,'');
      description = description.replace(/<\/a>/g,'');

      snippet.innerHTML += description;
    }

    // build item
    item['a'] = snippet;

    item['h'] = 'Hayoo - ' + info['module'] + '.' + info['name']; // title

    // build a link back to Hayoo, rather than Hackage - it's polite, and users rarely want exactly one result when searching by type
    item['s'] = 'Hayoo'; // source
    item['u'] = 'http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=' + info['name']; // url

    item['t'] = info['module'];

    // shove it in the array and print
    items[0] = item;
    nra(items, 1);
  } else {
    // no hits, no zero-click info
  }
}

<commit_msg>heuristic for finding the most relevant hayoo result, modulo bug in DDG.get_query()<commit_after>// Hayoo returns separate results for definitions, modules, packages, and other search queries
// we will just show "functions" results for now (which means everything that isn't a module or a package)
// we also won't show any "did you mean..." stuff, because it's not generally that helpful
function ddg_spice_hayoo(res) {
  if (res['hits'] > 0) {
    var items = new Array();
    var item = new Array();

    // the individual function's json
    var info = sort_functions(res['functions'])[0];

    // build some nice output
    var snippet = document.createElement('span');
    snippet.innerHTML += '' + info['name'] + ' :: ' + info['signature'] + '
'; // answer
    if (info['description'] != '') {
      // Hayoo uses scripts to fill empty  tags
      var description = info['description'].replace(//g,'');
      description = description.replace(/<\/a>/g,'');

      snippet.innerHTML += description;
    }

    // build item
    item['a'] = snippet;

    item['h'] = 'Hayoo - ' + info['module'] + '.' + info['name']; // title

    // build a link back to Hayoo, rather than Hackage - it's polite, and users rarely want exactly one result when searching by type
    item['s'] = 'Hayoo'; // source
    item['u'] = 'http://holumbus.fh-wedel.de/hayoo/hayoo.html?query=' + info['name']; // url

    item['t'] = info['module'];

    // shove it in the array and print
    items[0] = item;
    nra(items, 1);
  } else {
    // no hits, no zero-click info
  }
}

// sort the results to favor exact matches and standard library functions
// this should be done server-side, and will be when the maintainer of Hayoo replies back
function sort_functions(funcs) {
  var query = DDG.get_query();
  query = query.replace(/^hayoo\s+/i, '');

  // XXX BUG - when testing this with 'duckpan server', query is erroneously populated with the value 'duckduckhack-template-for-spice' - this string appears in many places in the generated js for a search
  // alert(query);

  for (var i in funcs) {
    var fun = funcs[i];
    var priority = 0;

    // favor exact matches, stuff that comes with any compiler, and a shortlist of good packages in the Haskell Platform
    if (fun['name'] == query) priority += 4;
    if (fun['package'] == 'base') priority += 2;
    if (fun['module'] == 'Prelude') priority += 1; // on top of the bonus of being in base
    if (fun['package'] == 'mtl') priority += 2;
    if (fun['package'] == 'transformers') priority += 1;
    if (fun['package'] == 'parallel') priority += 1;
    if (fun['package'] == 'array') priority += 1;
    if (fun['package'] == 'bytestring') priority += 1;
    if (fun['package'] == 'containers') priority += 1;
    if (fun['package'] == 'text') priority += 1;
    if (fun['package'] == 'time') priority += 1;
    if (fun['package'] == 'network') priority += 1;
    if (fun['package'] == 'old-locale') priority += 1;
    if (fun['package'] == 'random') priority += 1;
    if (fun['package'] == 'parsec') priority += 1;

    // don't favor GHC-specific stuff, because internals are scary
    // don't favor acme results, for obvious reasons
    // don't favor unix, because it's OS-specific
    // don't favor unsafe results
    if (fun['package'].match(/ghc/i)) priority -= 1;
    if (fun['package'].match(/acme/i)) priority -= 1;
    if (fun['package'].match(/unix/i)) priority -= 1;
    if (fun['name'].match(/unsafe/i)) priority -= 2;

    fun['priority'] = priority;
  }

  funcs = funcs.sort(function(a,b) {return b['priority'] - a['priority'];});

  return funcs;
}

<|endoftext|>


<commit_before>function ddg_spice_imdb(response) {

    if (!response['Response'] == 'True') return;

    var movie = [];
    var currentDate = new Date();
    var tempDate = response["Released"] != "N/A" ? new Date(response["Released"]) : "";
    movie.runtime = response["Runtime"].replace(/\s/g, "").replace("min", "m");
    movie.runtime = movie.runtime === "N/A" ? "" : movie.runtime + ", ";

    // Is a release date planned?
    if (tempDate && tempDate > currentDate){
        movie.rating = "an upcoming ";
        movie.releaseDate = tempDate.toDateString().slice(4);
    }
    // Is it upcoming?
    else if (response["Year"] > currentDate.getFullYear())
        movie.rating = "an upcoming ";
    // It's already out.
    else if (response["Rated"] === "R" || response["Rated"] === "NC-17" || response["Rated"] === "N/A")
        movie.rating = "an ";
    // otherwise:
    else
        movie.rating = "a ";
    // No releaseDate? releaseDate = year
    movie.releaseDate = !movie.releaseDate ? response["Year"] : releaseDate;

    // Unrated?
    if (response["Rated"] === "N/A") response.rating += "Unrated";
    else movie.rating += response["Rated"];

    // Reviews?
    movie.reviews = (response['imdbRating'] != "N/A") ?
                        response['imdbRating']+"/10) " : "None) ";

    movie.title = response['Title'];
    movie.year = response['Year'];

    if (response['Actors'] && response['Actors'] != "N/A")
        movie.actors = response['Actors'];

    if (response["Director"] && response["Director"] != "N/A")
        movie.director = response['Director'];

    if (response["Plot"] && response["Plot"] != "N/A")
        movie.plot = response["Plot"];

    Spice.render({
        data              : movie,
        header1           : movie.title + " (IMDb)",
        source_url        : 'http://www.imdb.com/title/'
                            + response['imdbID'],
        source_name       : 'IMDb',
        template_normal   : 'imdb',
        image             : (response['Poster'] != 'N/A' ?
                                response['Poster'] : ''),
        force_big_header  : true,
        force_space_after : true,
        force_no_fold     : true,
    });
}
<commit_msg>make movie a hash not array for everyones sanity<commit_after>function ddg_spice_imdb(response) {

    if (!response['Response'] == 'True') return;

    var movie = {};
    var currentDate = new Date();
    var tempDate = response["Released"] != "N/A" ? new Date(response["Released"]) : "";
    movie.runtime = response["Runtime"].replace(/\s/g, "").replace("min", "m");
    movie.runtime = movie.runtime === "N/A" ? "" : movie.runtime + ", ";

    // Is a release date planned?
    if (tempDate && tempDate > currentDate){
        movie.rating = "an upcoming ";
        movie.releaseDate = tempDate.toDateString().slice(4);
    }
    // Is it upcoming?
    else if (response["Year"] > currentDate.getFullYear())
        movie.rating = "an upcoming ";
    // It's already out.
    else if (response["Rated"] === "R" || response["Rated"] === "NC-17" || response["Rated"] === "N/A")
        movie.rating = "an ";
    // otherwise:
    else
        movie.rating = "a ";
    // No releaseDate? releaseDate = year
    movie.releaseDate = !movie.releaseDate ? response["Year"] : releaseDate;

    // Unrated?
    if (response["Rated"] === "N/A") response.rating += "Unrated";
    else movie.rating += response["Rated"];

    // Reviews?
    movie.reviews = (response['imdbRating'] != "N/A") ?
                        response['imdbRating']+"/10) " : "None) ";

    movie.title = response['Title'];
    movie.year = response['Year'];

    if (response['Actors'] && response['Actors'] != "N/A")
        movie.actors = response['Actors'];

    if (response["Director"] && response["Director"] != "N/A")
        movie.director = response['Director'];

    if (response["Plot"] && response["Plot"] != "N/A")
        movie.plot = response["Plot"];

    Spice.render({
        data              : movie,
        header1           : movie.title + " (IMDb)",
        source_url        : 'http://www.imdb.com/title/'
                            + response['imdbID'],
        source_name       : 'IMDb',
        template_normal   : 'imdb',
        image             : (response['Poster'] != 'N/A' ?
                                response['Poster'] : ''),
        force_big_header  : true,
        force_space_after : true,
        force_no_fold     : true,
    });
}
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';

import Navigation from '~/shared/Navigation';
import Routes from '~/core/Router';

import * as actions from './actions';

const App = ({ history }): React$Element<*> => (

    <ConnectedRouter history={history}>

        <Navigation />
        <Routes />

    </ConnectedRouter>

    {/*  */}

);

export default connect(
  ({ app }) => ({ app }),
  dispatch => ({ actions: bindActionCreators(actions, dispatch) }),
)(App);
<commit_msg>334th Commit<commit_after>// @flow

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import CssBaseline from '@material-ui/core/CssBaseline';

import Navigation from '~/shared/Navigation';
import Routes from '~/core/Router';

import * as actions from './actions';

const App = ({ history }): React$Element<*> => (

    <React.Fragment>
      <CssBaseline />

      <ConnectedRouter history={history}>

          <Navigation />
          <Routes />

      </ConnectedRouter>
    </React.Fragment>

);

export default connect(
  ({ app }) => ({ app }),
  dispatch => ({ actions: bindActionCreators(actions, dispatch) }),
)(App);
<|endoftext|>


<commit_before>function ddg_spice_movie (api_result) {
    "use strict";

    if (api_result.total === 0) {
        return;
    }

    var ignore = ["movie", "film", "rotten", "rating", "rt", "tomatoes", "release date"];
    var result, max_score = 0;

    // Assign a ranking value for the movie. This isn't a complete sorting value though
    // also we are blindling assuming these values exist
    var score = function(m) {
        var s = m.ratings.critics_score * m.ratings.audience_score;
        if (s > max_score) max_score = s;
        // If any above are undefined, s is undefined.
        return s;
    };

    // returns the more relevant of the two movies
    var better = function(currentbest, next) {
        // If score() returns undefined, this is false, so we're still OK.
        return (score(next) > score(currentbest) &&
                (next.year < currentbest.year) &&
                DDG.isRelevant(next.title, ignore)) ? next : currentbest;
    };

    result = DDG_bestResult(api_result.movies, better);

    // Favor the first result if the max score is within 1% of the score for the first result.
    if (result !== api_result.movies[0] && Math.abs(score(api_result.movies[0]) - max_score) / max_score < 0.1) {
        result = api_result.movies[0];
    }

    // Check if the movie that we have is relevant enough.
    if(!DDG.isRelevant(result.title, ignore)) {
        return;
    }

    var checkYear = function(year) {
        if(year) {
            return " (" + year + ")";
        }
        return "";
    };

    if ((result.synopsis && result.synopsis.length) ||
        (result.critics_consensus && result.critics_consensus.length)) {
        result.hasContent = true;
    }

    Spice.render({
        data: result,
        source_name: 'Rotten Tomatoes',
        template_normal: "movie",
        template_small: "movie_small",
        force_no_fold: 1,
        source_url: result.links.alternate,
        header1: result.title + checkYear(result.year),
        image_url: result.posters.thumbnail.indexOf("poster_default.gif") === -1 ? result.posters.thumbnail : ""
    });
};

/*
 * rating_adjective
 *
 * help make the description of the movie gramatically correct
 * used in reference to the rating of the movie, as in
 *   'an' R rated movie, or
 *   'a'  PG rated movie
 */
Handlebars.registerHelper("rating_adjective", function() {
    return (this.mpaa_rating === "R"
         || this.mpaa_rating === "NC-17"
         || this.mpaa_rating === "Unrated") ?  "an" :"a";
});

/* star rating */
Handlebars.registerHelper("star_rating", function(score) {
    var r = (score / 20) - 1;
    var s = "";

    if (r > 0) {
        for (var i = 0; i < r; i++) {
            s += "★";
        }
    }

    if (s.length == 0) {
        s = "0 Stars";
    }

    return s;
});<commit_msg>Movie: Linted.<commit_after>function ddg_spice_movie (api_result) {
    "use strict";

    if (api_result.total === 0) {
        return;
    }

    var ignore = ["movie", "film", "rotten", "rating", "rt", "tomatoes", "release date"];
    var result, max_score = 0;

    // Assign a ranking value for the movie. This isn't a complete sorting value though
    // also we are blindling assuming these values exist
    var score = function(m) {
        var s = m.ratings.critics_score * m.ratings.audience_score;
        if (s > max_score) max_score = s;
        // If any above are undefined, s is undefined.
        return s;
    };

    // returns the more relevant of the two movies
    var better = function(currentbest, next) {
        // If score() returns undefined, this is false, so we're still OK.
        return (score(next) > score(currentbest) &&
                (next.year < currentbest.year) &&
                DDG.isRelevant(next.title, ignore)) ? next : currentbest;
    };

    result = DDG_bestResult(api_result.movies, better);

    // Favor the first result if the max score is within 1% of the score for the first result.
    if (result !== api_result.movies[0] && Math.abs(score(api_result.movies[0]) - max_score) / max_score < 0.1) {
        result = api_result.movies[0];
    }

    // Check if the movie that we have is relevant enough.
    if(!DDG.isRelevant(result.title, ignore)) {
        return;
    }

    var checkYear = function(year) {
        if(year) {
            return " (" + year + ")";
        }
        return "";
    };

    if ((result.synopsis && result.synopsis.length) ||
        (result.critics_consensus && result.critics_consensus.length)) {
        result.hasContent = true;
    }

    Spice.render({
        data: result,
        source_name: 'Rotten Tomatoes',
        template_normal: "movie",
        template_small: "movie_small",
        force_no_fold: 1,
        source_url: result.links.alternate,
        header1: result.title + checkYear(result.year),
        image_url: result.posters.thumbnail.indexOf("poster_default.gif") === -1 ? result.posters.thumbnail : ""
    });
}

/*
 * rating_adjective
 *
 * help make the description of the movie gramatically correct
 * used in reference to the rating of the movie, as in
 *   'an' R rated movie, or
 *   'a'  PG rated movie
 */
Handlebars.registerHelper("rating_adjective", function() {
    "use strict";

    return (this.mpaa_rating === "R" ||
            this.mpaa_rating === "NC-17" ||
            this.mpaa_rating === "Unrated") ?  "an" :"a";
});

/* star rating */
Handlebars.registerHelper("star_rating", function(score) {
    "use strict";

    var r = (score / 20) - 1;
    var s = "";

    if (r > 0) {
        for (var i = 0; i < r; i++) {
            s += "★";
        }
    }

    if (s.length === 0) {
        s = "0 Stars";
    }

    return s;
});<|endoftext|>


<commit_before>export default {
    'localAPI': 'localhost:8080/',
    'rootAPI': 'https://famous-places-api.herokuapp.com/api'
};
<commit_msg>Fix local api route<commit_after>export default {
    'localAPI': 'http://localhost:8080/api',
    'rootAPI': 'https://famous-places-api.herokuapp.com/api'
};
<|endoftext|>


<commit_before>/**
 * Created by Freddy Snijder on 15/05/14.
 */

(function() {
    var NS          = null;

    var document    = null;

    var __isNode    = (typeof module !== 'undefined' && typeof module.exports !== 'undefined');
    if (__isNode) {
        require("../extensions/string.ext.js");

        var jsdom       = require("jsdom");
        document        = jsdom.jsdom("");

        NS = exports;
    } else {
        //Add to Visionscapers namespace
        NS = window["__VI__"] || window;

        document        = window.document;
    }

    //using underscore.js _ as base object
    //changing and augmenting it where we want to
    NS.UtilsStrings = {};
    NS.UtilsStrings.addTo = function (utils, log) {

        if (log !== Object(log)) {
            console.warn("UtilsStrings : no logging object provided, using browser console logger");
            log = console;
        }

        if ((utils !== Object(utils)) && (typeof(utils) != "function")) {
            log.error("UtilsStrings", "No valid utils object given, not adding utils");
            return;
        }

        if ((utils._utilsComponents !== Object(utils._utilsComponents)) || (!utils._utilsComponents["base"])) {
            log.error("UtilsStrings", "This utils component needs the base utils component, not adding utils");
            return;
        }

        /**************************************************
         *
         * Register utils component
         *
         **************************************************/

            //Different util components are registered here
            //This allows us to check in a simple way if certain functionality is available
        utils._mustExist("_utilsComponents");
        if (utils.obj(utils._utilsComponents)) {
            utils._utilsComponents["strings"] = true;
        }

        /**************************************************
         *
         * END Register utils component
         *
         **************************************************/

        utils._mustNOTexist("eqStr");
        /**
         *
         * Checks if strings s1 and s2 are equal, case insensitive.
         * If that is the case, true is returned.
         *
         * if s1 or s2 is NOT a string or s1 or s2 is empty, false is returned
         *
         * @param {string} s1
         * @param {string} s2
         *
         * @returns {boolean}
         *
         */
        var eqStr = function(s1, s2) {
            if ((!utils.string(s1) || !utils.string(s2)) || (utils.empty(s1) || utils.empty(s2))) {
                return false;
            }

            return (s1.toLowerCase() == s2.toLowerCase());
        };
        utils.eqStr = utils.eqStr || eqStr;

        utils._mustNOTexist("joinPaths");
        /**
         *
         * Joins paths in the paths array, by ensuring that there are no double slashes at
         * the join positions
         *
         * @param {Array} paths
         *
         * @returns {String|null}
         *
         */
        var joinPaths = function (paths) {
            var me = "Utils::joinPaths";
            var concatenated = null;

            if (!utils.array(paths)) {
                _l.error(me, "Paths is not an array, unable to join paths");
                return concatenated;
            }

            var nextPath;
            var numPaths = paths.length;
            if (numPaths == 0) {
                concatenated = "";
            } else if (numPaths == 1) {
                concatenated = paths[0] + "";
            }

            if (utils.string(concatenated)) {
                return concatenated;
            }

            var __join = function (path1, path2) {
                path1 = path1 + "";
                path2 = path2 + "";

                var firstPathEndsWithSlash = (path1[path1.length - 1] == '/');
                var secondPathStartsWithSlash = (path2[0] == '/');

                if (!firstPathEndsWithSlash) {
                    path1 += '/';
                }

                if (secondPathStartsWithSlash) {
                    path2 = path2.slice(1);
                }

                return path1 + path2;
            };

            concatenated = paths[0];
            for (var idx = 1; idx < numPaths; idx++) {
                nextPath = paths[idx];

                concatenated = __join(concatenated, nextPath);
            }

            return concatenated;
        };
        utils.joinPaths = utils.joinPaths || joinPaths;

        utils._mustNOTexist("url");
        var URLPatternDev   = new RegExp('^(https?:\\/\\/)?' + // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
        '((\\d{1,3}\\.){3}\\d{1,3})|' + // OR ip (v4) address
        '(localhost))' + // OR 'localhost'
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
        '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator

        var URLPattern      = new RegExp('^(https?:\\/\\/)?' + // protocol
                '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
                '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
                '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
                '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
                '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator

        /**
         *
         * Returns true if given string is a valid URL, else false
         *
         * @param {String} str              string to be tested
         * @param {Boolean} [dev=false]     if dev is true 'localhost' is allowed as domain, else not
         *
         * @returns {boolean}
         *
         */
        var url = function (str, dev) {
            if (!utils.bool(dev)) {
                dev = false;
            }

            var pattern = dev ? URLPatternDev : URLPattern;

            return (pattern.test(str) === true);
        };
        utils.url = utils.url || url;

        utils._mustNOTexist("request");
        /**
         *
         * Get the request part from a URL. If no URL is given it tries to use the window.location.href
         *
         * @param url
         *
         */
        var request = function(url) {
            if (!utils.string(url) || utils.empty(url)) {
                if (typeof(window) === 'undefined') {
                    log.warn("utils::request", "No window object available, unable to get current URL.");
                    return null;
                }

                url = utils.get(window, "location.href") || "";
            }

            var a = document.createElement('a');
            a.href = url;

            /************************************************************
             *
             * IE11 FIX :-P
             *
             ***********************************************************/
            var host        = a.host || "";
            var colonIdx    = host.indexOf(":");
            if (colonIdx >= 0) {
                //With colon
                var port = host.substring(colonIdx);
                //Only when the port is not specified in the original URL
                if (url.indexOf(port) < 0) {
                    host = host.substring(0, colonIdx);
                }
            }
            /************************************************************
             *
             * END IE11 FIX
             *
             ***********************************************************/

            //protocol://host
            return url.substring(a.protocol.length + host.length + 2);
        };
        utils.request = utils.request || request;

        utils._mustNOTexist("URLQueryParams");
        /**
         *
         * Get the query parameters of a URL as an object with the query parameters as properties.
         * If no URL is given it tries to use the window.location.href.
         *
         * @param url
         *
         * @returns {object|null}
         *
         */
        var URLQueryParams = function(url) {
            var me = "utils::URLQueryParams";

            if (!utils.string(url) || utils.empty(url)) {
                if (typeof(window) === 'undefined') {
                    log.warn(me, "No window object available, unable to get current URL.");
                    return null;
                }

                url = utils.get(window, "location.href") || "";
            }

            var a = document.createElement('a');
            a.href = url;

            var queryParams     = {};

            var query           = decodeURIComponent(a.search.substring(1));
            if (_.empty(query)) {
                return queryParams;
            }

            var queryComponents = query.split('&');

            var keyValuePair    = null;
            for (var i = 0; i < queryComponents.length; i++) {
                keyValuePair = queryComponents[i].split('=');

                if (keyValuePair.length < 2) {
                    log.warn(me, "Invalid query key value pair, skipping : [{0}]".fmt(keyValuePair));
                    continue;
                }

                queryParams[keyValuePair[0]] = keyValuePair[1];
            }

            return queryParams;
        };
        utils.URLQueryParams = utils.URLQueryParams || URLQueryParams;

        utils._mustNOTexist("trim");
        //From https://github.com/visionmedia/superagent
        var trim = function (s) {
            if (utils.string(s)) {
                return s.replace(/(^\s*|\s*$)/g, '');
            } else {
                return null;
            }
        };
        utils.trim = utils.trim || trim;

        utils._mustNOTexist("capitaliseFirst");
        var capitaliseFirst = function (s) {
            if (!utils.string(s)) {
                return null;
            }

            return s.charAt(0).toUpperCase() + s.slice(1);
        };
        utils.capitaliseFirst = utils.capitaliseFirst || capitaliseFirst;

        utils._mustNOTexist("encoded");
        /**
         *
         * HTML entity encodes the string
         *
         * @param {String} s
         *
         * @returns {String|null}
         *
         */
        var encoded = function (s) {
            var encodedStr = null;

            if (!utils.string(s)) {
                return encodedStr;
            }

            //http://stackoverflow.com/a/18750001/889617
            var encodedStr = s.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
                return '&#' + i.charCodeAt(0) + ';';
            });

            return encodedStr;
        };
        utils.encoded = utils.encoded || encoded;

        String.prototype.endsWith = function(suffix) {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };

        utils._mustNOTexist("endsWith");
        /**
         *
         * Checks if string ends with string
         *
         * @param {String} s
         *
         * @returns {boolean}
         *
         */
        var endsWith = function(s, suffix) {
            if (!utils.string(s)) {
                return false;
            }

            return s.length >= suffix.length && s.substr(s.length - suffix.length) == suffix;
        };
        utils.endsWith = utils.endsWith || endsWith;

        utils._mustNOTexist("toBase64");
        /**
         *
         * Converts binary string to Base64 ASCII encoded string
         *
         * @param {string} data         string with binary data
         *
         * @returns {string | null}     If a problem occurred null is returned
         *
         */
        var toBase64 = function(data) {
            var data64 = null;

            if (!_.string(data)) {
                return data64;
            }

            if (!_.func(window.btoa)) {
                _l.error("Utils::toBase64", "btoa method not supported to encode as Base64");
                return data64;
            }

            return (data64 = window.btoa(data));
        };
        utils.toBase64 = utils.toBase64 || toBase64;

        utils._mustNOTexist("fromBase64");
        /**
         *
         * Converts Base64 ASCII encoded string to binary string
         *
         * @param {string} data64       string with Base64 ASCII encoded  data
         *
         * @returns {string | null}     If a problem occurred null is returned
         *
         */
        var fromBase64 = function(data64) {
            var data = null;

            if (!utils.string(data64)) {
                return data;
            }

            if (!utils.func(window.atob)) {
                log.error("Utils::fromBase64", "atob method not supported to decode Base64");
                return data;
            }

            return (data = window.atob(data64));
        };
        utils.fromBase64 = utils.fromBase64 || fromBase64;

        utils._mustNOTexist("insertBeforeLast");
        /**
         *
         * Places insert before last occurrence of string c in s
         * If the specified string c does not occur at all in s, string insert is placed at the end of s
         *
         * Example :
         * insertBeforeLast('.', '-original', 'test.x.jpg') returns "test.x-original.jpg"
         *
         * @param {string} c        Substring where to insert string 'insert' before
         * @param {string} insert   String to insert before last occurrence of c in s
         * @param {string} s        String to insert string 'insert' in to
         *
         * @returns {string|null}
         */
        var insertBeforeLast = function(c, insert, s) {
            var me          = "Utils::insertBeforeLast";
            var sInserted   = null;

            if (!utils.string(s)) {
                return sInserted;
            }

            if (!utils.string(insert)) {
                log.error(me, "insert is not a string, returning null");
                return sInserted;
            }

            if (!utils.string(c)) {
                return (sInserted = s+insert);
            }

            var idx = s.lastIndexOf(c);
            if (idx < 0) {
                sInserted = s+insert;
            } else {
                sInserted = s.substring(0, idx) + insert + s.substring(idx)
            }

            return sInserted;
        };
        utils.insertBeforeLast = utils.insertBeforeLast || insertBeforeLast;

        utils._mustNOTexist("stripScripts");
        /**
         *
         * Strip scripts from html string
         *
         * @param {string} html
         *
         * @returns {null | string}
         */
        function stripScripts(html) {
            if (!utils.string(html)) {
                return null;
            }

            if (utils.empty(html)) {
                return "";
            }

            var div = document.createElement('div');
            div.innerHTML = html;

            var scripts = div.getElementsByTagName('script');
            var i = scripts.length;
            while (i--) {
                scripts[i].parentNode.removeChild(scripts[i]);
            }

            return div.innerHTML;
        }
        utils.stripScripts = utils.stripScripts || stripScripts;

        utils._mustNOTexist("toText");
        /**
         *
         * Strip scripts from html string and convert in to plain text
         *
         * @param {string} html
         *
         * @returns {null | string}
         */
        function toText(html) {
            html = utils.stripScripts(html);

            if (!utils.string(html)) {
                return null;
            }

            if (utils.empty(html)) {
                return "";
            }

            var div = document.createElement('div');
            div.innerHTML = html;

            return div.textContent;
        }
        utils.toText = utils.toText || toText;

        utils._mustNOTexist("csvToArray");
        function csvToArray(string, separator) {
            if(!utils.def(separator)) {
                separator = ',';
            }
            var list    = utils.map(string.split(new RegExp('[/s]*'+separator+'[/s]*')), utils.trim);

            // Trimp empty items from start and end
            var firstItem = list[0];
            if(utils.empty(firstItem)) {
                list.shift();
            }
            var lastItem = list[list.length - 1];
            if (utils.empty(lastItem)) {
                list.pop();
            }

            return list;
        }
        utils.csvToArray = utils.csvToArray || csvToArray;

        utils._mustNOTexist("plural");
        function plural(string) {
            if(!utils.string(string)) {
                return "things";
            }

            // Covers some irregular plurals
            if(string.slice(-2) === 'us') {
                return string.slice(0, string.length-2) + 'i';
            }

            if(string.slice(-1) === 's') {
                return string + 'es';
            }

            return string + 's';
        }
        utils.plural = utils.plural || plural;

    };

})();<commit_msg>Fixed issue in csvToArray and added getFilenameFrom util<commit_after>/**
 * Created by Freddy Snijder on 15/05/14.
 */

(function() {
    var NS          = null;

    var document    = null;

    var __isNode    = (typeof module !== 'undefined' && typeof module.exports !== 'undefined');
    if (__isNode) {
        require("../extensions/string.ext.js");

        var jsdom       = require("jsdom");
        document        = jsdom.jsdom("");

        NS = exports;
    } else {
        //Add to Visionscapers namespace
        NS = window["__VI__"] || window;

        document        = window.document;
    }

    //using underscore.js _ as base object
    //changing and augmenting it where we want to
    NS.UtilsStrings = {};
    NS.UtilsStrings.addTo = function (utils, log) {

        if (log !== Object(log)) {
            console.warn("UtilsStrings : no logging object provided, using browser console logger");
            log = console;
        }

        if ((utils !== Object(utils)) && (typeof(utils) != "function")) {
            log.error("UtilsStrings", "No valid utils object given, not adding utils");
            return;
        }

        if ((utils._utilsComponents !== Object(utils._utilsComponents)) || (!utils._utilsComponents["base"])) {
            log.error("UtilsStrings", "This utils component needs the base utils component, not adding utils");
            return;
        }

        /**************************************************
         *
         * Register utils component
         *
         **************************************************/

            //Different util components are registered here
            //This allows us to check in a simple way if certain functionality is available
        utils._mustExist("_utilsComponents");
        if (utils.obj(utils._utilsComponents)) {
            utils._utilsComponents["strings"] = true;
        }

        /**************************************************
         *
         * END Register utils component
         *
         **************************************************/

        utils._mustNOTexist("eqStr");
        /**
         *
         * Checks if strings s1 and s2 are equal, case insensitive.
         * If that is the case, true is returned.
         *
         * if s1 or s2 is NOT a string or s1 or s2 is empty, false is returned
         *
         * @param {string} s1
         * @param {string} s2
         *
         * @returns {boolean}
         *
         */
        var eqStr = function(s1, s2) {
            if ((!utils.string(s1) || !utils.string(s2)) || (utils.empty(s1) || utils.empty(s2))) {
                return false;
            }

            return (s1.toLowerCase() == s2.toLowerCase());
        };
        utils.eqStr = utils.eqStr || eqStr;

        utils._mustNOTexist("joinPaths");
        /**
         *
         * Joins paths in the paths array, by ensuring that there are no double slashes at
         * the join positions
         *
         * @param {Array} paths
         *
         * @returns {String|null}
         *
         */
        var joinPaths = function (paths) {
            var me = "Utils::joinPaths";
            var concatenated = null;

            if (!utils.array(paths)) {
                _l.error(me, "Paths is not an array, unable to join paths");
                return concatenated;
            }

            var nextPath;
            var numPaths = paths.length;
            if (numPaths == 0) {
                concatenated = "";
            } else if (numPaths == 1) {
                concatenated = paths[0] + "";
            }

            if (utils.string(concatenated)) {
                return concatenated;
            }

            var __join = function (path1, path2) {
                path1 = path1 + "";
                path2 = path2 + "";

                var firstPathEndsWithSlash = (path1[path1.length - 1] == '/');
                var secondPathStartsWithSlash = (path2[0] == '/');

                if (!firstPathEndsWithSlash) {
                    path1 += '/';
                }

                if (secondPathStartsWithSlash) {
                    path2 = path2.slice(1);
                }

                return path1 + path2;
            };

            concatenated = paths[0];
            for (var idx = 1; idx < numPaths; idx++) {
                nextPath = paths[idx];

                concatenated = __join(concatenated, nextPath);
            }

            return concatenated;
        };
        utils.joinPaths = utils.joinPaths || joinPaths;

        utils._mustNOTexist("url");
        var URLPatternDev   = new RegExp('^(https?:\\/\\/)?' + // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
        '((\\d{1,3}\\.){3}\\d{1,3})|' + // OR ip (v4) address
        '(localhost))' + // OR 'localhost'
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
        '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator

        var URLPattern      = new RegExp('^(https?:\\/\\/)?' + // protocol
                '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
                '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
                '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
                '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
                '(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator

        /**
         *
         * Returns true if given string is a valid URL, else false
         *
         * @param {String} str              string to be tested
         * @param {Boolean} [dev=false]     if dev is true 'localhost' is allowed as domain, else not
         *
         * @returns {boolean}
         *
         */
        var url = function (str, dev) {
            if (!utils.bool(dev)) {
                dev = false;
            }

            var pattern = dev ? URLPatternDev : URLPattern;

            return (pattern.test(str) === true);
        };
        utils.url = utils.url || url;

        utils._mustNOTexist("request");
        /**
         *
         * Get the request part from a URL. If no URL is given it tries to use the window.location.href
         *
         * @param url
         *
         */
        var request = function(url) {
            if (!utils.string(url) || utils.empty(url)) {
                if (typeof(window) === 'undefined') {
                    log.warn("utils::request", "No window object available, unable to get current URL.");
                    return null;
                }

                url = utils.get(window, "location.href") || "";
            }

            var a = document.createElement('a');
            a.href = url;

            /************************************************************
             *
             * IE11 FIX :-P
             *
             ***********************************************************/
            var host        = a.host || "";
            var colonIdx    = host.indexOf(":");
            if (colonIdx >= 0) {
                //With colon
                var port = host.substring(colonIdx);
                //Only when the port is not specified in the original URL
                if (url.indexOf(port) < 0) {
                    host = host.substring(0, colonIdx);
                }
            }
            /************************************************************
             *
             * END IE11 FIX
             *
             ***********************************************************/

            //protocol://host
            return url.substring(a.protocol.length + host.length + 2);
        };
        utils.request = utils.request || request;

        utils._mustNOTexist("URLQueryParams");
        /**
         *
         * Get the query parameters of a URL as an object with the query parameters as properties.
         * If no URL is given it tries to use the window.location.href.
         *
         * @param url
         *
         * @returns {object|null}
         *
         */
        var URLQueryParams = function(url) {
            var me = "utils::URLQueryParams";

            if (!utils.string(url) || utils.empty(url)) {
                if (typeof(window) === 'undefined') {
                    log.warn(me, "No window object available, unable to get current URL.");
                    return null;
                }

                url = utils.get(window, "location.href") || "";
            }

            var a = document.createElement('a');
            a.href = url;

            var queryParams     = {};

            var query           = decodeURIComponent(a.search.substring(1));
            if (_.empty(query)) {
                return queryParams;
            }

            var queryComponents = query.split('&');

            var keyValuePair    = null;
            for (var i = 0; i < queryComponents.length; i++) {
                keyValuePair = queryComponents[i].split('=');

                if (keyValuePair.length < 2) {
                    log.warn(me, "Invalid query key value pair, skipping : [{0}]".fmt(keyValuePair));
                    continue;
                }

                queryParams[keyValuePair[0]] = keyValuePair[1];
            }

            return queryParams;
        };
        utils.URLQueryParams = utils.URLQueryParams || URLQueryParams;

        utils._mustNOTexist("trim");
        //From https://github.com/visionmedia/superagent
        var trim = function (s) {
            if (utils.string(s)) {
                return s.replace(/(^\s*|\s*$)/g, '');
            } else {
                return null;
            }
        };
        utils.trim = utils.trim || trim;

        utils._mustNOTexist("capitaliseFirst");
        var capitaliseFirst = function (s) {
            if (!utils.string(s)) {
                return null;
            }

            return s.charAt(0).toUpperCase() + s.slice(1);
        };
        utils.capitaliseFirst = utils.capitaliseFirst || capitaliseFirst;

        utils._mustNOTexist("encoded");
        /**
         *
         * HTML entity encodes the string
         *
         * @param {String} s
         *
         * @returns {String|null}
         *
         */
        var encoded = function (s) {
            var encodedStr = null;

            if (!utils.string(s)) {
                return encodedStr;
            }

            //http://stackoverflow.com/a/18750001/889617
            var encodedStr = s.replace(/[\u00A0-\u9999<>\&]/gim, function (i) {
                return '&#' + i.charCodeAt(0) + ';';
            });

            return encodedStr;
        };
        utils.encoded = utils.encoded || encoded;

        String.prototype.endsWith = function(suffix) {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };

        utils._mustNOTexist("endsWith");
        /**
         *
         * Checks if string ends with string
         *
         * @param {String} s
         *
         * @returns {boolean}
         *
         */
        var endsWith = function(s, suffix) {
            if (!utils.string(s)) {
                return false;
            }

            return s.length >= suffix.length && s.substr(s.length - suffix.length) == suffix;
        };
        utils.endsWith = utils.endsWith || endsWith;

        utils._mustNOTexist("toBase64");
        /**
         *
         * Converts binary string to Base64 ASCII encoded string
         *
         * @param {string} data         string with binary data
         *
         * @returns {string | null}     If a problem occurred null is returned
         *
         */
        var toBase64 = function(data) {
            var data64 = null;

            if (!_.string(data)) {
                return data64;
            }

            if (!_.func(window.btoa)) {
                _l.error("Utils::toBase64", "btoa method not supported to encode as Base64");
                return data64;
            }

            return (data64 = window.btoa(data));
        };
        utils.toBase64 = utils.toBase64 || toBase64;

        utils._mustNOTexist("fromBase64");
        /**
         *
         * Converts Base64 ASCII encoded string to binary string
         *
         * @param {string} data64       string with Base64 ASCII encoded  data
         *
         * @returns {string | null}     If a problem occurred null is returned
         *
         */
        var fromBase64 = function(data64) {
            var data = null;

            if (!utils.string(data64)) {
                return data;
            }

            if (!utils.func(window.atob)) {
                log.error("Utils::fromBase64", "atob method not supported to decode Base64");
                return data;
            }

            return (data = window.atob(data64));
        };
        utils.fromBase64 = utils.fromBase64 || fromBase64;

        utils._mustNOTexist("insertBeforeLast");
        /**
         *
         * Places insert before last occurrence of string c in s
         * If the specified string c does not occur at all in s, string insert is placed at the end of s
         *
         * Example :
         * insertBeforeLast('.', '-original', 'test.x.jpg') returns "test.x-original.jpg"
         *
         * @param {string} c        Substring where to insert string 'insert' before
         * @param {string} insert   String to insert before last occurrence of c in s
         * @param {string} s        String to insert string 'insert' in to
         *
         * @returns {string|null}
         */
        var insertBeforeLast = function(c, insert, s) {
            var me          = "Utils::insertBeforeLast";
            var sInserted   = null;

            if (!utils.string(s)) {
                return sInserted;
            }

            if (!utils.string(insert)) {
                log.error(me, "insert is not a string, returning null");
                return sInserted;
            }

            if (!utils.string(c)) {
                return (sInserted = s+insert);
            }

            var idx = s.lastIndexOf(c);
            if (idx < 0) {
                sInserted = s+insert;
            } else {
                sInserted = s.substring(0, idx) + insert + s.substring(idx)
            }

            return sInserted;
        };
        utils.insertBeforeLast = utils.insertBeforeLast || insertBeforeLast;

        utils._mustNOTexist("stripScripts");
        /**
         *
         * Strip scripts from html string
         *
         * @param {string} html
         *
         * @returns {null | string}
         */
        function stripScripts(html) {
            if (!utils.string(html)) {
                return null;
            }

            if (utils.empty(html)) {
                return "";
            }

            var div = document.createElement('div');
            div.innerHTML = html;

            var scripts = div.getElementsByTagName('script');
            var i = scripts.length;
            while (i--) {
                scripts[i].parentNode.removeChild(scripts[i]);
            }

            return div.innerHTML;
        }
        utils.stripScripts = utils.stripScripts || stripScripts;

        utils._mustNOTexist("toText");
        /**
         *
         * Strip scripts from html string and convert in to plain text
         *
         * @param {string} html
         *
         * @returns {null | string}
         */
        function toText(html) {
            html = utils.stripScripts(html);

            if (!utils.string(html)) {
                return null;
            }

            if (utils.empty(html)) {
                return "";
            }

            var div = document.createElement('div');
            div.innerHTML = html;

            return div.textContent;
        }
        utils.toText = utils.toText || toText;

        utils._mustNOTexist("csvToArray");
        function csvToArray(string, separator) {
            if (!utils.string(string)) {
                return null;
            }
            if(!utils.def(separator)) {
                separator = ',';
            }
            var list    = utils.map(string.split(new RegExp('[/s]*'+separator+'[/s]*')), utils.trim);

            // Trim empty items from start and end
            var firstItem = list[0];
            if(utils.empty(firstItem)) {
                list.shift();
            }
            var lastItem = list[list.length - 1];
            if (utils.empty(lastItem)) {
                list.pop();
            }

            return list;
        }
        utils.csvToArray = utils.csvToArray || csvToArray;

        utils._mustNOTexist("plural");
        function plural(string) {
            if(!utils.string(string)) {
                return "things";
            }

            // Covers some irregular plurals
            if(string.slice(-2) === 'us') {
                return string.slice(0, string.length-2) + 'i';
            }

            if(string.slice(-1) === 's') {
                return string + 'es';
            }

            return string + 's';
        }
        utils.plural = utils.plural || plural;

        utils._mustNOTexist("getFilenameFrom");
        function getFilenameFrom(path) {
            if (!utils.string(path)) {
                return null;
            }

            var lastSlashIndex = path.lastIndexOf("/");
            if (lastSlashIndex < 0) {
                return path;
            }

            return path.substr(lastSlashIndex+1);
        }
        utils.getFilenameFrom = utils.getFilenameFrom || getFilenameFrom;

    };

})();<|endoftext|>


<commit_before>'use strict';

const cluster = require('cluster');

/**
 * Raven client for logging errors and debugging events
 * @type {Raven}
 */
const Raven = require('raven');

/**
 * Bot class for interacting with discord and handling commands
 * @type {Genesis}
 */
const Genesis = require('./src/bot.js');

/**
 * Raven client instance for logging errors and debugging events
 */
const client = new Raven.Client(process.env.RAVEN_URL);

/**
 * Logging functions class
 * @type {Object}
 */
const Logger = require('./src/Logger.js');

const logger = new Logger(client);

/**
 * Class that manages the cluster's workers
 * @type {Function}
 */
const ClusterManager = require('./src/ClusterManager.js');

client.install();

client.on('error', (error) => {
  logger.error(`Could not report the following error to Sentry: ${error.message}`);
});

if (cluster.isMaster) {
  const localShards = process.env.LOCAL_SHARDS || 1;
  const shardOffset = process.env.SHARD_OFFSET || 0;

  const clusterManager = new ClusterManager(cluster, logger, localShards, shardOffset);
  clusterManager.start();
} else {
  const totalShards = parseInt(process.env.SHARDS) || 1;
  const shard = new Genesis(process.env.TOKEN, logger, {
    shardId: parseInt(process.env.shard_id),
    shardCount: totalShards,
    prefix: process.env.PREFIX,
    logger,
    owner: process.env.OWNER,
  });
  shard.start();
}
<commit_msg>Add radix to parseInt<commit_after>'use strict';

const cluster = require('cluster');

/**
 * Raven client for logging errors and debugging events
 * @type {Raven}
 */
const Raven = require('raven');

/**
 * Bot class for interacting with discord and handling commands
 * @type {Genesis}
 */
const Genesis = require('./src/bot.js');

/**
 * Raven client instance for logging errors and debugging events
 */
const client = new Raven.Client(process.env.RAVEN_URL);

/**
 * Logging functions class
 * @type {Object}
 */
const Logger = require('./src/Logger.js');

const logger = new Logger(client);

/**
 * Class that manages the cluster's workers
 * @type {Function}
 */
const ClusterManager = require('./src/ClusterManager.js');

client.install();

client.on('error', (error) => {
  logger.error(`Could not report the following error to Sentry: ${error.message}`);
});

if (cluster.isMaster) {
  const localShards = process.env.LOCAL_SHARDS || 1;
  const shardOffset = process.env.SHARD_OFFSET || 0;

  const clusterManager = new ClusterManager(cluster, logger, localShards, shardOffset);
  clusterManager.start();
} else {
  const totalShards = parseInt(process.env.SHARDS, 10) || 1;
  const shard = new Genesis(process.env.TOKEN, logger, {
    shardId: parseInt(process.env.shard_id, 10),
    shardCount: totalShards,
    prefix: process.env.PREFIX,
    logger,
    owner: process.env.OWNER,
  });
  shard.start();
}
<|endoftext|>


<commit_before>/*
 * Project Ariana
 * app.js
 *
 * This file contains the AppController, which controls the entire application.
 * It also contain the global configuration settings.
 *
 */

"use strict";

var app = angular.module('ariana', [
    'ui.router',
    'ui.bootstrap',
    'templates-ariana',
    'ngFileUpload',
    'ngAnimate'
]);

/* The AppController is the main controller of the application. */
app.controller('AppCtrl', ['$scope',
    function($scope) {

        /* The config object contains the current state of the layers, tools,
         * canvas and the mouse. It is accessed by all kinds of controllers. */
        $scope.config = {
            mouse: {
                old: {
                    x : 0,
                    y : 0,
                    global: {
                        x : 0,
                        y : 0,
                    },
                },
                current: {
                    x: 0,
                    y: 0,
                    global: {
                        x : 0,
                        y : 0,
                    },
                },
                button: {
                    1: false, // left button
                    2: false, // middle button
                    3: false, // right button
                }
            },
            canvas: {
                cursor: 'default',
                x: 128,
                y: 128,
                xr: 1,
                yr: 1,
                zoom: 1,
                width: 0,
                height: 0
            },
            tools: {
                activeTool: 'pan',
                activeToolFunctions: null,
                activeToolset: null,
                colors: {
                    primary: {
                        r: 0,
                        g: 0,
                        b: 0
                    },
                    secondary: {
                        r: 255,
                        g: 255,
                        b: 255
                    }
                }
            },
            layers: {
                numberOfLayers: 0,
                currentLayer: -1,
                layerInfo: [],
            }
        };

        $scope.renderEngine = null;
        $scope.drawEngine = null;

        /* This function creates the RenderEngine. It requires the canvas to
         * render on. */
        $scope.startEngines = function(renderCanvas, drawCanvas) {
            $scope.renderEngine = new RenderEngine(renderCanvas);
            $scope.drawEngine = new DrawEngine(drawCanvas);
        };

        /* This function creates a new layer from a given Image-object. The new
         * layer is placed on top. */
        $scope.newLayerFromImage = function(image) {
            var layer = $scope.renderEngine.createImageLayer(image);

            var height = layer.getHeight();
            var width  = layer.getWidth();

            layer.setPos(0.5 * width, 0.5 * height);

            $scope.renderEngine.addLayer(layer)

            /* set the correct layer info in config. The new layer comes on top
             * and is immediately selected. */
            //$scope.setSelection([$scope.config.layers.numberOfLayers]);
            $scope.config.layers.numberOfLayers += 1;
            $scope.config.layers.currentLayer = $scope.config.layers.numberOfLayers - 1;

            /* Store information about the layers in the config object. */
            $scope.config.layers.layerInfo[$scope.config.layers.currentLayer] = {
                "name": $scope.config.layers.currentLayer,
                "x": layer.getPosX(),
                "y": layer.getPosY(),
                "originalWidth": width,
                "originalHeight": height,
                "width": width,
                "height": height,
                "rotation": layer.getRotation(),
            }

            $scope.renderEngine.render();
        };

        $scope.resizeCanvases = function(width, height) {
            $scope.config.canvas.width = width;
            $scope.config.canvas.height = height;
            $scope.renderEngine.resize($scope.config.canvas.width, $scope.config.canvas.height);
            $scope.drawEngine.resize($scope.config.canvas.width, $scope.config.canvas.height);

            $scope.config.layers.numberOfLayers = 0;
            $scope.config.layers.currentLayer = -1;
            $scope.config.layers.layerInfo = [];
        };
	}
]);
<commit_msg>init the select tool again at new canvas<commit_after>/*
 * Project Ariana
 * app.js
 *
 * This file contains the AppController, which controls the entire application.
 * It also contain the global configuration settings.
 *
 */

"use strict";

var app = angular.module('ariana', [
    'ui.router',
    'ui.bootstrap',
    'templates-ariana',
    'ngFileUpload',
    'ngAnimate'
]);

/* The AppController is the main controller of the application. */
app.controller('AppCtrl', ['$scope',
    function($scope) {

        /* The config object contains the current state of the layers, tools,
         * canvas and the mouse. It is accessed by all kinds of controllers. */
        $scope.config = {
            mouse: {
                old: {
                    x : 0,
                    y : 0,
                    global: {
                        x : 0,
                        y : 0,
                    },
                },
                current: {
                    x: 0,
                    y: 0,
                    global: {
                        x : 0,
                        y : 0,
                    },
                },
                button: {
                    1: false, // left button
                    2: false, // middle button
                    3: false, // right button
                }
            },
            canvas: {
                cursor: 'default',
                x: 128,
                y: 128,
                xr: 1,
                yr: 1,
                zoom: 1,
                width: 0,
                height: 0
            },
            tools: {
                activeTool: 'pan',
                activeToolFunctions: null,
                activeToolset: null,
                colors: {
                    primary: {
                        r: 0,
                        g: 0,
                        b: 0
                    },
                    secondary: {
                        r: 255,
                        g: 255,
                        b: 255
                    }
                }
            },
            layers: {
                numberOfLayers: 0,
                currentLayer: -1,
                layerInfo: [],
            }
        };

        $scope.renderEngine = null;
        $scope.drawEngine = null;

        /* This function creates the RenderEngine. It requires the canvas to
         * render on. */
        $scope.startEngines = function(renderCanvas, drawCanvas) {
            $scope.renderEngine = new RenderEngine(renderCanvas);
            $scope.drawEngine = new DrawEngine(drawCanvas);
        };

        /* This function creates a new layer from a given Image-object. The new
         * layer is placed on top. */
        $scope.newLayerFromImage = function(image) {
            var layer = $scope.renderEngine.createImageLayer(image);

            var height = layer.getHeight();
            var width  = layer.getWidth();

            layer.setPos(0.5 * width, 0.5 * height);

            $scope.renderEngine.addLayer(layer)

            /* set the correct layer info in config. The new layer comes on top
             * and is immediately selected. */
            //$scope.setSelection([$scope.config.layers.numberOfLayers]);
            $scope.config.layers.numberOfLayers += 1;
            $scope.config.layers.currentLayer = $scope.config.layers.numberOfLayers - 1;

            /* Store information about the layers in the config object. */
            $scope.config.layers.layerInfo[$scope.config.layers.currentLayer] = {
                "name": $scope.config.layers.currentLayer,
                "x": layer.getPosX(),
                "y": layer.getPosY(),
                "originalWidth": width,
                "originalHeight": height,
                "width": width,
                "height": height,
                "rotation": layer.getRotation(),
            }

            $scope.renderEngine.render();
        };

        $scope.resizeCanvases = function(width, height) {
            var toolFunctions = $scope.config.tools.activeToolFunctions;

            $scope.config.canvas.width = width;
            $scope.config.canvas.height = height;
            $scope.renderEngine.resize($scope.config.canvas.width, $scope.config.canvas.height);
            $scope.drawEngine.resize($scope.config.canvas.width, $scope.config.canvas.height);

            if (toolFunctions && toolFunctions.init) {
                toolFunctions.init();
            }

            $scope.config.layers.numberOfLayers = 0;
            $scope.config.layers.currentLayer = -1;
            $scope.config.layers.layerInfo = [];
        };
	}
]);
<|endoftext|>


<commit_before>// Meyda Javascript DSP library
var Medya = function(audioContext,callback,bufferSize=256){
	var node = audioContext.createScriptProcessor(bufferSize, 1, 1);
	node.onaudioprocess = function(e) {
		var input = e.inputBuffer.getChannelData(0);
		var output = e.outputBuffer.getChannelData(0);
		console.log("isArray"+input.isArray())
		callback(Math.sqrt(input.reduce(function(last,current){
			return Math.pow(current,2);
		},0)/bufferSize))
	}
	return node;
}<commit_msg>made reduce work, lengthens time it works for<commit_after>// Meyda Javascript DSP library
var Medya = function(audioContext,callback,bufferSize=256){
	var node = audioContext.createScriptProcessor(bufferSize, 1, 1);
	node.onaudioprocess = function(e) {
		// type float32Array
		var input = e.inputBuffer.getChannelData(0);

		// Convert from float32Array to Array
		input = Array.prototype.slice.call(input);
		callback(Math.sqrt(input.reduce(function(last,current){
			return Math.pow(current,2);
		},0)/bufferSize))
	}
	return node;
}<|endoftext|>