<commit_before>;(function($B) {
var _b_ = $B.builtins
  // Static binding in function closure needed for import hooks
  // to stick to builtin cache even if module is overriden in sys.modules
  //$sys = $B.imported['sys'];

/**
* [Import spec] [PEP 302] Brython import machinery
*
* @param mod_name        {string}    name of module to load
* @param origin          {string}    name of module context invoking the import
* @param _path           {list}      Brython's None for top-level modules
*                                    Value of parent package's __path__
* @param module          {module}    [Optional] Existing module, for reload only
*/
function import_hooks(mod_name, _path, from_stdlib) {

    var meta_path = $B.meta_path.slice(),
        _sys_modules = $B.imported,
        _loader,
        spec
    if(from_stdlib){
        // When importing from a module in the standard library, remove
        // finder_path from the finders : the module can't be in the current
        // directory.
        var path_ix = meta_path.indexOf($B.finders["path"])
        if(path_ix > -1){
            meta_path.splice(path_ix, 1)
        }
    }
    for(var i = 0, len = meta_path.length; i < len; i++){
        var _finder = meta_path[i],
            find_spec = $B.$getattr(_finder, "find_spec", _b_.None)
        if(find_spec == _b_.None){
            // If find_spec is not defined for the meta path, try the legacy
            // method find_module()
            var find_module = $B.$getattr(_finder, "find_module", _b_.None)
            if(find_module !== _b_.None){
                _loader = find_module(mod_name, _path)
                // The loader has a method load_module()
                var load_module = $B.$getattr(_loader, "load_module"),
                    module = $B.$call(load_module)(mod_name)
                _sys_modules[mod_name] = module
                return module
            }
        }else{
            spec = find_spec(mod_name, _path)

            if(!$B.is_none(spec)){
                module = $B.imported[spec.name]
                if(module !== undefined){
                    // If module of same name is already in imports, return it
                    return _sys_modules[spec.name] = module
                }
                _loader = _b_.getattr(spec, "loader", _b_.None)
                break
            }
        }
    }

    if(_loader === undefined){
        // No import spec found
        var exc = _b_.ImportError.$factory("No module named " + mod_name)
        exc.name = mod_name
        throw exc
    }

    // Import spec represents a match
    if($B.is_none(module)){
        var _spec_name = _b_.getattr(spec, "name")

        // Create module object
        if(!$B.is_none(_loader)){
            var create_module = _b_.getattr(_loader, "create_module", _b_.None)
            if(!$B.is_none(create_module)){
                module = $B.$call(create_module)(spec)
            }
        }
        if(module === undefined){throw _b_.ImportError.$factory(mod_name)}
        if($B.is_none(module)){
            // FIXME : Initialize __doc__ and __package__
            module = $B.module.$factory(mod_name)
            var mod_desc = _b_.getattr(spec, "origin")
            if(_b_.getattr(spec, "has_location")){
                mod_desc = "from '" + mod_desc + "'"
            }else{
                mod_desc = "(" + mod_desc + ")"
            }
        }
    }
    module.__name__ = _spec_name
    module.__loader__ = _loader
    module.__package__ = _b_.getattr(spec, "parent", "")
    module.__spec__ = spec

    var locs = _b_.getattr(spec, "submodule_search_locations")
    // Brython-specific var
    if(module.$is_package = !$B.is_none(locs)){
        module.__path__ = locs
    }
    if(_b_.getattr(spec, "has_location")){
        module.__file__ = _b_.getattr(spec, "origin")
        $B.$py_module_path[module.__name__] = module.__file__
    }
    var cached = _b_.getattr(spec, "cached")
    if(! $B.is_none(cached)){
        module.__cached__ = cached
    }

    if($B.is_none(_loader)){
        if(!$B.is_none(locs)){
            _sys_modules[_spec_name] = module
        }else{
            throw _b_.ImportError.$factory(mod_name)
        }
    }else{
        var exec_module = _b_.getattr(_loader, "exec_module", _b_.None)
        if($B.is_none(exec_module)){
            // FIXME : Remove !!! Backwards compat in CPython
            module = _b_.getattr(_loader, "load_module")(_spec_name)
        }else{
            _sys_modules[_spec_name] = module
            try{
                exec_module(module)
            }catch(e){
                delete _sys_modules[_spec_name]
                throw e
           }
        }
    }
    return _sys_modules[_spec_name]
}

$B.import_hooks = import_hooks
})(__BRYTHON__)
<commit_msg>Replace ImportError by ModuleNotFoundError (related to issue #1237)<commit_after>;(function($B) {
var _b_ = $B.builtins
  // Static binding in function closure needed for import hooks
  // to stick to builtin cache even if module is overriden in sys.modules
  //$sys = $B.imported['sys'];

/**
* [Import spec] [PEP 302] Brython import machinery
*
* @param mod_name        {string}    name of module to load
* @param origin          {string}    name of module context invoking the import
* @param _path           {list}      Brython's None for top-level modules
*                                    Value of parent package's __path__
* @param module          {module}    [Optional] Existing module, for reload only
*/
function import_hooks(mod_name, _path, from_stdlib) {

    var meta_path = $B.meta_path.slice(),
        _sys_modules = $B.imported,
        _loader,
        spec

    if(from_stdlib){
        // When importing from a module in the standard library, remove
        // finder_path from the finders : the module can't be in the current
        // directory.
        var path_ix = meta_path.indexOf($B.finders["path"])
        if(path_ix > -1){
            meta_path.splice(path_ix, 1)
        }
    }
    for(var i = 0, len = meta_path.length; i < len; i++){
        var _finder = meta_path[i],
            find_spec = $B.$getattr(_finder, "find_spec", _b_.None)
        if(find_spec == _b_.None){
            // If find_spec is not defined for the meta path, try the legacy
            // method find_module()
            var find_module = $B.$getattr(_finder, "find_module", _b_.None)
            if(find_module !== _b_.None){
                _loader = find_module(mod_name, _path)
                // The loader has a method load_module()
                var load_module = $B.$getattr(_loader, "load_module"),
                    module = $B.$call(load_module)(mod_name)
                _sys_modules[mod_name] = module
                return module
            }
        }else{
            spec = find_spec(mod_name, _path)

            if(!$B.is_none(spec)){
                module = $B.imported[spec.name]
                if(module !== undefined){
                    // If module of same name is already in imports, return it
                    return _sys_modules[spec.name] = module
                }
                _loader = _b_.getattr(spec, "loader", _b_.None)
                break
            }
        }
    }

    if(_loader === undefined){
        // No import spec found
        var exc = _b_.ModuleNotFoundError.$factory(mod_name)
        exc.name = mod_name
        throw exc
    }

    // Import spec represents a match
    if($B.is_none(module)){
        var _spec_name = _b_.getattr(spec, "name")

        // Create module object
        if(!$B.is_none(_loader)){
            var create_module = _b_.getattr(_loader, "create_module", _b_.None)
            if(!$B.is_none(create_module)){
                module = $B.$call(create_module)(spec)
            }
        }
        if(module === undefined){throw _b_.ImportError.$factory(mod_name)}
        if($B.is_none(module)){
            // FIXME : Initialize __doc__ and __package__
            module = $B.module.$factory(mod_name)
            var mod_desc = _b_.getattr(spec, "origin")
            if(_b_.getattr(spec, "has_location")){
                mod_desc = "from '" + mod_desc + "'"
            }else{
                mod_desc = "(" + mod_desc + ")"
            }
        }
    }
    module.__name__ = _spec_name
    module.__loader__ = _loader
    module.__package__ = _b_.getattr(spec, "parent", "")
    module.__spec__ = spec

    var locs = _b_.getattr(spec, "submodule_search_locations")
    // Brython-specific var
    if(module.$is_package = !$B.is_none(locs)){
        module.__path__ = locs
    }
    if(_b_.getattr(spec, "has_location")){
        module.__file__ = _b_.getattr(spec, "origin")
        $B.$py_module_path[module.__name__] = module.__file__
    }
    var cached = _b_.getattr(spec, "cached")
    if(! $B.is_none(cached)){
        module.__cached__ = cached
    }

    if($B.is_none(_loader)){
        if(!$B.is_none(locs)){
            _sys_modules[_spec_name] = module
        }else{
            throw _b_.ImportError.$factory(mod_name)
        }
    }else{
        var exec_module = _b_.getattr(_loader, "exec_module", _b_.None)
        if($B.is_none(exec_module)){
            // FIXME : Remove !!! Backwards compat in CPython
            module = _b_.getattr(_loader, "load_module")(_spec_name)
        }else{
            _sys_modules[_spec_name] = module
            try{
                exec_module(module)
            }catch(e){
                delete _sys_modules[_spec_name]
                throw e
           }
        }
    }
    return _sys_modules[_spec_name]
}

$B.import_hooks = import_hooks
})(__BRYTHON__)
<|endoftext|>


<commit_before>var gulp        = require('gulp'),
    fs          = require('fs'),
    yaml        = require('js-yaml'),
    sass        = require('gulp-sass'),
    concat      = require('gulp-concat'),
    uglify      = require('gulp-uglify'),
    csslint     = require('gulp-csslint'),
    runSequence = require('run-sequence'),
    stylestats  = require('gulp-stylestats'),
    sourcemaps  = require('gulp-sourcemaps'),
    uglifyCss   = require('gulp-uglifycss');

var f, compileFile, cssFileName, cssTestFileName, cssVendorsFileName, cssMergeFileName, jsFileName;

f = yaml.safeLoad(fs.readFileSync('./frontsize.yml', 'utf-8'));
compileFile        = 'compile.scss';
cssFileName        = 'frontsize-theme.min.css';
cssTestFileName    = 'frontsize.csslint.css';
cssVendorsFileName = 'vendors.min.css';
jsFileName         = 'frontsize.min.js';
cssMergeFileName   = 'frontsize.min.css';

gulp.task('default', function () {
    var tasks = [
        'frontsize:watch'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:css', function () {
    return gulp.src(f.path.frontsize + compileFile)
        .pipe(sourcemaps.init())
        .pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError))
        .pipe(concat(cssFileName))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(f.path.css));
});

gulp.task('frontsize:sourcemap', function () {
    return gulp.src(f.path.frontsize + compileFile)
        .pipe(sourcemaps.init())
        .pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError))
        .pipe(concat(cssTestFileName))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(f.path.test));
});

gulp.task('frontsize:test', function () {
    var tasks = [
        'frontsize:test:build',
        'frontsize:test:report'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:test:build', function () {
    return gulp.src('example_source/frontsize/test.scss')
        .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError))
        .pipe(concat('frontsize.test.css'))
        .pipe(gulp.dest(f.path.test));
});

gulp.task('frontsize:test:report', ['frontsize:test:build'], function () {
    return gulp.src(f.path.test + 'frontsize.test.css')
        .pipe(csslint('example_source/.csslintrc'))
        .pipe(stylestats());
});

gulp.task('frontsize:report', ['frontsize:sourcemap'], function () {
    return gulp.src(f.path.test + cssTestFileName)
        .pipe(csslint('.csslintrc'))
        .pipe(stylestats());
});

gulp.task('frontsize:assets:images', function () {
    return gulp.src(f.path.frontsize + 'themes/' + f.theme + '/img/**/*.*')
        .pipe(gulp.dest(f.path.images));
});

gulp.task('frontsize:assets:fonts', function () {
    return gulp.src(f.path.frontsize + 'themes/' + f.theme + '/fonts/**/*.*')
        .pipe(gulp.dest(f.path.fonts));
});

gulp.task('frontsize:build', function () {
    var tasks = [
        'frontsize:css',
        'frontsize:assets:images',
        'frontsize:assets:fonts',
        'frontsize:vendors',
        'frontsize:js',
        'frontsize:merge',
        'frontsize:sourcemap',
        'frontsize:report'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:watch', function () {
    var tasks = [
        'frontsize:build'
    ];
    runSequence(tasks);
    var watchList = [
        f.path.frontsize + 'themes/**/*.scss',
        f.path.frontsize + 'themes/**/img/**/*',
        f.path.frontsize + 'themes/**/fonts/**/*'
    ];
    if (f.js !== undefined && f.js.watch !== undefined) {
        watchList.push(f.js.watch);
    }
    return gulp.watch(watchList, tasks);
});

gulp.task('frontsize:vendors', function(){
    var tasks = [
        'frontsize:vendors:css',
        'frontsize:vendors:fonts',
        'frontsize:vendors:images'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:vendors:css', function () {
    if (f.vendors !== undefined && f.vendors.css !== undefined) {
        return gulp.src(f.vendors.css)
            .pipe(uglifyCss())
            .pipe(concat(cssVendorsFileName))
            .pipe(gulp.dest(f.path.css));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:vendors:fonts', function () {
    if (f.vendors !== undefined && f.vendors.fonts !== undefined) {
        return gulp.src(f.vendors.fonts)
            .pipe(gulp.dest(f.path.fonts));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:vendors:images', function () {
    if (f.vendors !== undefined && f.vendors.images !== undefined) {
        return gulp.src(f.vendors.images)
            .pipe(gulp.dest(f.path.images));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:js', function () {
    if (f.js !== undefined && f.js.files !== undefined) {
        return gulp.src(f.js.files)
            .pipe(uglify())
            .pipe(concat(f.js.name || jsFileName))
            .pipe(gulp.dest(f.path.js));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:merge', ['frontsize:vendors:css', 'frontsize:css'], function () {
    if (f.vendors !== undefined && f.vendors.css !== undefined) {
        var css = f.vendors.css.slice(0);
        css.push(f.path.test + cssTestFileName);
        return gulp.src(css)
            .pipe(uglifyCss())
            .pipe(concat(cssMergeFileName))
            .pipe(gulp.dest(f.path.css));
    } else {
        return gulp;
    }
});
<commit_msg>Add missing sourcemap for js files<commit_after>var gulp        = require('gulp'),
    fs          = require('fs'),
    yaml        = require('js-yaml'),
    sass        = require('gulp-sass'),
    concat      = require('gulp-concat'),
    uglify      = require('gulp-uglify'),
    csslint     = require('gulp-csslint'),
    runSequence = require('run-sequence'),
    stylestats  = require('gulp-stylestats'),
    sourcemaps  = require('gulp-sourcemaps'),
    uglifyCss   = require('gulp-uglifycss');

var f, compileFile, cssFileName, cssTestFileName, cssVendorsFileName, cssMergeFileName, jsFileName;

f = yaml.safeLoad(fs.readFileSync('./frontsize.yml', 'utf-8'));
compileFile        = 'compile.scss';
cssFileName        = 'frontsize-theme.min.css';
cssTestFileName    = 'frontsize.csslint.css';
cssVendorsFileName = 'vendors.min.css';
jsFileName         = 'frontsize.min.js';
cssMergeFileName   = 'frontsize.min.css';

gulp.task('default', function () {
    var tasks = [
        'frontsize:watch'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:css', function () {
    return gulp.src(f.path.frontsize + compileFile)
        .pipe(sourcemaps.init())
        .pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError))
        .pipe(concat(cssFileName))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(f.path.css));
});

gulp.task('frontsize:sourcemap', function () {
    return gulp.src(f.path.frontsize + compileFile)
        .pipe(sourcemaps.init())
        .pipe(sass({ outputStyle: 'expanded' }).on('error', sass.logError))
        .pipe(concat(cssTestFileName))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(f.path.test));
});

gulp.task('frontsize:test', function () {
    var tasks = [
        'frontsize:test:build',
        'frontsize:test:report'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:test:build', function () {
    return gulp.src('example_source/frontsize/test.scss')
        .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError))
        .pipe(concat('frontsize.test.css'))
        .pipe(gulp.dest(f.path.test));
});

gulp.task('frontsize:test:report', ['frontsize:test:build'], function () {
    return gulp.src(f.path.test + 'frontsize.test.css')
        .pipe(csslint('example_source/.csslintrc'))
        .pipe(stylestats());
});

gulp.task('frontsize:report', ['frontsize:sourcemap'], function () {
    return gulp.src(f.path.test + cssTestFileName)
        .pipe(csslint('.csslintrc'))
        .pipe(stylestats());
});

gulp.task('frontsize:assets:images', function () {
    return gulp.src(f.path.frontsize + 'themes/' + f.theme + '/img/**/*.*')
        .pipe(gulp.dest(f.path.images));
});

gulp.task('frontsize:assets:fonts', function () {
    return gulp.src(f.path.frontsize + 'themes/' + f.theme + '/fonts/**/*.*')
        .pipe(gulp.dest(f.path.fonts));
});

gulp.task('frontsize:build', function () {
    var tasks = [
        'frontsize:css',
        'frontsize:assets:images',
        'frontsize:assets:fonts',
        'frontsize:vendors',
        'frontsize:js',
        'frontsize:merge',
        'frontsize:sourcemap',
        'frontsize:report'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:watch', function () {
    var tasks = [
        'frontsize:build'
    ];
    runSequence(tasks);
    var watchList = [
        f.path.frontsize + 'themes/**/*.scss',
        f.path.frontsize + 'themes/**/img/**/*',
        f.path.frontsize + 'themes/**/fonts/**/*'
    ];
    if (f.js !== undefined && f.js.watch !== undefined) {
        watchList.push(f.js.watch);
    }
    return gulp.watch(watchList, tasks);
});

gulp.task('frontsize:vendors', function(){
    var tasks = [
        'frontsize:vendors:css',
        'frontsize:vendors:fonts',
        'frontsize:vendors:images'
    ];
    runSequence(tasks);
});

gulp.task('frontsize:vendors:css', function () {
    if (f.vendors !== undefined && f.vendors.css !== undefined) {
        return gulp.src(f.vendors.css)
            .pipe(uglifyCss())
            .pipe(concat(cssVendorsFileName))
            .pipe(gulp.dest(f.path.css));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:vendors:fonts', function () {
    if (f.vendors !== undefined && f.vendors.fonts !== undefined) {
        return gulp.src(f.vendors.fonts)
            .pipe(gulp.dest(f.path.fonts));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:vendors:images', function () {
    if (f.vendors !== undefined && f.vendors.images !== undefined) {
        return gulp.src(f.vendors.images)
            .pipe(gulp.dest(f.path.images));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:js', function () {
    if (f.js !== undefined && f.js.files !== undefined) {
        return gulp.src(f.js.files)
            .pipe(sourcemaps.init())
            .pipe(uglify())
            .pipe(concat(f.js.name || jsFileName))
            .pipe(sourcemaps.write('./'))
            .pipe(gulp.dest(f.path.js));
    } else {
        return gulp;
    }
});

gulp.task('frontsize:merge', ['frontsize:vendors:css', 'frontsize:css'], function () {
    if (f.vendors !== undefined && f.vendors.css !== undefined) {
        var css = f.vendors.css.slice(0);
        css.push(f.path.test + cssTestFileName);
        return gulp.src(css)
            .pipe(uglifyCss())
            .pipe(concat(cssMergeFileName))
            .pipe(gulp.dest(f.path.css));
    } else {
        return gulp;
    }
});
<|endoftext|>


<commit_before>/*
 * jQuery treeTable Plugin VERSION
 * http://ludo.cubicphuse.nl/jquery-plugins/treeTable/doc/
 *
 * Copyright 2011, Ludo van den Boom
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function($) {
  // Helps to make options available to all functions
  // TODO: This gives problems when there are both expandable and non-expandable
  // trees on a page. The options shouldn't be global to all these instances!
  var options;
  var defaultPaddingLeft;
  var persistStore;

  $.fn.treeTable = function(opts) {
    options = $.extend({}, $.fn.treeTable.defaults, opts);

    if(options.persist) {
      persistStore = new Persist.Store(options.persistStoreName);
    }

    return this.each(function() {
      $(this).addClass("treeTable").find("tbody tr").each(function() {
        // Skip initialized nodes.
        if (!$(this).hasClass('initialized')) {
          var isRootNode = ($(this)[0].className.search(options.childPrefix) == -1);

          // To optimize performance of indentation, I retrieve the padding-left
          // value of the first root node. This way I only have to call +css+
          // once.
          if (isRootNode && isNaN(defaultPaddingLeft)) {
            defaultPaddingLeft = parseInt($($(this).children("td")[options.treeColumn]).css('padding-left'), 10);
          }

          // Set child nodes to initial state if we're in expandable mode.
          if(!isRootNode && options.expandable && options.initialState == "collapsed") {
            $(this).addClass('ui-helper-hidden');
          }

          // If we're not in expandable mode, initialize all nodes.
          // If we're in expandable mode, only initialize root nodes.
          if(!options.expandable || isRootNode) {
            initialize($(this));
          }
        }
      });
    });
  };

  $.fn.treeTable.defaults = {
    childPrefix: "child-of-",
    clickableNodeNames: false,
    expandable: true,
    indent: 19,
    initialState: "collapsed",
    onNodeShow: null,
    onNodeHide: null,
    treeColumn: 0,
    persist: false,
    persistStoreName: 'treeTable',
    stringExpand: "Expand",
    stringCollapse: "Collapse"
  };

  //Expand all nodes
  $.fn.expandAll = function() {
    $(this).find("tr").each(function() {
      $(this).expand();
    });
  };

  //Collapse all nodes
  $.fn.collapseAll = function() {
    $(this).find("tr").each(function() {
      $(this).collapse();
    });
  };

  // Recursively hide all node's children in a tree
  $.fn.collapse = function() {
    return this.each(function() {
      $(this).removeClass("expanded").addClass("collapsed");

      if (options.persist) {
        persistNodeState($(this));
      }

      childrenOf($(this)).each(function() {
        if(!$(this).hasClass("collapsed")) {
          $(this).collapse();
        }

        $(this).addClass('ui-helper-hidden');

        if($.isFunction(options.onNodeHide)) {
          options.onNodeHide.call(this);
        }

      });
    });
  };

  // Recursively show all node's children in a tree
  $.fn.expand = function() {
    return this.each(function() {
      $(this).removeClass("collapsed").addClass("expanded");

      if (options.persist) {
        persistNodeState($(this));
      }

      childrenOf($(this)).each(function() {
        initialize($(this));

        if($(this).is(".expanded.parent")) {
          $(this).expand();
        }

        $(this).removeClass('ui-helper-hidden');

        if($.isFunction(options.onNodeShow)) {
          options.onNodeShow.call(this);
        }
      });
    });
  };

  // Reveal a node by expanding all ancestors
  $.fn.reveal = function() {
    $(ancestorsOf($(this)).reverse()).each(function() {
      initialize($(this));
      $(this).expand().show();
    });

    return this;
  };

  // Add an entire branch to +destination+
  $.fn.appendBranchTo = function(destination) {
    var node = $(this);
    var parent = parentOf(node);

    var ancestorNames = $.map(ancestorsOf($(destination)), function(a) { return a.id; });

    // Conditions:
    // 1: +node+ should not be inserted in a location in a branch if this would
    //    result in +node+ being an ancestor of itself.
    // 2: +node+ should not have a parent OR the destination should not be the
    //    same as +node+'s current parent (this last condition prevents +node+
    //    from being moved to the same location where it already is).
    // 3: +node+ should not be inserted as a child of +node+ itself.
    if($.inArray(node[0].id, ancestorNames) == -1 && (!parent || (destination.id != parent[0].id)) && destination.id != node[0].id) {
      indent(node, ancestorsOf(node).length * options.indent * -1); // Remove indentation

      if(parent) { node.removeClass(options.childPrefix + parent[0].id); }

      node.addClass(options.childPrefix + destination.id);
      move(node, destination); // Recursively move nodes to new location
      indent(node, ancestorsOf(node).length * options.indent);
    }

    return this;
  };

  // Add reverse() function from JS Arrays
  $.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
  };

  // Toggle an entire branch
  $.fn.toggleBranch = function() {
    if($(this).hasClass("collapsed")) {
      $(this).expand();
    } else {
      $(this).collapse();
    }

    return this;
  };

  // === Private functions

  function ancestorsOf(node) {
    var ancestors = [];
    while(node = parentOf(node)) {
      ancestors[ancestors.length] = node[0];
    }
    return ancestors;
  };

  function childrenOf(node) {
    return $(node).siblings("tr." + options.childPrefix + node[0].id);
  };

  function getPaddingLeft(node) {
    var paddingLeft = parseInt(node[0].style.paddingLeft, 10);
    return (isNaN(paddingLeft)) ? defaultPaddingLeft : paddingLeft;
  }

  function indent(node, value) {
    var cell = $(node.children("td")[options.treeColumn]);
    cell[0].style.paddingLeft = getPaddingLeft(cell) + value + "px";

    childrenOf(node).each(function() {
      indent($(this), value);
    });
  };

  function initialize(node) {
    if(!node.hasClass("initialized")) {
      node.addClass("initialized");

      var childNodes = childrenOf(node);

      if(!node.hasClass("parent") && childNodes.length > 0) {
        node.addClass("parent");
      }

      if(node.hasClass("parent")) {
        var cell = $(node.children("td")[options.treeColumn]);
        var padding = getPaddingLeft(cell) + options.indent;

        childNodes.each(function() {
          $(this).children("td")[options.treeColumn].style.paddingLeft = padding + "px";
        });

        if(options.expandable) {
          var newLink = '';

          if(options.clickableNodeNames) {
            cell.wrapInner(newLink);
          } else {
            cell.html(newLink+cell.html());
          }

          $(cell[0].firstChild).click(function() { node.toggleBranch(); return false; }).mousedown(function() { return false; });
          $(cell[0].firstChild).keydown(function(e) { if(e.keyCode == 13) { node.toggleBranch(); return false; }});

          if(options.clickableNodeNames) {
            cell[0].style.cursor = "pointer";
            $(cell).click(function(e) {
              // Don't double-toggle if the click is on the existing expander icon
              if (e.target.className != 'expander') {
                node.toggleBranch();
              }
            });
          }

          if (options.persist && getPersistedNodeState(node)) {
            node.addClass('expanded');
          }

          // Check for a class set explicitly by the user, otherwise set the default class
          if(!(node.hasClass("expanded") || node.hasClass("collapsed"))) {
            node.addClass(options.initialState);
          }

          if(node.hasClass("expanded")) {
            node.expand();
          }
        }
      }
    }
  };

  function move(node, destination) {
    node.insertAfter(destination);
    childrenOf(node).reverse().each(function() { move($(this), node[0]); });
  };

  function parentOf(node) {
    var classNames = node[0].className.split(' ');

    for(var key=0; key<classNames.length; key++) {
      if(classNames[key].match(options.childPrefix)) {
        return $(node).siblings("#" + classNames[key].substring(options.childPrefix.length));
      }
    }

    return null;
  };

  //saving state functions, not critical, so will not generate alerts on error
  function persistNodeState(node) {
    if(node.hasClass('expanded')) {
      try {
         persistStore.set(node.attr('id'), '1');
      } catch (err) {

      }
    } else {
      try {
        persistStore.remove(node.attr('id'));
      } catch (err) {

      }
    }
  }

  function getPersistedNodeState(node) {
    try {
      return persistStore.get(node.attr('id')) == '1';
    } catch (err) {
      return false;
    }
  }
})(jQuery);<commit_msg>Journeys removed negative positions indent (attempt 2)<commit_after>/*
 * jQuery treeTable Plugin VERSION
 * http://ludo.cubicphuse.nl/jquery-plugins/treeTable/doc/
 *
 * Copyright 2011, Ludo van den Boom
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function($) {
  // Helps to make options available to all functions
  // TODO: This gives problems when there are both expandable and non-expandable
  // trees on a page. The options shouldn't be global to all these instances!
  var options;
  var defaultPaddingLeft;
  var persistStore;

  $.fn.treeTable = function(opts) {
    options = $.extend({}, $.fn.treeTable.defaults, opts);

    if(options.persist) {
      persistStore = new Persist.Store(options.persistStoreName);
    }

    return this.each(function() {
      $(this).addClass("treeTable").find("tbody tr").each(function() {
        // Skip initialized nodes.
        if (!$(this).hasClass('initialized')) {
          var isRootNode = ($(this)[0].className.search(options.childPrefix) == -1);

          // To optimize performance of indentation, I retrieve the padding-left
          // value of the first root node. This way I only have to call +css+
          // once.
          if (isRootNode && isNaN(defaultPaddingLeft)) {
            defaultPaddingLeft = parseInt($($(this).children("td")[options.treeColumn]).css('padding-left'), 10);
          }

          // Set child nodes to initial state if we're in expandable mode.
          if(!isRootNode && options.expandable && options.initialState == "collapsed") {
            $(this).addClass('ui-helper-hidden');
          }

          // If we're not in expandable mode, initialize all nodes.
          // If we're in expandable mode, only initialize root nodes.
          if(!options.expandable || isRootNode) {
            initialize($(this));
          }
        }
      });
    });
  };

  $.fn.treeTable.defaults = {
    childPrefix: "child-of-",
    clickableNodeNames: false,
    expandable: true,
    indent: 19,
    initialState: "collapsed",
    onNodeShow: null,
    onNodeHide: null,
    treeColumn: 0,
    persist: false,
    persistStoreName: 'treeTable',
    stringExpand: "Expand",
    stringCollapse: "Collapse"
  };

  //Expand all nodes
  $.fn.expandAll = function() {
    $(this).find("tr").each(function() {
      $(this).expand();
    });
  };

  //Collapse all nodes
  $.fn.collapseAll = function() {
    $(this).find("tr").each(function() {
      $(this).collapse();
    });
  };

  // Recursively hide all node's children in a tree
  $.fn.collapse = function() {
    return this.each(function() {
      $(this).removeClass("expanded").addClass("collapsed");

      if (options.persist) {
        persistNodeState($(this));
      }

      childrenOf($(this)).each(function() {
        if(!$(this).hasClass("collapsed")) {
          $(this).collapse();
        }

        $(this).addClass('ui-helper-hidden');

        if($.isFunction(options.onNodeHide)) {
          options.onNodeHide.call(this);
        }

      });
    });
  };

  // Recursively show all node's children in a tree
  $.fn.expand = function() {
    return this.each(function() {
      $(this).removeClass("collapsed").addClass("expanded");

      if (options.persist) {
        persistNodeState($(this));
      }

      childrenOf($(this)).each(function() {
        initialize($(this));

        if($(this).is(".expanded.parent")) {
          $(this).expand();
        }

        $(this).removeClass('ui-helper-hidden');

        if($.isFunction(options.onNodeShow)) {
          options.onNodeShow.call(this);
        }
      });
    });
  };

  // Reveal a node by expanding all ancestors
  $.fn.reveal = function() {
    $(ancestorsOf($(this)).reverse()).each(function() {
      initialize($(this));
      $(this).expand().show();
    });

    return this;
  };

  // Add an entire branch to +destination+
  $.fn.appendBranchTo = function(destination) {
    var node = $(this);
    var parent = parentOf(node);

    var ancestorNames = $.map(ancestorsOf($(destination)), function(a) { return a.id; });

    // Conditions:
    // 1: +node+ should not be inserted in a location in a branch if this would
    //    result in +node+ being an ancestor of itself.
    // 2: +node+ should not have a parent OR the destination should not be the
    //    same as +node+'s current parent (this last condition prevents +node+
    //    from being moved to the same location where it already is).
    // 3: +node+ should not be inserted as a child of +node+ itself.
    if($.inArray(node[0].id, ancestorNames) == -1 && (!parent || (destination.id != parent[0].id)) && destination.id != node[0].id) {
      indent(node, ancestorsOf(node).length * options.indent * -1); // Remove indentation

      if(parent) { node.removeClass(options.childPrefix + parent[0].id); }

      node.addClass(options.childPrefix + destination.id);
      move(node, destination); // Recursively move nodes to new location
      indent(node, ancestorsOf(node).length * options.indent);
    }

    return this;
  };

  // Add reverse() function from JS Arrays
  $.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
  };

  // Toggle an entire branch
  $.fn.toggleBranch = function() {
    if($(this).hasClass("collapsed")) {
      $(this).expand();
    } else {
      $(this).collapse();
    }

    return this;
  };

  // === Private functions

  function ancestorsOf(node) {
    var ancestors = [];
    while(node = parentOf(node)) {
      ancestors[ancestors.length] = node[0];
    }
    return ancestors;
  };

  function childrenOf(node) {
    return $(node).siblings("tr." + options.childPrefix + node[0].id);
  };

  function getPaddingLeft(node) {
    var paddingLeft = parseInt(node[0].style.paddingLeft, 10);
    return (isNaN(paddingLeft)) ? defaultPaddingLeft : paddingLeft;
  }

  function indent(node, value) {
    var cell = $(node.children("td")[options.treeColumn]);
    cell[0].style.paddingLeft = getPaddingLeft(cell) + value + "px";

    childrenOf(node).each(function() {
      indent($(this), value);
    });
  };

  function initialize(node) {
    if(!node.hasClass("initialized")) {
      node.addClass("initialized");

      var childNodes = childrenOf(node);

      if(!node.hasClass("parent") && childNodes.length > 0) {
        node.addClass("parent");
      }

      if(node.hasClass("parent")) {
        var cell = $(node.children("td")[options.treeColumn]);
        var padding = getPaddingLeft(cell) + options.indent;

        childNodes.each(function() {
          $(this).children("td")[options.treeColumn].style.paddingLeft = padding + "px";
        });

        if(options.expandable) {
          var newLink = '';

          if(options.clickableNodeNames) {
            cell.wrapInner(newLink);
          } else {
            cell.html(newLink+cell.html());
          }

          $(cell[0].firstChild).click(function() { node.toggleBranch(); return false; }).mousedown(function() { return false; });
          $(cell[0].firstChild).keydown(function(e) { if(e.keyCode == 13) { node.toggleBranch(); return false; }});

          if(options.clickableNodeNames) {
            cell[0].style.cursor = "pointer";
            $(cell).click(function(e) {
              // Don't double-toggle if the click is on the existing expander icon
              if (e.target.className != 'expander') {
                node.toggleBranch();
              }
            });
          }

          if (options.persist && getPersistedNodeState(node)) {
            node.addClass('expanded');
          }

          // Check for a class set explicitly by the user, otherwise set the default class
          if(!(node.hasClass("expanded") || node.hasClass("collapsed"))) {
            node.addClass(options.initialState);
          }

          if(node.hasClass("expanded")) {
            node.expand();
          }
        }
      }
    }
  };

  function move(node, destination) {
    node.insertAfter(destination);
    childrenOf(node).reverse().each(function() { move($(this), node[0]); });
  };

  function parentOf(node) {
    var classNames = node[0].className.split(' ');

    for(var key=0; key<classNames.length; key++) {
      if(classNames[key].match(options.childPrefix)) {
        return $(node).siblings("#" + classNames[key].substring(options.childPrefix.length));
      }
    }

    return null;
  };

  //saving state functions, not critical, so will not generate alerts on error
  function persistNodeState(node) {
    if(node.hasClass('expanded')) {
      try {
         persistStore.set(node.attr('id'), '1');
      } catch (err) {

      }
    } else {
      try {
        persistStore.remove(node.attr('id'));
      } catch (err) {

      }
    }
  }

  function getPersistedNodeState(node) {
    try {
      return persistStore.get(node.attr('id')) == '1';
    } catch (err) {
      return false;
    }
  }
})(jQuery);<|endoftext|>


<commit_before>const { fromEvent, merge, of } = require('rxjs')
const { map, switchMap } = require('rxjs/operators')
const { ofType } = require('redux-observable')

const {
	ADD_LIFX_NETWORK_CLIENT,
	addLifxNetworkLight,
	removeLifxNetworkLight,
	startNetworkListeners,
} = require('./actions')

const lifxNetworkDiscoveryEpic = (
	action$ => (
		action$
		.pipe(
			ofType(ADD_LIFX_NETWORK_CLIENT),
			switchMap(({ lifxNetworkClient }) => (
				merge(
					(
						fromEvent(
							lifxNetworkClient,
							'light-new',
						)
						.pipe(
							map(addLifxNetworkLight)
						)
					),
					(
						fromEvent(
							lifxNetworkClient,
							'light-offline',
						)
						.pipe(
							map(removeLifxNetworkLight)
						)
					),
					(
						fromEvent(
							lifxNetworkClient,
							'light-online',
						)
						.pipe(
							map(addLifxNetworkLight)
						)
					),
					of(startNetworkListeners()),
				)
			)),
		)
	)
)

module.exports = lifxNetworkDiscoveryEpic
<commit_msg>Refactored code styling in lifxNetworkDiscoveryEpic<commit_after>const { fromEvent, merge, of } = require('rxjs')
const { map, switchMap } = require('rxjs/operators')
const { ofType } = require('redux-observable')

const catchEpicError = require('$redux/utils/catchEpicError')

const {
	ADD_LIFX_NETWORK_CLIENT,
	addLifxNetworkLight,
	removeLifxNetworkLight,
	startNetworkListeners,
} = require('./actions')

const lifxNetworkDiscoveryEpic = (
	action$,
) => (
	action$
	.pipe(
		ofType(ADD_LIFX_NETWORK_CLIENT),
		switchMap(({ lifxNetworkClient }) => (
			merge(
				(
					fromEvent(
						lifxNetworkClient,
						'light-new',
					)
					.pipe(
						map(addLifxNetworkLight)
					)
				),
				(
					fromEvent(
						lifxNetworkClient,
						'light-offline',
					)
					.pipe(
						map(removeLifxNetworkLight)
					)
				),
				(
					fromEvent(
						lifxNetworkClient,
						'light-online',
					)
					.pipe(
						map(addLifxNetworkLight)
					)
				),
				of(startNetworkListeners()),
			)
		)),
		catchEpicError(),
	)
)

module.exports = lifxNetworkDiscoveryEpic
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", // declare
	"dojo/i18n", // i18n.getLocalization
	"./MappedTextBox"
], function(declare, i18n, MappedTextBox){

	// module:
	//		dijit/form/RangeBoundTextBox

	var RangeBoundTextBox = declare("dijit.form.RangeBoundTextBox", MappedTextBox, {
		// summary:
		//		Base class for textbox form widgets which defines a range of valid values.

		// rangeMessage: String
		//		The message to display if value is out-of-range
		rangeMessage: "",

		/*=====
		// constraints: RangeBoundTextBox.__Constraints
		constraints: {},
		======*/

		rangeCheck: function(/*Number*/ primitive, /*dijit/form/RangeBoundTextBox.__Constraints*/ constraints){
			// summary:
			//		Overridable function used to validate the range of the numeric input value.
			// tags:
			//		protected
			return	("min" in constraints? (this.compare(primitive,constraints.min) >= 0) : true) &&
				("max" in constraints? (this.compare(primitive,constraints.max) <= 0) : true); // Boolean
		},

		isInRange: function(/*Boolean*/ /*===== isFocused =====*/){
			// summary:
			//		Tests if the value is in the min/max range specified in constraints
			// tags:
			//		protected
			return this.rangeCheck(this.get('value'), this.constraints);
		},

		_isDefinitelyOutOfRange: function(){
			// summary:
			//		Returns true if the value is out of range and will remain
			//		out of range even if the user types more characters
			var val = this.get('value');
			if(val == null){ return false; } // not yet valid enough to compare to
			var outOfRange = false;
			if("min" in this.constraints){
				var min = this.constraints.min;
				outOfRange = this.compare(val, ((typeof min == "number") && min >= 0 && val != 0) ? 0 : min) < 0;
			}
			if(!outOfRange && ("max" in this.constraints)){
				var max = this.constraints.max;
				outOfRange = this.compare(val, ((typeof max != "number") || max > 0) ? max : 0) > 0;
			}
			return outOfRange;
		},

		_isValidSubset: function(){
			// summary:
			//		Overrides `dijit/form/ValidationTextBox._isValidSubset()`.
			//		Returns true if the input is syntactically valid, and either within
			//		range or could be made in range by more typing.
			return this.inherited(arguments) && !this._isDefinitelyOutOfRange();
		},

		isValid: function(/*Boolean*/ isFocused){
			// Overrides dijit/form/ValidationTextBox.isValid() to check that the value is also in range.
			return this.inherited(arguments) &&
				((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			// Overrides dijit/form/ValidationTextBox.getErrorMessage() to print "out of range" message if appropriate
			var v = this.get('value');
			if(v != null /* and !undefined */ && v !== '' && (typeof v != "number" || !isNaN(v)) && !this.isInRange(isFocused)){ // don't check isInRange w/o a real value
				return this.rangeMessage; // String
			}
			return this.inherited(arguments);
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			if(!this.rangeMessage){
				this.messages = i18n.getLocalization("dijit.form", "validate", this.lang);
				this.rangeMessage = this.messages.rangeMessage;
			}
		}
	});
	/*=====
	RangeBoundTextBox.__Constraints = declare(null, {
		// min: Number
		//		Minimum signed value.  Default is -Infinity
		// max: Number
		//		Maximum signed value.  Default is +Infinity
	});
	=====*/
	return RangeBoundTextBox;
});
<commit_msg>Modules are supposed to list their NLS resources in the define() dependencies.   !RangeBoundTextBox is missing "dojo/i18n!./nls/validate".   I guess it gets pulled in by a superclass but it's standard practice to list it explicitly.   Plus necessary, starting in 2.0.  Refs #16585 !strict.<commit_after>define([
	"dojo/_base/declare", // declare
	"dojo/i18n", // i18n.getLocalization
	"./MappedTextBox",
	"dojo/i18n!./nls/validate"
], function(declare, i18n, MappedTextBox){

	// module:
	//		dijit/form/RangeBoundTextBox

	var RangeBoundTextBox = declare("dijit.form.RangeBoundTextBox", MappedTextBox, {
		// summary:
		//		Base class for textbox form widgets which defines a range of valid values.

		// rangeMessage: String
		//		The message to display if value is out-of-range
		rangeMessage: "",

		/*=====
		// constraints: RangeBoundTextBox.__Constraints
		constraints: {},
		======*/

		rangeCheck: function(/*Number*/ primitive, /*dijit/form/RangeBoundTextBox.__Constraints*/ constraints){
			// summary:
			//		Overridable function used to validate the range of the numeric input value.
			// tags:
			//		protected
			return	("min" in constraints? (this.compare(primitive,constraints.min) >= 0) : true) &&
				("max" in constraints? (this.compare(primitive,constraints.max) <= 0) : true); // Boolean
		},

		isInRange: function(/*Boolean*/ /*===== isFocused =====*/){
			// summary:
			//		Tests if the value is in the min/max range specified in constraints
			// tags:
			//		protected
			return this.rangeCheck(this.get('value'), this.constraints);
		},

		_isDefinitelyOutOfRange: function(){
			// summary:
			//		Returns true if the value is out of range and will remain
			//		out of range even if the user types more characters
			var val = this.get('value');
			if(val == null){ return false; } // not yet valid enough to compare to
			var outOfRange = false;
			if("min" in this.constraints){
				var min = this.constraints.min;
				outOfRange = this.compare(val, ((typeof min == "number") && min >= 0 && val != 0) ? 0 : min) < 0;
			}
			if(!outOfRange && ("max" in this.constraints)){
				var max = this.constraints.max;
				outOfRange = this.compare(val, ((typeof max != "number") || max > 0) ? max : 0) > 0;
			}
			return outOfRange;
		},

		_isValidSubset: function(){
			// summary:
			//		Overrides `dijit/form/ValidationTextBox._isValidSubset()`.
			//		Returns true if the input is syntactically valid, and either within
			//		range or could be made in range by more typing.
			return this.inherited(arguments) && !this._isDefinitelyOutOfRange();
		},

		isValid: function(/*Boolean*/ isFocused){
			// Overrides dijit/form/ValidationTextBox.isValid() to check that the value is also in range.
			return this.inherited(arguments) &&
				((this._isEmpty(this.textbox.value) && !this.required) || this.isInRange(isFocused)); // Boolean
		},

		getErrorMessage: function(/*Boolean*/ isFocused){
			// Overrides dijit/form/ValidationTextBox.getErrorMessage() to print "out of range" message if appropriate
			var v = this.get('value');
			if(v != null /* and !undefined */ && v !== '' && (typeof v != "number" || !isNaN(v)) && !this.isInRange(isFocused)){ // don't check isInRange w/o a real value
				return this.rangeMessage; // String
			}
			return this.inherited(arguments);
		},

		postMixInProperties: function(){
			this.inherited(arguments);
			if(!this.rangeMessage){
				this.messages = i18n.getLocalization("dijit.form", "validate", this.lang);
				this.rangeMessage = this.messages.rangeMessage;
			}
		}
	});
	/*=====
	RangeBoundTextBox.__Constraints = declare(null, {
		// min: Number
		//		Minimum signed value.  Default is -Infinity
		// max: Number
		//		Maximum signed value.  Default is +Infinity
	});
	=====*/
	return RangeBoundTextBox;
});
<|endoftext|>


<commit_before>;
(function (global, undefined) {
    'use strict';

    function Player(playerNumber, x, y, style) {
        var player = _.create(v2(x, y), {
            playerNumber: playerNumber,

            speed: 300,
            radius: 25,
            pointerRadius: 4,
            rotation: 0,
            style: style || "#ffffff",
            lastFire: -Infinity,
            slowestFire: 50,
            mass: 1,
            tag: 'player',
            batchName: 'player',
            gravity: false,
            health: 400,
            maxHealth: 400,
            movement: v2(0, 0),
            hpBarStyles: ["white", "blue", "lightgreen", "darkred", 'yellow'],
            tao: Math.PI * 2
        });
        player.uid = _.uniqueId(player.tag);

        if (Path2D !== undefined) {
            player.startBatchDraw = function (context) {

                context.save();
                context.strokeStyle = player.style;

                return player.setupCache(new Path2D());

                //context.beginPath();
            };
            player.setupCache = function (path2d) {

                path2d.arc(0, 0, player.radius, 0, Math.PI * 2);
                //path2d.moveTo(player.radius / 4, 0);
                //path2d.arc(0, 0, player.radius / 4, 0, (player.tao * player.health / player.maxHealth));

                path2d.moveTo(-player.radius, 0);

                path2d.arc(-player.radius, 0, player.pointerRadius, Math.PI / 2, -Math.PI / 2);
                return path2d;
            };

            player.draw = function (context, path2d) {
                context.save();
                context.translate(player.x, player.y);

                context.rotate(player.rotation);
                path2d = path2d || player.cache;
                // ctx.translate(-60, -25);
                context.stroke(path2d);
                context.moveTo(player.radius / 4, 0);
                if (player.health > 0) {
                    let perc = player.health % 100 / 100;
                    if (perc === 0) {

                        context.strokeStyle = player.hpBarStyles[player.health / 100];
                        context.arc(0, 0, player.radius / 4, 0, player.tao);
                        context.stroke();
                    } else if (player.health / 100 < 1) {
                        context.strokeStyle = player.hpBarStyles[1];
                        context.beginPath();
                        context.arc(0, 0, player.radius / 4, 0, player.tao * perc, false);
                        context.closePath();
                        context.stroke();
                    } else {
                        let endAngle = player.tao * perc;

                        context.strokeStyle = player.hpBarStyles[Math.floor(player.health / 100)];
                        context.beginPath();
                        context.arc(0, 0, player.radius / 4, 0, endAngle, true);
                        context.closePath();
                        context.stroke();
                        //console.log(perc, Math.ceil(player.health / 100), Math.floor(player.health / 100));
                        context.beginPath();
                        context.strokeStyle = player.hpBarStyles[Math.ceil(player.health / 100)];

                        context.arc(0, 0, player.radius / 4, 0, endAngle, false);
                        context.closePath();

                        context.stroke();

                    }
                }
                /*for (var hp = 0, max = player.health / 100; hp < max; hp++) {
                    context.strokeStyle = player.hpBarStyles[hp];
                    context.arc(0, 0, player.radius / 4, 0, player.tao);
                    context.stroke();
                }
                if (player.health > 0 && player.health < player.maxHealth) {
                    context.strokeStyle = player.hpBarStyles[hp];
                    context.arc(0, 0, player.radius / 4, 0, player.tao * (max % 1));
                    context.stroke();
                }*/
                context.strokeStyle = player.style;

                context.restore();
            };
            player.endBatchDraw = function (context) {
                context.restore();
            };
            player.cache = player.setupCache(new Path2D());
        } else {
            player.startBatchDraw = function (context, graphics) {

                context.save();
                context.strokeStyle = player.style;

                context.beginPath();
            };

            player.draw = function (context) {
                var frontX = player.radius * Math.cos(player.rotation),
                    frontY = player.radius * Math.sin(player.rotation);
                context.save();
                context.moveTo(player.x + frontX, player.y + frontY);

                context.arc(player.x, player.y, player.radius, player.rotation, player.rotation + player.tao);
                context.moveTo(player.x + frontX / 4, player.y + frontY / 4);

                context.arc(player.x, player.y, player.radius / 4, player.rotation, player.rotation + (player.tao * player.health / player.maxHealth));

                context.moveTo(
                    player.x - frontX,
                    player.y - frontY);

                var rotStart = player.rotation - Math.PI / 2,
                    rotEnd = player.rotation + Math.PI / 2;

                context.arc(player.x - frontX, player.y - frontY, player.pointerRadius, rotEnd, rotStart);
                context.restore();
            };
            player.endBatchDraw = function (context) {
                context.stroke();

                context.restore();
            };

        }

        player.addMovement = function (dx, dy) {

            player.movement.x += dx;
            player.movement.y += dy;
        };
        player.physicsTick = function (perSecond) {
            player.x += player.movement.x; //* perSecond;
            player.y += player.movement.y; //* perSecond;
            player.movement.x = 0;
            player.movement.y = 0;
            /*if (player.playerNumber >= 1) {
                //var dy = player.y - Game.manager.objects[0].y;
                player.rotation = player.angleTo(Game.manager.objects[0]); //dy < 0 ? player.angleTo(Game.manager.objects[0]) : player.angleTo(player.sub(Game.manager.objects[0]));
                player.fireProjectile(1, performance.now());
            }*/
        };
        player.fireProjectile = function (rate, timestamp) {
            if (timestamp >= player.lastFire + ((1 - rate) * player.slowestFire + 120)) {

                player.lastFire = timestamp;
                let cos = Math.cos(player.rotation),
                    sin = Math.sin(player.rotation);

                Game.manager.add(Game.Projectile(
                    player.rotation,
                    4,
                    player.x - (player.radius * cos) - (4 * cos) - (player.pointerRadius * cos),
                    player.y - (player.radius * sin) - (4 * sin) - (player.pointerRadius * sin)
                ));
            }
        };
        player.getPoints = function () {
            return [v2(player.x, player.y)];
        };
        player.getAxes = function (oPoints) {
            _.each(oPoints, function (point) {

            });
        };
        player.controlTick = function (event) {
            /* var controls = event.controls,
                mousePos = controls.getMousePosition(),
                dirX = player.x - mousePos.x,
                dirY = player.y - mousePos.y;

            player.rotation = Math.atan2(dirY, dirX);*/
            var controls = event.controls,
                input = event.input,
                controllerIndex = event.controllerIndex,
                perSec = event.tickDelta / 1000;

            if (controllerIndex == -1) {
                let dirX = player.x - event.mouseCoords.x,
                    dirY = player.y - event.mouseCoords.y;
                player.rotation = Math.atan2(dirY, dirX);
            } else {
                if (input['lookV'].pressed || input['lookH'].pressed) {
                    player.rotation = Math.atan2(-input['lookV'].value, -input['lookH'].value);
                }
            }

            player.addMovement(player.speed * input['moveH'].value * perSec, player.speed * input['moveV'].value * perSec);

            if (input['fire'].pressed) {
                player.fireProjectile(input['fire'].value, event.timestamp);
            }

        };
        player.setupListeners = function (eventEmitters) {
            var id = player.playerNumber;

            eventEmitters.physics.addEventListener('physicsTick', player.physicsTick);
            eventEmitters.controls.addEventListener('control-tick-p' + id, player.controlTick);
        };
        player.removeListeners = function (eventEmitters) {
            var id = player.playerNumber;

            eventEmitters.physics.removeEventListener('physicsTick', player.physicsTick);
            eventEmitters.controls.removeEventListener('control-tick-p' + id, player.controlTick);
        };
        player.collide = function (object) {
            if ((object.tag !== 'object' || object.parent !== player) && object.tag !== 'projectile') {
                var dX = player.x - object.x,
                    dY = player.y - object.y,
                    angleTo = Math.atan2(dY, dX),
                    midX = (player.x + object.x) / 2,
                    midY = (player.y + object.y) / 2;

                /*sideX = object.x + (object.radius * Math.cos(angleTo)),
                    sideY = object.y + (object.radius * Math.sin(angleTo)),
                    centerX = sideX + (player.radius * Math.cos(angleTo)),
                    centerY = sideY + (player.radius * Math.sin(angleTo));*/

                /*sideDX = sideX - object.x,
                    sideDY = sideY - object.y,
                    distance = Math.sqrt(sideDX * sideDX + sideDY * sideDY),
                    diffDist = object.radius - distance;*/

                player.x = midX + (player.radius * Math.cos(angleTo)); //centerX;
                player.y = midY + (player.radius * Math.sin(angleTo)); //centerX;
                object.x = midX - (object.radius * Math.cos(angleTo)); //centerX;
                object.y = midY - (object.radius * Math.sin(angleTo));
            }
            if (object.tag === 'projectile') {
                player.health -= object.damage;
            }
        };
        return player;
    }
    global.Game = global.Game || {};
    global.Game.Player = Player;
}(this));<commit_msg>Changing how we detect for Path2D Support<commit_after>;
(function (global, undefined) {
    'use strict';

    function Player(playerNumber, x, y, style) {
        var player = _.create(v2(x, y), {
            playerNumber: playerNumber,

            speed: 300,
            radius: 25,
            pointerRadius: 4,
            rotation: 0,
            style: style || "#ffffff",
            lastFire: -Infinity,
            slowestFire: 50,
            mass: 1,
            tag: 'player',
            batchName: 'player',
            gravity: false,
            health: 400,
            maxHealth: 400,
            movement: v2(0, 0),
            hpBarStyles: ["white", "blue", "lightgreen", "darkred", 'yellow'],
            tao: Math.PI * 2
        });
        player.uid = _.uniqueId(player.tag);

        if (typeof Path2D !== 'undefined') {
            player.startBatchDraw = function (context) {

                context.save();
                context.strokeStyle = player.style;

                return player.setupCache(new Path2D());

                //context.beginPath();
            };
            player.setupCache = function (path2d) {

                path2d.arc(0, 0, player.radius, 0, Math.PI * 2);
                //path2d.moveTo(player.radius / 4, 0);
                //path2d.arc(0, 0, player.radius / 4, 0, (player.tao * player.health / player.maxHealth));

                path2d.moveTo(-player.radius, 0);

                path2d.arc(-player.radius, 0, player.pointerRadius, Math.PI / 2, -Math.PI / 2);
                return path2d;
            };

            player.draw = function (context, path2d) {
                context.save();
                context.translate(player.x, player.y);

                context.rotate(player.rotation);
                path2d = path2d || player.cache;
                // ctx.translate(-60, -25);
                context.stroke(path2d);
                context.moveTo(player.radius / 4, 0);
                if (player.health > 0) {
                    let perc = player.health % 100 / 100;
                    if (perc === 0) {

                        context.strokeStyle = player.hpBarStyles[player.health / 100];
                        context.arc(0, 0, player.radius / 4, 0, player.tao);
                        context.stroke();
                    } else if (player.health / 100 < 1) {
                        context.strokeStyle = player.hpBarStyles[1];
                        context.beginPath();
                        context.arc(0, 0, player.radius / 4, 0, player.tao * perc, false);
                        context.closePath();
                        context.stroke();
                    } else {
                        let endAngle = player.tao * perc;

                        context.strokeStyle = player.hpBarStyles[Math.floor(player.health / 100)];
                        context.beginPath();
                        context.arc(0, 0, player.radius / 4, 0, endAngle, true);
                        context.closePath();
                        context.stroke();
                        //console.log(perc, Math.ceil(player.health / 100), Math.floor(player.health / 100));
                        context.beginPath();
                        context.strokeStyle = player.hpBarStyles[Math.ceil(player.health / 100)];

                        context.arc(0, 0, player.radius / 4, 0, endAngle, false);
                        context.closePath();

                        context.stroke();

                    }
                }
                /*for (var hp = 0, max = player.health / 100; hp < max; hp++) {
                    context.strokeStyle = player.hpBarStyles[hp];
                    context.arc(0, 0, player.radius / 4, 0, player.tao);
                    context.stroke();
                }
                if (player.health > 0 && player.health < player.maxHealth) {
                    context.strokeStyle = player.hpBarStyles[hp];
                    context.arc(0, 0, player.radius / 4, 0, player.tao * (max % 1));
                    context.stroke();
                }*/
                context.strokeStyle = player.style;

                context.restore();
            };
            player.endBatchDraw = function (context) {
                context.restore();
            };
            player.cache = player.setupCache(new Path2D());
        } else {
            player.startBatchDraw = function (context, graphics) {

                context.save();
                context.strokeStyle = player.style;

                context.beginPath();
            };

            player.draw = function (context) {
                var frontX = player.radius * Math.cos(player.rotation),
                    frontY = player.radius * Math.sin(player.rotation);
                context.save();
                context.moveTo(player.x + frontX, player.y + frontY);

                context.arc(player.x, player.y, player.radius, player.rotation, player.rotation + player.tao);
                context.moveTo(player.x + frontX / 4, player.y + frontY / 4);

                context.arc(player.x, player.y, player.radius / 4, player.rotation, player.rotation + (player.tao * player.health / player.maxHealth));

                context.moveTo(
                    player.x - frontX,
                    player.y - frontY);

                var rotStart = player.rotation - Math.PI / 2,
                    rotEnd = player.rotation + Math.PI / 2;

                context.arc(player.x - frontX, player.y - frontY, player.pointerRadius, rotEnd, rotStart);
                context.restore();
            };
            player.endBatchDraw = function (context) {
                context.stroke();

                context.restore();
            };

        }

        player.addMovement = function (dx, dy) {

            player.movement.x += dx;
            player.movement.y += dy;
        };
        player.physicsTick = function (perSecond) {
            player.x += player.movement.x; //* perSecond;
            player.y += player.movement.y; //* perSecond;
            player.movement.x = 0;
            player.movement.y = 0;
            /*if (player.playerNumber >= 1) {
                //var dy = player.y - Game.manager.objects[0].y;
                player.rotation = player.angleTo(Game.manager.objects[0]); //dy < 0 ? player.angleTo(Game.manager.objects[0]) : player.angleTo(player.sub(Game.manager.objects[0]));
                player.fireProjectile(1, performance.now());
            }*/
        };
        player.fireProjectile = function (rate, timestamp) {
            if (timestamp >= player.lastFire + ((1 - rate) * player.slowestFire + 120)) {

                player.lastFire = timestamp;
                let cos = Math.cos(player.rotation),
                    sin = Math.sin(player.rotation);

                Game.manager.add(Game.Projectile(
                    player.rotation,
                    4,
                    player.x - (player.radius * cos) - (4 * cos) - (player.pointerRadius * cos),
                    player.y - (player.radius * sin) - (4 * sin) - (player.pointerRadius * sin)
                ));
            }
        };
        player.getPoints = function () {
            return [v2(player.x, player.y)];
        };
        player.getAxes = function (oPoints) {
            _.each(oPoints, function (point) {

            });
        };
        player.controlTick = function (event) {
            /* var controls = event.controls,
                mousePos = controls.getMousePosition(),
                dirX = player.x - mousePos.x,
                dirY = player.y - mousePos.y;

            player.rotation = Math.atan2(dirY, dirX);*/
            var controls = event.controls,
                input = event.input,
                controllerIndex = event.controllerIndex,
                perSec = event.tickDelta / 1000;

            if (controllerIndex == -1) {
                let dirX = player.x - event.mouseCoords.x,
                    dirY = player.y - event.mouseCoords.y;
                player.rotation = Math.atan2(dirY, dirX);
            } else {
                if (input['lookV'].pressed || input['lookH'].pressed) {
                    player.rotation = Math.atan2(-input['lookV'].value, -input['lookH'].value);
                }
            }

            player.addMovement(player.speed * input['moveH'].value * perSec, player.speed * input['moveV'].value * perSec);

            if (input['fire'].pressed) {
                player.fireProjectile(input['fire'].value, event.timestamp);
            }

        };
        player.setupListeners = function (eventEmitters) {
            var id = player.playerNumber;

            eventEmitters.physics.addEventListener('physicsTick', player.physicsTick);
            eventEmitters.controls.addEventListener('control-tick-p' + id, player.controlTick);
        };
        player.removeListeners = function (eventEmitters) {
            var id = player.playerNumber;

            eventEmitters.physics.removeEventListener('physicsTick', player.physicsTick);
            eventEmitters.controls.removeEventListener('control-tick-p' + id, player.controlTick);
        };
        player.collide = function (object) {
            if ((object.tag !== 'object' || object.parent !== player) && object.tag !== 'projectile') {
                var dX = player.x - object.x,
                    dY = player.y - object.y,
                    angleTo = Math.atan2(dY, dX),
                    midX = (player.x + object.x) / 2,
                    midY = (player.y + object.y) / 2;

                /*sideX = object.x + (object.radius * Math.cos(angleTo)),
                    sideY = object.y + (object.radius * Math.sin(angleTo)),
                    centerX = sideX + (player.radius * Math.cos(angleTo)),
                    centerY = sideY + (player.radius * Math.sin(angleTo));*/

                /*sideDX = sideX - object.x,
                    sideDY = sideY - object.y,
                    distance = Math.sqrt(sideDX * sideDX + sideDY * sideDY),
                    diffDist = object.radius - distance;*/

                player.x = midX + (player.radius * Math.cos(angleTo)); //centerX;
                player.y = midY + (player.radius * Math.sin(angleTo)); //centerX;
                object.x = midX - (object.radius * Math.cos(angleTo)); //centerX;
                object.y = midY - (object.radius * Math.sin(angleTo));
            }
            if (object.tag === 'projectile') {
                player.health -= object.damage;
            }
        };
        return player;
    }
    global.Game = global.Game || {};
    global.Game.Player = Player;
}(this));
<|endoftext|>


<commit_before>angular.module('yds').directive('ydsRating', ['$templateRequest', '$compile', '$location', 'Data', 'Filters',
    function ($templateRequest, $compile, $location, Data, Filters) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                // Check that the rating is enabled before continuing
                var enableRating = scope.enableRating;

                if (_.isUndefined(enableRating) || enableRating != "true") {
                    return false;
                }

                // Get the possible attributes for any chart
                var projectId = scope.projectId;
                var viewType = scope.viewType;
                var lang = scope.lang;

                var elementClass = attrs.class;
                var visualisationType = "";
                var defaultVisTypes = ["pie", "line", "scatter", "bubble", "bar", "tree", "map", "grid"];

                // Set default language if it's not defined
                if (_.isUndefined(lang) || lang.trim().length == 0) {
                    lang = "en";
                }

                // Find the visualisation type from its class
                if (!_.isUndefined(elementClass) && elementClass.trim().length > 0) {
                    var visTypeFound = false;

                    var visTypesLen = defaultVisTypes.length;
                    for (var i = 0; i < visTypesLen; i++) {
                        var index = elementClass.indexOf(defaultVisTypes[i]);

                        if (index != -1) {
                            visualisationType = defaultVisTypes[i];
                            visTypeFound = true;

                            break;
                        }
                    }

                    if (!visTypeFound) {
                        console.error("The rating extension cannot be applied on this element!");
                        return false;
                    }
                } else {
                    return false;
                }

                // Add rating buttons to the chart
                var ratingBtnX = scope.ratingBtnX || 100;
                var ratingBtnY = scope.ratingBtnY || 15;

                $templateRequest("templates/rating-buttons.html").then(function (html) {
                    var template = angular.element(html);

                    // Compile the element
                    var compiledTemplate = $compile(template)(scope);
                    compiledTemplate.css("top", ratingBtnY + "px");
                    compiledTemplate.css("left", ratingBtnX + "px");

                    // Add element as a child to the parent
                    element.parent().append(compiledTemplate);
                });

                /**
                 * Rate the chart with the specified number of stars
                 * @param stars Number of stars to give to the chart
                 */
                scope.rateChart = function (stars) {
                    // console.log("Chart rating: " + stars + " stars");

                    // If number of stars is undefined or not a number, abort
                    if (_.isUndefined(stars) || !_.isNumber(stars)) {
                        return;
                    }

                    // Get parameters that were used to create the chart
                    var chartParams = {
                        chart_type: visualisationType,
                        page_url: $location.absUrl(),
                        project_id: projectId,
                        view_type: viewType,
                        extra_params: scope.extraParams,
                        lang: lang,
                        user_id: "ydsUser",
                        rating: stars
                    };

                    // Remove undefined values from the object
                    chartParams = _.omit(chartParams, function (value) {
                        return _.isUndefined(value);
                    });

                    // console.log("Chart parameters:", chartParams);
                    Data.saveRating(chartParams);
                };
            }
        }
    }
]);
<commit_msg>Stringify any extra parameters before sending to API<commit_after>angular.module('yds').directive('ydsRating', ['$templateRequest', '$compile', '$location', 'Data', 'Filters',
    function ($templateRequest, $compile, $location, Data, Filters) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                // Check that the rating is enabled before continuing
                var enableRating = scope.enableRating;

                if (_.isUndefined(enableRating) || enableRating != "true") {
                    return false;
                }

                // Get the possible attributes for any chart
                var projectId = scope.projectId;
                var viewType = scope.viewType;
                var lang = scope.lang;

                var elementClass = attrs.class;
                var visualisationType = "";
                var defaultVisTypes = ["pie", "line", "scatter", "bubble", "bar", "tree", "map", "grid"];

                // Set default language if it's not defined
                if (_.isUndefined(lang) || lang.trim().length == 0) {
                    lang = "en";
                }

                // Find the visualisation type from its class
                if (!_.isUndefined(elementClass) && elementClass.trim().length > 0) {
                    var visTypeFound = false;

                    var visTypesLen = defaultVisTypes.length;
                    for (var i = 0; i < visTypesLen; i++) {
                        var index = elementClass.indexOf(defaultVisTypes[i]);

                        if (index != -1) {
                            visualisationType = defaultVisTypes[i];
                            visTypeFound = true;

                            break;
                        }
                    }

                    if (!visTypeFound) {
                        console.error("The rating extension cannot be applied on this element!");
                        return false;
                    }
                } else {
                    return false;
                }

                // Add rating buttons to the chart
                var ratingBtnX = scope.ratingBtnX || 100;
                var ratingBtnY = scope.ratingBtnY || 15;

                $templateRequest("templates/rating-buttons.html").then(function (html) {
                    var template = angular.element(html);

                    // Compile the element
                    var compiledTemplate = $compile(template)(scope);
                    compiledTemplate.css("top", ratingBtnY + "px");
                    compiledTemplate.css("left", ratingBtnX + "px");

                    // Add element as a child to the parent
                    element.parent().append(compiledTemplate);
                });

                /**
                 * Rate the chart with the specified number of stars
                 * @param stars Number of stars to give to the chart
                 */
                scope.rateChart = function (stars) {
                    // console.log("Chart rating: " + stars + " stars");

                    // If number of stars is undefined or not a number, abort
                    if (_.isUndefined(stars) || !_.isNumber(stars)) {
                        return;
                    }

                    // Get parameters that were used to create the chart
                    var chartParams = {
                        chart_type: visualisationType,
                        page_url: $location.absUrl(),
                        project_id: projectId,
                        view_type: viewType,
                        extra_params: JSON.stringify(scope.extraParams),
                        lang: lang,
                        user_id: "ydsUser",
                        rating: stars
                    };

                    // Remove undefined values from the object
                    chartParams = _.omit(chartParams, function (value) {
                        return _.isUndefined(value);
                    });

                    // console.log("Chart parameters:", chartParams);
                    Data.saveRating(chartParams);
                };
            }
        }
    }
]);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Drawer from 'react-native-drawer';
import _ from 'lodash';
import moment from 'moment';

import { createNewDrawer } from '../boundActionCreators/drawer';
import { pushRoute } from '../boundActionCreators/navigation';
import { setExpenseDate } from '../actionCreators/addExpenseForm';
import { setIncomeDate } from '../actionCreators/addIncomeForm';
import { populateEditExpenseForm } from '../actionCreators/editExpenseForm';
import { populateEditIncomeForm } from '../actionCreators/editIncomeForm';
import { setCalendarDate, createNewCalendar } from '../actionCreators/calendar';
import Menu from '../components/Drawer/Menu';
import Overview from '../components/Overview';
import { translateOne } from '../services/translator';
import { CATEGORY_PROP, ITEM_PROP } from '../constants/TranslationProps';

// This should be a plain object
const drawerStyles = {
  drawer: {
    borderRightColor: 'rgba(0,0,0,1)',
    borderRightWidth: 0,
    elevation: 5,
    shadowColor: '#000000',
    shadowOpacity: 0.8,
    shadowRadius: 3
  },
  main: {
  }
};

class HomeContainer extends Component {
  constructor(state) {
    super(state);
    this.getDrawer = this.getDrawer.bind(this);
    this.goTo = this.goTo.bind(this);
    this.addExpense = this.addExpense.bind(this);
    this.addIncome = this.addIncome.bind(this);
    this.onDateSelect = this.onDateSelect.bind(this);
    this.getCalendar = this.getCalendar.bind(this);
    this.editExpense = this.editExpense.bind(this);
    this.editIncome = this.editIncome.bind(this);
  }

  addExpense() {
    const { prepareExpenseDate, selectedDate } = this.props;
    prepareExpenseDate(selectedDate);
    this.goTo('add_expense');
  }

  addIncome() {
    const { prepareIncomeDate, selectedDate } = this.props;
    prepareIncomeDate(selectedDate);
    this.goTo('add_income');
  }

  editExpense(id) {
    const { prepareEditExpenseForm, expenses } = this.props;
    const expenseToEdit = _.find(expenses, (e) => e.id === id);
    prepareEditExpenseForm(expenseToEdit);
    this.goTo('edit_expense');
  }

  editIncome(id) {
    const { prepareEditIncomeForm, incomes } = this.props;
    const incomeToEdit = _.find(incomes, (i) => i.id === id);
    prepareEditIncomeForm(incomeToEdit);
    this.goTo('edit_income');
  }

  getDrawer(drawer) {
    const { createDrawer } = this.props;
    createDrawer(drawer);
  }

  onDateSelect(date) {
    const { calendar, selectedDate, selectCalendarDate } = this.props;
    const currentDate = moment(selectedDate);
    const newDate = moment(date);

    if (currentDate.year() === newDate.year() &&
      currentDate.month() === newDate.month() &&
      currentDate.date() === newDate.date()) {
      return calendar.selectDate(null);
    }

    selectCalendarDate(date);
  }

  getCalendar(calendar) {
    const { createCalendar } = this.props;
    createCalendar(calendar);
  }

  goTo(route) {
    const { push } = this.props;

    push({
      key: route
    });
  }

  render() {
    const {
      categoriesCount,
      itemsCount,
      currentIncome,
      currentSalary,
      selectedDate,
      eventsDate,
      currentExpense,
      currency,
      selectedEvents,
    } = this.props;

    const MenuComponent = (
      <Menu
        categoriesCount={categoriesCount}
        currency={currency}
        currentExpense={currentExpense}
        currentIncome={currentIncome}
        currentSalary={currentSalary}
        goTo={this.goTo}
        itemsCount={itemsCount}
      />
    );

    return (
      <Drawer
        closedDrawerOffset={0.0}
        content={MenuComponent}
        openDrawerOffset={0.2}
        panCloseMask={0.2}
        panOpenMask={0.1}
        panThreshold={0.25}
        ref={this.getDrawer}
        side="left"
        styles={drawerStyles}
        tapToClose
        tweenHandler={(ratio) => ({
          main: { opacity: (2 - ratio) / 2 }
        })}
        type="overlay">
        <Overview
          addExpense={this.addExpense}
          addIncome={this.addIncome}
          editExpense={this.editExpense}
          editIncome={this.editIncome}
          events={selectedEvents}
          eventsDate={eventsDate}
          getCalendar={this.getCalendar}
          onDateSelect={this.onDateSelect}
          selectedDate={selectedDate} />
      </Drawer >
    );
  }
}

HomeContainer.propTypes = {
  createDrawer: PropTypes.func.isRequired,
  push: PropTypes.func.isRequired,
  selectedDate: PropTypes.any,
  eventsDate: PropTypes.array,
  currentExpense: PropTypes.number,
  currency: PropTypes.string,
  categoriesCount: PropTypes.number,
  itemsCount: PropTypes.number,
  currentIncome: PropTypes.number,
  currentSalary: PropTypes.number,
  prepareExpenseDate: PropTypes.func.isRequired,
  prepareIncomeDate: PropTypes.func.isRequired,
  selectCalendarDate: PropTypes.func.isRequired,
  createCalendar: PropTypes.func.isRequired,
  calendar: PropTypes.object,
  selectedEvents: PropTypes.array,
  prepareEditExpenseForm: PropTypes.func.isRequired,
  prepareEditIncomeForm: PropTypes.func.isRequired,
  expenses: PropTypes.array,
  incomes: PropTypes.array,
};

function calculateCurrentIncome(incomes) {
  const filteredIncomes = _.filter(incomes, (income) => {
    const incomeDate = moment(income.date);
    const currentDate = moment();
    return incomeDate.month() === currentDate.month() &&
      incomeDate.year() === currentDate.year();
  });
  return _.sumBy(filteredIncomes, 'value');
}

function calculateCurrentExpense(expenses) {
  const filteredIncomes = _.filter(expenses, (expense) => {
    const expenseDate = moment(expense.date);
    const currentDate = moment();
    return expenseDate.month() === currentDate.month() &&
      expenseDate.year() === currentDate.year();
  });
  return _.sumBy(filteredIncomes, 'value');
}

function getEventDates(ebudgie) {
  const incomeDates = _.map(ebudgie.incomes, (income) => {
    return moment(income.date).format('YYYY-MM-DD');
  });

  const expenseDates = _.map(ebudgie.expenses, (expense) => {
    return moment(expense.date).format('YYYY-MM-DD');
  });

  return incomeDates.concat(expenseDates);
}

function getSelectedEvents(selectedDate, ebudgie) {
  const incomes = _.filter(ebudgie.incomes, (income) => {
    const currentMoment = moment(selectedDate);
    const incomeMoment = moment(income.date);

    return currentMoment.year() === incomeMoment.year() &&
      currentMoment.month() === incomeMoment.month() &&
      currentMoment.date() === incomeMoment.date();
  });

  const expenses = _.filter(ebudgie.expenses, (expense) => {
    const currentMoment = moment(selectedDate);
    const expenseMoment = moment(expense.date);

    return currentMoment.year() === expenseMoment.year() &&
      currentMoment.month() === expenseMoment.month() &&
      currentMoment.date() === expenseMoment.date();
  });

  const events = _.map(incomes.concat(expenses), event => {
    const mappedEvent = {
      id: event.id,
      value: event.value,
      date: event.date,
    };

    const category = _.find(ebudgie.categories, c => c.id === event.categoryId);
    const item = _.find(ebudgie.items, i => i.id === event.itemId);

    const translatedCategory = translateOne(category, CATEGORY_PROP);
    const translatedItem = translateOne(item, ITEM_PROP);

    mappedEvent.category = translatedCategory.title;
    mappedEvent.icon = translatedCategory.icon;
    mappedEvent.color = translatedCategory.color;
    mappedEvent.item = translatedItem.name;

    return mappedEvent;
  });

  return events;
}

function mapStateToProps(state) {
  const { salaries, expenses, incomes } = state.ebudgie;
  const currentSalary = salaries[salaries.length - 1] || {};

  return {
    expenses,
    incomes,
    currency: state.ebudgie.currency,
    categoriesCount: state.ebudgie.categories.length,
    itemsCount: state.ebudgie.items.length,
    currentIncome: calculateCurrentIncome(state.ebudgie.incomes),
    currentExpense: calculateCurrentExpense(state.ebudgie.expenses),
    currentSalary: currentSalary.value || 0,
    selectedDate: state.calendar.selectedDate,
    eventsDate: getEventDates(state.ebudgie),
    calendar: state.calendar.instance,
    selectedEvents: getSelectedEvents(state.calendar.selectedDate, state.ebudgie),
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    createDrawer: createNewDrawer,
    push: pushRoute,
    prepareExpenseDate: setExpenseDate,
    prepareIncomeDate: setIncomeDate,
    createCalendar: createNewCalendar,
    selectCalendarDate: setCalendarDate,
    prepareEditExpenseForm: populateEditExpenseForm,
    prepareEditIncomeForm: populateEditIncomeForm,
  }, dispatch);
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(HomeContainer);
<commit_msg>Go to edit salary if the user just logged and don't have salary<commit_after>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Drawer from 'react-native-drawer';
import _ from 'lodash';
import moment from 'moment';

import { createNewDrawer } from '../boundActionCreators/drawer';
import { pushRoute } from '../boundActionCreators/navigation';
import { setExpenseDate } from '../actionCreators/addExpenseForm';
import { setIncomeDate } from '../actionCreators/addIncomeForm';
import { populateEditExpenseForm } from '../actionCreators/editExpenseForm';
import { populateEditIncomeForm } from '../actionCreators/editIncomeForm';
import { setCalendarDate, createNewCalendar } from '../actionCreators/calendar';
import Menu from '../components/Drawer/Menu';
import Overview from '../components/Overview';
import { translateOne } from '../services/translator';
import { CATEGORY_PROP, ITEM_PROP } from '../constants/TranslationProps';

// This should be a plain object
const drawerStyles = {
  drawer: {
    borderRightColor: 'rgba(0,0,0,1)',
    borderRightWidth: 0,
    elevation: 5,
    shadowColor: '#000000',
    shadowOpacity: 0.8,
    shadowRadius: 3
  },
  main: {
  }
};

class HomeContainer extends Component {
  constructor(state) {
    super(state);
    this.getDrawer = this.getDrawer.bind(this);
    this.goTo = this.goTo.bind(this);
    this.addExpense = this.addExpense.bind(this);
    this.addIncome = this.addIncome.bind(this);
    this.onDateSelect = this.onDateSelect.bind(this);
    this.getCalendar = this.getCalendar.bind(this);
    this.editExpense = this.editExpense.bind(this);
    this.editIncome = this.editIncome.bind(this);
  }

  componentWillMount = () => {
    const { currentSalary, push } = this.props;

    if (!(currentSalary && currentSalary > 0)) {
      return push({ key: 'edit_salary' });
    }
  }

  addExpense() {
    const { prepareExpenseDate, selectedDate } = this.props;
    prepareExpenseDate(selectedDate);
    this.goTo('add_expense');
  }

  addIncome() {
    const { prepareIncomeDate, selectedDate } = this.props;
    prepareIncomeDate(selectedDate);
    this.goTo('add_income');
  }

  editExpense(id) {
    const { prepareEditExpenseForm, expenses } = this.props;
    const expenseToEdit = _.find(expenses, (e) => e.id === id);
    prepareEditExpenseForm(expenseToEdit);
    this.goTo('edit_expense');
  }

  editIncome(id) {
    const { prepareEditIncomeForm, incomes } = this.props;
    const incomeToEdit = _.find(incomes, (i) => i.id === id);
    prepareEditIncomeForm(incomeToEdit);
    this.goTo('edit_income');
  }

  getDrawer(drawer) {
    const { createDrawer } = this.props;
    createDrawer(drawer);
  }

  onDateSelect(date) {
    const { calendar, selectedDate, selectCalendarDate } = this.props;
    const currentDate = moment(selectedDate);
    const newDate = moment(date);

    if (currentDate.year() === newDate.year() &&
      currentDate.month() === newDate.month() &&
      currentDate.date() === newDate.date()) {
      return calendar.selectDate(null);
    }

    selectCalendarDate(date);
  }

  getCalendar(calendar) {
    const { createCalendar } = this.props;
    createCalendar(calendar);
  }

  goTo(route) {
    const { push } = this.props;

    push({
      key: route
    });
  }

  render() {
    const {
      categoriesCount,
      itemsCount,
      currentIncome,
      currentSalary,
      selectedDate,
      eventsDate,
      currentExpense,
      currency,
      selectedEvents,
    } = this.props;

    const MenuComponent = (
      <Menu
        categoriesCount={categoriesCount}
        currency={currency}
        currentExpense={currentExpense}
        currentIncome={currentIncome}
        currentSalary={currentSalary}
        goTo={this.goTo}
        itemsCount={itemsCount}
      />
    );

    return (
      <Drawer
        closedDrawerOffset={0.0}
        content={MenuComponent}
        openDrawerOffset={0.2}
        panCloseMask={0.2}
        panOpenMask={0.1}
        panThreshold={0.25}
        ref={this.getDrawer}
        side="left"
        styles={drawerStyles}
        tapToClose
        tweenHandler={(ratio) => ({
          main: { opacity: (2 - ratio) / 2 }
        })}
        type="overlay">
        <Overview
          addExpense={this.addExpense}
          addIncome={this.addIncome}
          editExpense={this.editExpense}
          editIncome={this.editIncome}
          events={selectedEvents}
          eventsDate={eventsDate}
          getCalendar={this.getCalendar}
          onDateSelect={this.onDateSelect}
          selectedDate={selectedDate} />
      </Drawer >
    );
  }
}

HomeContainer.propTypes = {
  createDrawer: PropTypes.func.isRequired,
  push: PropTypes.func.isRequired,
  selectedDate: PropTypes.any,
  eventsDate: PropTypes.array,
  currentExpense: PropTypes.number,
  currency: PropTypes.string,
  categoriesCount: PropTypes.number,
  itemsCount: PropTypes.number,
  currentIncome: PropTypes.number,
  currentSalary: PropTypes.number,
  prepareExpenseDate: PropTypes.func.isRequired,
  prepareIncomeDate: PropTypes.func.isRequired,
  selectCalendarDate: PropTypes.func.isRequired,
  createCalendar: PropTypes.func.isRequired,
  calendar: PropTypes.object,
  selectedEvents: PropTypes.array,
  prepareEditExpenseForm: PropTypes.func.isRequired,
  prepareEditIncomeForm: PropTypes.func.isRequired,
  expenses: PropTypes.array,
  incomes: PropTypes.array,
};

function calculateCurrentIncome(incomes) {
  const filteredIncomes = _.filter(incomes, (income) => {
    const incomeDate = moment(income.date);
    const currentDate = moment();
    return incomeDate.month() === currentDate.month() &&
      incomeDate.year() === currentDate.year();
  });
  return _.sumBy(filteredIncomes, 'value');
}

function calculateCurrentExpense(expenses) {
  const filteredIncomes = _.filter(expenses, (expense) => {
    const expenseDate = moment(expense.date);
    const currentDate = moment();
    return expenseDate.month() === currentDate.month() &&
      expenseDate.year() === currentDate.year();
  });
  return _.sumBy(filteredIncomes, 'value');
}

function getEventDates(ebudgie) {
  const incomeDates = _.map(ebudgie.incomes, (income) => {
    return moment(income.date).format('YYYY-MM-DD');
  });

  const expenseDates = _.map(ebudgie.expenses, (expense) => {
    return moment(expense.date).format('YYYY-MM-DD');
  });

  return incomeDates.concat(expenseDates);
}

function getSelectedEvents(selectedDate, ebudgie) {
  const incomes = _.filter(ebudgie.incomes, (income) => {
    const currentMoment = moment(selectedDate);
    const incomeMoment = moment(income.date);

    return currentMoment.year() === incomeMoment.year() &&
      currentMoment.month() === incomeMoment.month() &&
      currentMoment.date() === incomeMoment.date();
  });

  const expenses = _.filter(ebudgie.expenses, (expense) => {
    const currentMoment = moment(selectedDate);
    const expenseMoment = moment(expense.date);

    return currentMoment.year() === expenseMoment.year() &&
      currentMoment.month() === expenseMoment.month() &&
      currentMoment.date() === expenseMoment.date();
  });

  const events = _.map(incomes.concat(expenses), event => {
    const mappedEvent = {
      id: event.id,
      value: event.value,
      date: event.date,
    };

    const category = _.find(ebudgie.categories, c => c.id === event.categoryId);
    const item = _.find(ebudgie.items, i => i.id === event.itemId);

    const translatedCategory = translateOne(category, CATEGORY_PROP);
    const translatedItem = translateOne(item, ITEM_PROP);

    mappedEvent.category = translatedCategory.title;
    mappedEvent.icon = translatedCategory.icon;
    mappedEvent.color = translatedCategory.color;
    mappedEvent.item = translatedItem.name;

    return mappedEvent;
  });

  return events;
}

function mapStateToProps(state) {
  const { salaries, expenses, incomes } = state.ebudgie;
  const currentSalary = salaries[salaries.length - 1] || {};

  return {
    expenses,
    incomes,
    currency: state.ebudgie.currency,
    categoriesCount: state.ebudgie.categories.length,
    itemsCount: state.ebudgie.items.length,
    currentIncome: calculateCurrentIncome(state.ebudgie.incomes),
    currentExpense: calculateCurrentExpense(state.ebudgie.expenses),
    currentSalary: currentSalary.value || 0,
    selectedDate: state.calendar.selectedDate,
    eventsDate: getEventDates(state.ebudgie),
    calendar: state.calendar.instance,
    selectedEvents: getSelectedEvents(state.calendar.selectedDate, state.ebudgie),
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    createDrawer: createNewDrawer,
    push: pushRoute,
    prepareExpenseDate: setExpenseDate,
    prepareIncomeDate: setIncomeDate,
    createCalendar: createNewCalendar,
    selectCalendarDate: setCalendarDate,
    prepareEditExpenseForm: populateEditExpenseForm,
    prepareEditIncomeForm: populateEditIncomeForm,
  }, dispatch);
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(HomeContainer);
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');

/**
 * Register sequelize as a Hapi plugin
 * @param plugin
 * @param options
 * @param next
 */
exports.register = function(plugin, options, next) {

    var db = {};
    var dir = path.join(process.cwd(), options.models);

    var sequelize = new Sequelize(options.database, options.user, options.pass, {
        host: options.host || 'localhost',
        dialect: options.dialect || 'mysql',
        port: options.port || 3306,
        define: options.defaults || {}
    });

    //recursively get all models in 'models' directory, and all nested sub-directories
    var getJSModels = function (folder) {
        var fileContents = fs.readdirSync(folder),
            stats;

        fileContents.forEach(function (fileName) {
            stats = fs.lstatSync(folder + '/' + fileName);

            if (stats.isDirectory()) {
                getJSModels(folder + '/' + fileName)
            } else {
                if(fileName.indexOf('.') !== 0) {
                    var filePath = path.join(folder, fileName);
                    console.log(filePath);
                    var model = sequelize.import(filePath);
                    db[model.name] = model;
                }
            }
        });

    };

    getJSModels(dir);

    Object.keys(db).forEach(function(modelName) {
        if ("associate" in db[modelName]) {
            db[modelName].associate(db);
        }
    });

    db.sequelize = sequelize;
    db.Sequelize = Sequelize;

    plugin.expose('db', db);

    next();
};

exports.register.attributes = {
    pkg: require('../package.json')
};
<commit_msg>Update index.js to recursively fetch models in nested folders<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');

/**
 * Register sequelize as a Hapi plugin
 * @param plugin
 * @param options
 * @param next
 */
exports.register = function(plugin, options, next) {

    var db = {};
    var dir = path.join(process.cwd(), options.models);

    var sequelize = new Sequelize(options.database, options.user, options.pass, {
        host: options.host || 'localhost',
        dialect: options.dialect || 'mysql',
        port: options.port || 3306,
        define: options.defaults || {}
    });

    //recursively get all models in 'models' directory, and all nested sub-directories
    var getJSModels = function (folder) {
        var fileContents = fs.readdirSync(folder),
            stats;

        fileContents.forEach(function (fileName) {
            stats = fs.lstatSync(folder + '/' + fileName);

            if (stats.isDirectory()) {
                getJSModels(folder + '/' + fileName)
            } else {
                if(fileName.indexOf('.') !== 0) {
                    var filePath = path.join(folder, fileName);
                    var model = sequelize.import(filePath);
                    db[model.name] = model;
                }
            }
        });

    };

    getJSModels(dir);

    Object.keys(db).forEach(function(modelName) {
        if ("associate" in db[modelName]) {
            db[modelName].associate(db);
        }
    });

    db.sequelize = sequelize;
    db.Sequelize = Sequelize;

    plugin.expose('db', db);

    next();
};

exports.register.attributes = {
    pkg: require('../package.json')
};
<|endoftext|>