<commit_before>var gulp = require('gulp');
// js
var browserify = require('browserify');
var uglify     = require('gulp-uglify');
var header     = require('gulp-header');
var replace    = require('gulp-replace');

var collapse   = require('bundle-collapser/plugin');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');

/////////
/// pages
/////

var rootdirname = __dirname;

gulp.task('page-js', function(){
  var headerTxt = '/* ' + new Date().getFullYear() + '- generated at ' + new Date() + '\n*/';
  var browserifyOption = {
	    entries: './pages/pages.js',
	    extensions: ['.js'],
	    //debug: true,
	  };

	  var b = browserify(browserifyOption);
	  var bundler = b
	    .transform('partialify')
	    .transform('babelify', {
	      compact: "auto",
	        ignore: [],
	        presets: ['es2015', 'react']
	      });

	  var rebundle = function() {
	    var rc = bundler.plugin(collapse)
	      .bundle()
	      .pipe(source('page.js'))
	      .pipe(buffer())
	  //    .pipe(uglify())
	      .pipe(header(headerTxt))
	      .pipe(gulp.dest(rootdirname));

	      return rc;
	    };
	  bundler = bundler.on('update', rebundle);
	  return rebundle();
});

gulp.task('page-css', function(){
  return 0;/*gulp.src("./pages/pages.less")
    .pipe(less())
    .pipe(rename('page.css'))
    .pipe(gulp.dest(rootdirname));*/
});

/////////
// dist
/////////
gulp.task('full', function(){

  var headerTxt = '/* ' + new Date().getFullYear() + '- generated at ' + new Date() + '\n*/';
  var browserifyOption = {
    entries: './src/Graph.jsx',
    extensions: ['.js','.jsx']
  };

  var b = browserify(browserifyOption);
  var bundler = b
    .transform('partialify')
    .transform('babelify', {
      compact: "auto",
      ignore: [],
      presets: ['es2015', 'react']
  }).external('react');

  var rebundle = function() {
    var rc = bundler.plugin(collapse)
      .bundle()
      .pipe(source('reactchart.js'))
      .pipe(buffer())
      .pipe(header(headerTxt))
      .pipe(gulp.dest('./dist'));

      return rc;
    };
  bundler = bundler.on('update', rebundle);
  return rebundle();
});

gulp.task('min', function(){

  var headerTxt = '/* ' + new Date().getFullYear() + '- generated at ' + new Date() + '\n*/';
  var browserifyOption = {
    entries: './src/Graph.jsx',
    extensions: ['.js','.jsx']
    //debug: true,
  };

  var b = browserify(browserifyOption);
  var bundler = b
    .transform('partialify')
    .transform('babelify', {
      compact: "auto",
      ignore: [],
      presets: ['es2015', 'react']
  }).external('react');

  var rebundle = function() {
    var rc = bundler.plugin(collapse)
      .bundle()
      .pipe(source('reactchart.min.js'))
      .pipe(buffer())
      .pipe(uglify())
      .pipe(header(headerTxt))
      .pipe(gulp.dest('./dist'));

      return rc;
    };
  bundler = bundler.on('update', rebundle);
  return rebundle();
});

////////////
// jsx -> js in require
///////////

gulp.task('jsx2js', () => {
  return gulp.src(['.lib/*.js',"./lib/**/*.js"])
    .pipe(replace(/\.jsx/g,'.js'))
    .pipe(gulp.dest('./lib'));
});

gulp.task('dist',['full','min'],() => 0);

gulp.task('doc',['page-js','page-css'],() => 0);

gulp.task('default',['dist','doc'],() => 0);
<commit_msg>gilp task for repointing to lib<commit_after>var gulp = require('gulp');
// js
var browserify = require('browserify');
var uglify     = require('gulp-uglify');
var header     = require('gulp-header');
var replace    = require('gulp-replace');

var collapse   = require('bundle-collapser/plugin');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');

/////////
/// pages
/////

var rootdirname = __dirname;

gulp.task('page-js', function(){
  var headerTxt = '/* ' + new Date().getFullYear() + '- generated at ' + new Date() + '\n*/';
  var browserifyOption = {
	    entries: './pages/pages.js',
	    extensions: ['.js'],
	    //debug: true,
	  };

	  var b = browserify(browserifyOption);
	  var bundler = b
	    .transform('partialify')
	    .transform('babelify', {
	      compact: "auto",
	        ignore: [],
	        presets: ['es2015', 'react']
	      });

	  var rebundle = function() {
	    var rc = bundler.plugin(collapse)
	      .bundle()
	      .pipe(source('page.js'))
	      .pipe(buffer())
	  //    .pipe(uglify())
	      .pipe(header(headerTxt))
	      .pipe(gulp.dest(rootdirname));

	      return rc;
	    };
	  bundler = bundler.on('update', rebundle);
	  return rebundle();
});

gulp.task('page-css', function(){
  return 0;/*gulp.src("./pages/pages.less")
    .pipe(less())
    .pipe(rename('page.css'))
    .pipe(gulp.dest(rootdirname));*/
});

/////////
// dist
/////////
gulp.task('full', function(){

  var headerTxt = '/* ' + new Date().getFullYear() + '- generated at ' + new Date() + '\n*/';
  var browserifyOption = {
    entries: './src/Graph.jsx',
    extensions: ['.js','.jsx']
  };

  var b = browserify(browserifyOption);
  var bundler = b
    .transform('partialify')
    .transform('babelify', {
      compact: "auto",
      ignore: [],
      presets: ['es2015', 'react']
  }).external('react');

  var rebundle = function() {
    var rc = bundler.plugin(collapse)
      .bundle()
      .pipe(source('reactchart.js'))
      .pipe(buffer())
      .pipe(header(headerTxt))
      .pipe(gulp.dest('./dist'));

      return rc;
    };
  bundler = bundler.on('update', rebundle);
  return rebundle();
});

gulp.task('min', function(){

  var headerTxt = '/* ' + new Date().getFullYear() + '- generated at ' + new Date() + '\n*/';
  var browserifyOption = {
    entries: './src/Graph.jsx',
    extensions: ['.js','.jsx']
    //debug: true,
  };

  var b = browserify(browserifyOption);
  var bundler = b
    .transform('partialify')
    .transform('babelify', {
      compact: "auto",
      ignore: [],
      presets: ['es2015', 'react']
  }).external('react');

  var rebundle = function() {
    var rc = bundler.plugin(collapse)
      .bundle()
      .pipe(source('reactchart.min.js'))
      .pipe(buffer())
      .pipe(uglify())
      .pipe(header(headerTxt))
      .pipe(gulp.dest('./dist'));

      return rc;
    };
  bundler = bundler.on('update', rebundle);
  return rebundle();
});

////////////
// jsx -> js in require
///////////

gulp.task('jsx2js', () => {
  return gulp.src(['.lib/*.js',"./lib/**/*.js"])
    .pipe(replace(/\.jsx/g,'.js'))
    .pipe(gulp.dest('./lib'));
});

////////////
// src -> lib in index
///////////

gulp.task('src2libIdx', () => {
  return gulp.src(["./index.js"])
    .pipe(replace(/src/g,'lib'))
    .pipe(gulp.dest('.'));
});

gulp.task('src2libHlp', () => {
  return gulp.src(["./helpers/index.js"])
    .pipe(replace(/src/g,'lib'))
    .pipe(gulp.dest('./helpers'));
});

gulp.task('src2lib',["src2libIdx","src2libHlp"],() => 0);

gulp.task('dist',['full','min'],() => 0);

gulp.task('doc',['page-js','page-css'],() => 0);

gulp.task('default',['dist','doc'],() => 0);
<|endoftext|>


<commit_before>app.SVGRenderer = class extends app.Renderer {
    /**
     * @param {number} width
     * @param {number} height
     */
    constructor(width, height) {
        super();
        this._element = this._createSVG('svg');
        this._scale = 1;
        this._offset = new g.Vec(0, 0);
        this._layout = null;
        this._isDirtyTransform = false;
        this._isDirtyLayout = false;
        this.setSize(width, height);
    }

    _createSVG(name) {
        return document.createElementNS('http://www.w3.org/2000/svg', name);
    }

    /**
     * @override
     * @return {!Element}
     */
    element() {
        return this._element;
    }

    /**
     * @override
     * @param {number} width
     * @param {number} height
     */
    setSize(width, height) {
        if (g.eq(width, this._width) && g.eq(height, this._height))
            return;
        this._width = width;
        this._height = height;
        this._element.setAttribute('width', width + 'px');
        this._element.setAttribute('height', height + 'px');
        this._isDirtyTransform = true;
    }

    /**
     * @override
     * @return {{width: number, height: number}}
     */
    size() {
        return {width: this._width, height: this._height};
    }

    /**
     * @param {number} scale
     */
    setScale(scale) {
        this._scale = scale;
        this._isDirtyTransform = true;
    }

    /**
     * @override
     * @return {number}
     */
    scale() {
        return this._scale;
    }

    /**
     * @override
     * @param {!g.Vec} offset
     */
    setOffset(offset) {
        this._offset = offset;
        this._isDirtyTransform = true;
    }

    /**
     * @override
     * @return {!g.Vec}
     */
    offset() {
        return this._offset;
    }

    setDatesFormatter(formatter) {
        if (this._datesFormatter === formatter)
            return;
        this._datesFormatter = formatter;
        this._isDirtyLayout = true;
    }

    _setTransformAttribute() {
        if (!this._container)
            return;
        var value = 'translate(' + (this._width/2) + ', ' + (this._height/2) + ') ';
        value += 'translate(' + this._offset.x + ', ' + this._offset.y + ') ';
        value += 'scale(' + this._scale + ', ' + this._scale + ') ';
        this._container.setAttribute('transform', value);
    }

    /**
     * @param {!app.Layout} layout
     */
    setLayout(layout) {
        if (this._layout === layout)
            return;
        this._layout = layout;
        this._isDirtyLayout = true;
    }

    /**
     * @override
     */
    render() {
        if (this._isDirtyTransform && !this._isDirtyLayout) {
            this._isDirtyTransform = false;
            this._setTransformAttribute();
            return;
        }
        if (!this._isDirtyLayout)
            return;
        this._isDirtyLayout = false;
        this._isDirtyTransform = false;
        if (this._container)
            this._container.remove();
        this._container = this._createSVG('g');
        this._container.setAttribute('style', 'will-change:transform;pointer-events: none');
        this._element.appendChild(this._container);
        this._setTransformAttribute();
        if (!this._layout)
            return;

        if (this._layout.backgroundImage) {
            var img = this._layout.backgroundImage;
            var image = this._createSVG('image');
            image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href',img.image.src);
            image.setAttribute('x', img.topLeft.x);
            image.setAttribute('y', img.topLeft.y);
            image.setAttribute('width', img.image.width);
            image.setAttribute('height', img.image.height);
            if (img.image.src.indexOf('_2x.') !== -1)
                image.classList.add('hidpi-image');
            this._container.appendChild(image);
        }

        this._renderScaffolding(this._container, this._layout.scaffolding);

        var radius = this._layout.personRadius;
        for (var person of this._layout.positions.keys()) {
            var position = this._layout.positions.get(person);
            var rotation = this._layout.rotations.get(person);
            var isRoot = person === this._layout.root;
            this._container.appendChild(this._renderPerson(person, position, rotation, radius, isRoot));
        }
    }

    /**
     * @param {!Element} container
     * @param {!app.Layout} layout
     */
    _renderScaffolding(container, scaffolding) {
        var path = '';
        for (var shape of scaffolding) {
            if (shape instanceof g.Line) {
                var line = /** @type {!g.Line} */(shape);
                path += ' M' + line.from.x + ' ' + line.from.y;
                path += ' L ' + line.to.x + ' ' + line.to.y;
            } else if (shape instanceof g.Arc) {
                var arc = /** @type {!g.Arc} */(shape);
                path += ' M' + arc.from.x + ' ' + arc.from.y;
                path += ' A ' + arc.r + ' ' + arc.r;
                var isLargeArc = g.normalizeRad(arc.toAngle - arc.fromAngle) > Math.PI;
                var component = isLargeArc ? ' 1 1' : ' 0 1';
                path += ' 0 ' + component;
                path += ' ' + arc.to.x + ' ' + arc.to.y;
            } else if (shape instanceof g.Bezier) {
                var bezier = /** @type {!g.Bezier} */(shape);
                path += ' M' + bezier.from.x + ' ' + bezier.from.y;
                path += ' Q ' + bezier.cp.x + ' ' + bezier.cp.y + ' ' + bezier.to.x + ' ' + bezier.to.y;
            }
        }

        var element = this._createSVG('path');
        element.classList.add('scaffolding');
        element.setAttribute('d', path);
        container.appendChild(element);
    }

    /**
     * @param {!app.Person} person
     * @return {!Element}
     */
    _renderPerson(person, position, rotation, personRadius, isRoot) {
        rotation = g.normalizeRad(rotation);
        var textOnLeft = rotation > Math.PI / 2 && rotation < 3 * Math.PI / 2;
        if (textOnLeft)
            rotation -= Math.PI;
        rotation = g.radToDeg(rotation);

        var group = this._createSVG('g');
        var transform = 'translate(' + position.x + ', ' + position.y + ') ';
        transform += 'rotate(' + rotation + ')';
        group.setAttribute('transform', transform);
        group.classList.add('person');
        if (person.deceased)
            group.classList.add('deceased');
        if (person.gender === app.Gender.Male)
            group.classList.add('sex-male');
        else if (person.gender === app.Gender.Female)
            group.classList.add('sex-female');
        else
            group.classList.add('sex-other');
        if (person.isChild())
            group.classList.add('infant');
        if (isRoot)
            group.classList.add('root');

        var circle = this._createSVG('circle');
        circle.setAttribute('r', personRadius);
        group.appendChild(circle);

        var fullName = this._createSVG('text');
        fullName.classList.add('name');
        fullName.textContent = person.fullName();
        fullName.setAttribute('y', '-0.35em');
        group.appendChild(fullName);

        var dates = this._createSVG('text');
        dates.setAttribute('dominant-baseline', 'text-before-edge');
        dates.classList.add('dates');
        dates.textContent = this._datesFormatter(person);
        dates.setAttribute('y', 0);
        group.appendChild(dates);

        var textPadding = 6;
        if (isRoot) {
            fullName.setAttribute('text-anchor', 'middle');
            fullName.setAttribute('x', 0);
            dates.setAttribute('text-anchor', 'middle');
            dates.setAttribute('x', 0);
        } else if (textOnLeft) {
            fullName.setAttribute('x', -personRadius - textPadding);
            fullName.setAttribute('text-anchor', 'end');
            dates.setAttribute('x', -personRadius - textPadding);
            dates.setAttribute('text-anchor', 'end');
        } else {
            fullName.setAttribute('x', personRadius + textPadding);
            dates.setAttribute('x', personRadius + textPadding);
        }
        return group;
    }

    createPersonIcon(size, gender, isChild, isDeceased) {
        var svg = this._createSVG('svg');
        svg.classList.add('legend');
        svg.setAttribute('width', size + 2);
        svg.setAttribute('height', size + 2);
        var radius = size / 2;
        var thisYear = new Date().getFullYear();
        var birthYear = isChild ? thisYear : 0;
        var deathYear = isDeceased ? thisYear : null;
        var person = new app.Person('', '', gender, birthYear, deathYear);
        person.deceased = isDeceased;
        svg.appendChild(this._renderPerson(person, new g.Vec(radius+1, radius+1), 0, radius, false));
        return svg;
    }
}
<commit_msg>Center names for those who don't have dates. Closes #14.<commit_after>app.SVGRenderer = class extends app.Renderer {
    /**
     * @param {number} width
     * @param {number} height
     */
    constructor(width, height) {
        super();
        this._element = this._createSVG('svg');
        this._scale = 1;
        this._offset = new g.Vec(0, 0);
        this._layout = null;
        this._isDirtyTransform = false;
        this._isDirtyLayout = false;
        this.setSize(width, height);
    }

    _createSVG(name) {
        return document.createElementNS('http://www.w3.org/2000/svg', name);
    }

    /**
     * @override
     * @return {!Element}
     */
    element() {
        return this._element;
    }

    /**
     * @override
     * @param {number} width
     * @param {number} height
     */
    setSize(width, height) {
        if (g.eq(width, this._width) && g.eq(height, this._height))
            return;
        this._width = width;
        this._height = height;
        this._element.setAttribute('width', width + 'px');
        this._element.setAttribute('height', height + 'px');
        this._isDirtyTransform = true;
    }

    /**
     * @override
     * @return {{width: number, height: number}}
     */
    size() {
        return {width: this._width, height: this._height};
    }

    /**
     * @param {number} scale
     */
    setScale(scale) {
        this._scale = scale;
        this._isDirtyTransform = true;
    }

    /**
     * @override
     * @return {number}
     */
    scale() {
        return this._scale;
    }

    /**
     * @override
     * @param {!g.Vec} offset
     */
    setOffset(offset) {
        this._offset = offset;
        this._isDirtyTransform = true;
    }

    /**
     * @override
     * @return {!g.Vec}
     */
    offset() {
        return this._offset;
    }

    setDatesFormatter(formatter) {
        if (this._datesFormatter === formatter)
            return;
        this._datesFormatter = formatter;
        this._isDirtyLayout = true;
    }

    _setTransformAttribute() {
        if (!this._container)
            return;
        var value = 'translate(' + (this._width/2) + ', ' + (this._height/2) + ') ';
        value += 'translate(' + this._offset.x + ', ' + this._offset.y + ') ';
        value += 'scale(' + this._scale + ', ' + this._scale + ') ';
        this._container.setAttribute('transform', value);
    }

    /**
     * @param {!app.Layout} layout
     */
    setLayout(layout) {
        if (this._layout === layout)
            return;
        this._layout = layout;
        this._isDirtyLayout = true;
    }

    /**
     * @override
     */
    render() {
        if (this._isDirtyTransform && !this._isDirtyLayout) {
            this._isDirtyTransform = false;
            this._setTransformAttribute();
            return;
        }
        if (!this._isDirtyLayout)
            return;
        this._isDirtyLayout = false;
        this._isDirtyTransform = false;
        if (this._container)
            this._container.remove();
        this._container = this._createSVG('g');
        this._container.setAttribute('style', 'will-change:transform;pointer-events: none');
        this._element.appendChild(this._container);
        this._setTransformAttribute();
        if (!this._layout)
            return;

        if (this._layout.backgroundImage) {
            var img = this._layout.backgroundImage;
            var image = this._createSVG('image');
            image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href',img.image.src);
            image.setAttribute('x', img.topLeft.x);
            image.setAttribute('y', img.topLeft.y);
            image.setAttribute('width', img.image.width);
            image.setAttribute('height', img.image.height);
            if (img.image.src.indexOf('_2x.') !== -1)
                image.classList.add('hidpi-image');
            this._container.appendChild(image);
        }

        this._renderScaffolding(this._container, this._layout.scaffolding);

        var radius = this._layout.personRadius;
        for (var person of this._layout.positions.keys()) {
            var position = this._layout.positions.get(person);
            var rotation = this._layout.rotations.get(person);
            var isRoot = person === this._layout.root;
            this._container.appendChild(this._renderPerson(person, position, rotation, radius, isRoot));
        }
    }

    /**
     * @param {!Element} container
     * @param {!app.Layout} layout
     */
    _renderScaffolding(container, scaffolding) {
        var path = '';
        for (var shape of scaffolding) {
            if (shape instanceof g.Line) {
                var line = /** @type {!g.Line} */(shape);
                path += ' M' + line.from.x + ' ' + line.from.y;
                path += ' L ' + line.to.x + ' ' + line.to.y;
            } else if (shape instanceof g.Arc) {
                var arc = /** @type {!g.Arc} */(shape);
                path += ' M' + arc.from.x + ' ' + arc.from.y;
                path += ' A ' + arc.r + ' ' + arc.r;
                var isLargeArc = g.normalizeRad(arc.toAngle - arc.fromAngle) > Math.PI;
                var component = isLargeArc ? ' 1 1' : ' 0 1';
                path += ' 0 ' + component;
                path += ' ' + arc.to.x + ' ' + arc.to.y;
            } else if (shape instanceof g.Bezier) {
                var bezier = /** @type {!g.Bezier} */(shape);
                path += ' M' + bezier.from.x + ' ' + bezier.from.y;
                path += ' Q ' + bezier.cp.x + ' ' + bezier.cp.y + ' ' + bezier.to.x + ' ' + bezier.to.y;
            }
        }

        var element = this._createSVG('path');
        element.classList.add('scaffolding');
        element.setAttribute('d', path);
        container.appendChild(element);
    }

    /**
     * @param {!app.Person} person
     * @return {!Element}
     */
    _renderPerson(person, position, rotation, personRadius, isRoot) {
        rotation = g.normalizeRad(rotation);
        var textOnLeft = rotation > Math.PI / 2 && rotation < 3 * Math.PI / 2;
        if (textOnLeft)
            rotation -= Math.PI;
        rotation = g.radToDeg(rotation);

        var group = this._createSVG('g');
        var transform = 'translate(' + position.x + ', ' + position.y + ') ';
        transform += 'rotate(' + rotation + ')';
        group.setAttribute('transform', transform);
        group.classList.add('person');
        if (person.deceased)
            group.classList.add('deceased');
        if (person.gender === app.Gender.Male)
            group.classList.add('sex-male');
        else if (person.gender === app.Gender.Female)
            group.classList.add('sex-female');
        else
            group.classList.add('sex-other');
        if (person.isChild())
            group.classList.add('infant');
        if (isRoot)
            group.classList.add('root');

        var circle = this._createSVG('circle');
        circle.setAttribute('r', personRadius);
        group.appendChild(circle);

        var datesText = this._datesFormatter(person);

        var fullName = this._createSVG('text');
        fullName.classList.add('name');
        fullName.textContent = person.fullName();
        if (!datesText && !person.children.size) {
            fullName.setAttribute('y', '0em');
            fullName.setAttribute('dominant-baseline', 'central');
        } else {
            fullName.setAttribute('y', '-0.35em');
        }
        group.appendChild(fullName);

        var dates = this._createSVG('text');

        if (datesText) {
            dates.setAttribute('dominant-baseline', 'text-before-edge');
            dates.classList.add('dates');
            dates.textContent = datesText;
            dates.setAttribute('y', 0);
            group.appendChild(dates);
        }

        var textPadding = 6;
        if (isRoot) {
            fullName.setAttribute('text-anchor', 'middle');
            fullName.setAttribute('x', 0);
            dates.setAttribute('text-anchor', 'middle');
            dates.setAttribute('x', 0);
        } else if (textOnLeft) {
            fullName.setAttribute('x', -personRadius - textPadding);
            fullName.setAttribute('text-anchor', 'end');
            dates.setAttribute('x', -personRadius - textPadding);
            dates.setAttribute('text-anchor', 'end');
        } else {
            fullName.setAttribute('x', personRadius + textPadding);
            dates.setAttribute('x', personRadius + textPadding);
        }
        return group;
    }

    createPersonIcon(size, gender, isChild, isDeceased) {
        var svg = this._createSVG('svg');
        svg.classList.add('legend');
        svg.setAttribute('width', size + 2);
        svg.setAttribute('height', size + 2);
        var radius = size / 2;
        var thisYear = new Date().getFullYear();
        var birthYear = isChild ? thisYear : 0;
        var deathYear = isDeceased ? thisYear : null;
        var person = new app.Person('', '', gender, birthYear, deathYear);
        person.deceased = isDeceased;
        svg.appendChild(this._renderPerson(person, new g.Vec(radius+1, radius+1), 0, radius, false));
        return svg;
    }
}
<|endoftext|>


<commit_before>var apiBase = '/api/1/';

angular.module('woogleApp.services', ['ngCookies'])

.factory('AccessControl', function ($cookieStore, $rootScope) {
  $rootScope.$watch(
    function () {
      return $cookieStore.get('userRole');
    },
    function (userRole) {
      $rootScope.userRole = Number(userRole);
    }
  );
  $rootScope.userRole = $cookieStore.get('userRole');
  var authorize = function (accessLevel) {
    var userRole = $rootScope.userRole;
    if (!accessLevel && !userRole) {
      return true;
    }
    return userRole & accessControl.accessLevels[accessLevel];
  };
  return {
    authorize: authorize
  };
})

.factory('ScheduleService', function ($http) {

  var schedules = [];
  var addSchedule = function (title, start, end, allDay) {
    schedules.push({
      scheduleId: schedules.length + 1,
      title: title,
      start: start,
      end: end,
      allDay: allDay,
      location: title + '장소',
      description: title + '설명'
    });
  };

  addSchedule('Schedule 8/20-1', moment('2014-08-20'), moment('2014-08-21'), true);
  addSchedule('Schedule 8/20-2', moment('2014-08-20'), moment('2014-08-20'), true);
  addSchedule('Schedule 8/22-1', moment('2014-08-22'), moment('2014-08-22'), false);
  addSchedule('Schedule 8/22-2', moment('2014-08-22'), moment('2014-08-22'), true);
  addSchedule('Schedule 8/22-3', moment('2014-08-22'), moment('2014-08-22'), true);
  addSchedule('Schedule 8/23-1', moment('2014-08-23'), moment('2014-08-23'), true);

  return {
    readAll: function (cb) {
      $http.get('/schedule')
      .success(function (data) {
        cb(data);
      });
    },
    readByDate: function (year, month, date) {
      $http.get('/schedule')
      .success(function (data) {
        _.filter(data, function (schedule) {
          return schedule.getFullYear() == year && schedules.getMonth() == month && schedules.getDate() == date;
        });
      })
    },
    readById: function (scheduleId, cb) {
      $http.get('/schedule/' + scheduleId)
      .success(function (data) {
        cb(data);
      });
    },
    create: function (body, cb) {
      console.log(body);
      $http.post('/schedules', body)
      .success(function () {
        cb(null);
      })
      .error(function () {
        cb(true);
      });
    }
  };
})
<commit_msg>readAll<commit_after>var apiBase = '/api/1/';

angular.module('woogleApp.services', ['ngCookies'])

.factory('AccessControl', function ($cookieStore, $rootScope) {
  $rootScope.$watch(
    function () {
      return $cookieStore.get('userRole');
    },
    function (userRole) {
      $rootScope.userRole = Number(userRole);
    }
  );
  $rootScope.userRole = $cookieStore.get('userRole');
  var authorize = function (accessLevel) {
    var userRole = $rootScope.userRole;
    if (!accessLevel && !userRole) {
      return true;
    }
    return userRole & accessControl.accessLevels[accessLevel];
  };
  return {
    authorize: authorize
  };
})

.factory('ScheduleService', function ($http) {

  var schedules = [];
  var addSchedule = function (title, start, end, allDay) {
    schedules.push({
      scheduleId: schedules.length + 1,
      title: title,
      start: start,
      end: end,
      allDay: allDay,
      location: title + '장소',
      description: title + '설명'
    });
  };

  addSchedule('Schedule 8/20-1', moment('2014-08-20'), moment('2014-08-21'), true);
  addSchedule('Schedule 8/20-2', moment('2014-08-20'), moment('2014-08-20'), true);
  addSchedule('Schedule 8/22-1', moment('2014-08-22'), moment('2014-08-22'), false);
  addSchedule('Schedule 8/22-2', moment('2014-08-22'), moment('2014-08-22'), true);
  addSchedule('Schedule 8/22-3', moment('2014-08-22'), moment('2014-08-22'), true);
  addSchedule('Schedule 8/23-1', moment('2014-08-23'), moment('2014-08-23'), true);

  var convertSchedule = function (schedule) {
    schedule.scheduleId = schedule.schedule_id;
    schedule.start = schedule.start_date;
    schedule.end = schedule.end_date;
    schedule.allDay = schedule.allday;
    return schedule;
  };

  var convertSchedules = function (schedules) {
    for (var i = 0; i < schedules.length; i++) {
      schedules[i] = convertSchedule(schedules[i]);
    }
  };

  return {
    readAll: function (cb) {
      $http.get('/schedule')
      .success(function (data) {
        cb(data);
      });
    },
    readByDate: function (year, month, date) {
      $http.get('/schedule')
      .success(function (data) {
        _.filter(data, function (schedule) {
          return schedule.getFullYear() == year && schedules.getMonth() == month && schedules.getDate() == date;
        });
      })
    },
    readById: function (scheduleId, cb) {
      $http.get('/schedule/' + scheduleId)
      .success(function (data) {
        cb(data);
      });
    },
    create: function (body, cb) {
      console.log(body);
      $http.post('/schedules', body)
      .success(function () {
        cb(null);
      })
      .error(function () {
        cb(true);
      });
    }
  };
})
<|endoftext|>


<commit_before>			// container_id: id of container without hash mark
			// show_fn: function called when showing a page
			// hide_fn: function called when hiding a page
			function SiidPage(page_id,container_id, show_fn, hide_fn)
			{
				page_id = page_id
				container_id = container_id;
				show_fn = show_fn;
				hide_fn = hide_fn;

				this.getPageId = function() { return page_id }
				this.getContainerId = function() { return container_id }
				this.show = function() { if(show_fn) { show_fn() } }
				this.hide = function() { if(hide_fn) { hide_fn() } }
			}

			// the page core class that handles all pages
			function PageCore()
			{
				var pages = {};
				var current_page_id = null;

				// register a new page
				this.register = function(siidpage) {
					pages[siidpage.getPageId()] = siidpage;
				}

				// switch to a new page
				this.switchTo = function(page_id)	{
					hidePage(current_page_id)
					showPage(page_id)
				}

				function getPage(page_id)
				{
					return pages[page_id]
				}

				// execute a function fn = function(element) for each link to a certain subpage
				function forLinkTo(page_id, fn)
				{
					fn( $('a[href$="#'+page_id+'"]').parent() )
				}

				// hide a page
				function hidePage(page_id) {
					if(getPage(page_id)) {
						// hide the container
						$("#"+ getPage(page_id).getContainerId() ).css("display","none")
						// execute the hide function hook
						getPage(page_id).hide()
						// update links
						forLinkTo(page_id, function(e) { e.removeClass('active') })
						current_page_id = null;
					}
				}

				// show a page
				function showPage(page_id) {
					if(getPage(page_id)) {
						// execute the show function hook
						getPage(page_id).show()
						// update links
						forLinkTo(page_id, function(e) { e.addClass('active') })
						// show the container
						$("#"+ getPage(page_id).getContainerId() ).css("display","block")
						current_page_id = page_id;
					}
				}

			}

			// resize all display areas to a 0.5 aspect
			function resizeDisplayAreas() {
				var display_area_aspect = 0.5;

				$(".display-area").each( function() {
					$(this).css("min-height", $(this).width() * display_area_aspect);
				})
			}

			var pagecore = new PageCore();
			var hash = window.location.hash;

			window.onload = function() {
				siid_start();

				$(window).resize( resizeDisplayAreas );
				resizeDisplayAreas();

				pagecore.register(
					new SiidPage(
						"power",
						"visibility-container-power",
						null, null
					)
				)

				// show the first page
				pagecore.switchTo("power")

				// track if the hash url part changes
				setInterval( function() {
					if(hash != window.location.hash) {
						hash = window.location.hash;
						pagecore.switchTo(hash.substr(1));
					}
				}, 1000 )
			}
<commit_msg>hiding all pages<commit_after>			// container_id: id of container without hash mark
			// show_fn: function called when showing a page
			// hide_fn: function called when hiding a page
			function SiidPage(page_id,container_id, show_fn, hide_fn)
			{
				page_id = page_id
				container_id = container_id;
				show_fn = show_fn;
				hide_fn = hide_fn;

				this.getPageId = function() { return page_id }
				this.getContainerId = function() { return container_id }
				this.show = function() { if(show_fn) { show_fn() } }
				this.hide = function() { if(hide_fn) { hide_fn() } }
			}

			// the page core class that handles all pages
			function PageCore()
			{
				var pages = {};
				var current_page_id = null;

				// register a new page
				this.register = function(siidpage) {
					pages[siidpage.getPageId()] = siidpage;
				}

				// switch to a new page
				this.switchTo = function(page_id)	{
					$.each(pages,function(i,e) { hidePage(e.getPageId())})
					showPage(page_id)
				}

				function getPage(page_id)
				{
					return pages[page_id]
				}

				// execute a function fn = function(element) for each link to a certain subpage
				function forLinkTo(page_id, fn)
				{
					fn( $('a[href$="#'+page_id+'"]').parent() )
				}

				// hide a page
				function hidePage(page_id) {
					if(getPage(page_id)) {
						// hide the container
						$("#"+ getPage(page_id).getContainerId() ).css("display","none")
						// execute the hide function hook
						getPage(page_id).hide()
						// update links
						forLinkTo(page_id, function(e) { e.removeClass('active') })
						current_page_id = null;
					}
				}

				// show a page
				function showPage(page_id) {
					if(getPage(page_id)) {
						// execute the show function hook
						getPage(page_id).show()
						// update links
						forLinkTo(page_id, function(e) { e.addClass('active') })
						// show the container
						$("#"+ getPage(page_id).getContainerId() ).css("display","block")
						current_page_id = page_id;
					}
				}

			}

			// resize all display areas to a 0.5 aspect
			function resizeDisplayAreas() {
				var display_area_aspect = 0.5;

				$(".display-area").each( function() {
					$(this).css("min-height", $(this).width() * display_area_aspect);
				})
			}

			var pagecore = new PageCore();
			var hash = window.location.hash;

			window.onload = function() {
				siid_start();

				$(window).resize( resizeDisplayAreas );
				resizeDisplayAreas();

				pagecore.register(
					new SiidPage(
						"power",
						"visibility-container-power",
						null, null
					)
				)

				// show the first page
				pagecore.switchTo("power")

				// track if the hash url part changes
				setInterval( function() {
					if(hash != window.location.hash) {
						hash = window.location.hash;
						pagecore.switchTo(hash.substr(1));
					}
				}, 1000 )
			}
<|endoftext|>


<commit_before>import { forEach, isFinite, isInteger } from 'lodash'
import { forOwn as forOwnAsync } from 'promise-toolbox'
import { prompt } from 'inquirer'

// ===================================================================

const EMPTY_OBJECT = Object.freeze({ __proto__: null })

const _extractValue = ({ value }) => value

export const confirm = (message, {
  default: defaultValue = null
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  message,
  name: 'value',
  type: 'confirm'
}).then(_extractValue)

export const input = (message, {
  default: defaultValue = null,
  filter = undefined,
  validate = undefined
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  message,
  name: 'value',
  type: 'input',
  validate
}).then(_extractValue)

export const list = (message, choices, {
  default: defaultValue = null
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  choices,
  message,
  name: 'value',
  type: 'list'
}).then(_extractValue)

export const password = (message, {
  default: defaultValue = null,
  filter = undefined,
  validate = undefined
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  message,
  name: 'value',
  type: 'password',
  validate
}).then(_extractValue)

// ===================================================================

const promptByType = {
  __proto__: null,

  array: async (schema, defaultValue, path) => {
    const items = []
    if (defaultValue == null) {
      defaultValue = items
    }

    let i = 0

    const itemSchema = schema.items
    const promptItem = async () => {
      items[i] = await promptGeneric(
        itemSchema,
        defaultValue[i],
        path
          ? `${path} [${i}]`
          : `[${i}]`
      )

      ++i
    }

    let n = schema.minItems || 0
    while (i < n) { // eslint-disable-line no-unmodified-loop-condition
      await promptItem()
    }

    n = schema.maxItems || Infinity
    while (
      i < n && // eslint-disable-line no-unmodified-loop-condition
      await confirm('additional item?', {
        default: false
      })
    ) {
      await promptItem()
    }

    return items
  },

  boolean: (schema, defaultValue, path) => confirm(path, {
    default: defaultValue || schema.default
  }),

  enum: (schema, defaultValue, path) => list(path, schema.enum, {
    defaultValue: defaultValue || schema.defaultValue
  }),

  integer: (schema, defaultValue, path) => input(path, {
    default: defaultValue || schema.default,
    filter: input => +input,
    validate: input => isInteger(+input)
  }),

  number: (schema, defaultValue, path) => input(path, {
    default: defaultValue || schema.default,
    filter: input => +input,
    validate: input => isFinite(+input)
  }),

  object: async (schema, defaultValue, path) => {
    const value = {}

    const required = {}
    schema.required && forEach(schema.required, name => {
      required[name] = true
    })

    const promptProperty = async (schema, name) => {
      const subpath = path
        ? `${path} > ${schema.title || name}`
        : schema.title || name

      if (
        required[name] ||
        await confirm(`fill optional ${subpath}?`, {
          default: Boolean(defaultValue && name in defaultValue)
        })
      ) {
        value[name] = await promptGeneric(
          schema,
          defaultValue && defaultValue[name],
          subpath
        )
      }
    }

    await forOwnAsync.call(schema.properties || {}, promptProperty)

    return value
  },

  string: (schema, defaultValue, path) => input(path, {
    default: defaultValue || schema.default
  })
}

export default function promptGeneric (schema, defaultValue, path) {
  const type = schema.enum
    ? 'enum'
    : schema.type

  const prompt = promptByType[type.toLowerCase()]
  if (!prompt) {
    throw new Error(`unsupported type: ${type}`)
  }

  return prompt(schema, defaultValue, path)
}
<commit_msg>fix(xo-server-auth-ldap): correctly use previous values for booleans<commit_after>import { forEach, isFinite, isInteger } from 'lodash'
import { forOwn as forOwnAsync } from 'promise-toolbox'
import { prompt } from 'inquirer'

// ===================================================================

const EMPTY_OBJECT = Object.freeze({ __proto__: null })

const _extractValue = ({ value }) => value

export const confirm = (message, {
  default: defaultValue = null
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  message,
  name: 'value',
  type: 'confirm'
}).then(_extractValue)

export const input = (message, {
  default: defaultValue = null,
  filter = undefined,
  validate = undefined
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  message,
  name: 'value',
  type: 'input',
  validate
}).then(_extractValue)

export const list = (message, choices, {
  default: defaultValue = null
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  choices,
  message,
  name: 'value',
  type: 'list'
}).then(_extractValue)

export const password = (message, {
  default: defaultValue = null,
  filter = undefined,
  validate = undefined
} = EMPTY_OBJECT) => prompt({
  default: defaultValue,
  message,
  name: 'value',
  type: 'password',
  validate
}).then(_extractValue)

// ===================================================================

const promptByType = {
  __proto__: null,

  array: async (schema, defaultValue, path) => {
    const items = []
    if (defaultValue == null) {
      defaultValue = items
    }

    let i = 0

    const itemSchema = schema.items
    const promptItem = async () => {
      items[i] = await promptGeneric(
        itemSchema,
        defaultValue[i],
        path
          ? `${path} [${i}]`
          : `[${i}]`
      )

      ++i
    }

    let n = schema.minItems || 0
    while (i < n) { // eslint-disable-line no-unmodified-loop-condition
      await promptItem()
    }

    n = schema.maxItems || Infinity
    while (
      i < n && // eslint-disable-line no-unmodified-loop-condition
      await confirm('additional item?', {
        default: false
      })
    ) {
      await promptItem()
    }

    return items
  },

  boolean: (schema, defaultValue, path) => confirm(path, {
    default: defaultValue != null ? defaultValue : schema.default
  }),

  enum: (schema, defaultValue, path) => list(path, schema.enum, {
    defaultValue: defaultValue || schema.defaultValue
  }),

  integer: (schema, defaultValue, path) => input(path, {
    default: defaultValue || schema.default,
    filter: input => +input,
    validate: input => isInteger(+input)
  }),

  number: (schema, defaultValue, path) => input(path, {
    default: defaultValue || schema.default,
    filter: input => +input,
    validate: input => isFinite(+input)
  }),

  object: async (schema, defaultValue, path) => {
    const value = {}

    const required = {}
    schema.required && forEach(schema.required, name => {
      required[name] = true
    })

    const promptProperty = async (schema, name) => {
      const subpath = path
        ? `${path} > ${schema.title || name}`
        : schema.title || name

      if (
        required[name] ||
        await confirm(`fill optional ${subpath}?`, {
          default: Boolean(defaultValue && name in defaultValue)
        })
      ) {
        value[name] = await promptGeneric(
          schema,
          defaultValue && defaultValue[name],
          subpath
        )
      }
    }

    await forOwnAsync.call(schema.properties || {}, promptProperty)

    return value
  },

  string: (schema, defaultValue, path) => input(path, {
    default: defaultValue || schema.default
  })
}

export default function promptGeneric (schema, defaultValue, path) {
  const type = schema.enum
    ? 'enum'
    : schema.type

  const prompt = promptByType[type.toLowerCase()]
  if (!prompt) {
    throw new Error(`unsupported type: ${type}`)
  }

  return prompt(schema, defaultValue, path)
}
<|endoftext|>


<commit_before>// SETTINGS
// ============================================
const gulp = require('gulp');
const del = require('del');
const riot = require('gulp-riot');
const concat = require('gulp-concat');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const sort = require('gulp-natural-sort')
const uglify = require('gulp-uglify');
const sequence = require('run-sequence');
const webserver = require('gulp-webserver-fast');
const plumber = require("gulp-plumber");
const rename = require('gulp-rename');
const eslint = require('gulp-eslint');
const htmlhint = require("gulp-htmlhint");
const escape = require('./gulp-code-escape');
const rimraf = require('rimraf');

const watch_target = [
  'tags/**/*',
  'docs/tags/**/*.tag',
  'index.js'
];

// TASK
// ============================================
gulp.task('default', function () {
  return sequence(
    'webserver',
    'htmlhint',
    'eslint',
    'clean',
    'build',
    'demo_build',
    'watch'
  );
});

gulp.task('clean', function () {
  return del([
    'dist/**/*',
    'docs/dist/**/*'
  ]);
});

gulp.task('build', function () {
  return sequence(
    'compile',
    'concat',
    'compress'
  );
});

gulp.task('compile', function () {
  return gulp.src('tags/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('dist/'));
});

gulp.task('concat', function () {
  return gulp.src(['dist/**/*.js', '!dist/semantic-ui-riot.*js'])
    .pipe(sort())
    .pipe(concat('semantic-ui-riot.js'))
    .pipe(gulp.dest('dist/'));
});

gulp.task('compress', function (cb) {
  return gulp.src('dist/semantic-ui-riot.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(rename('semantic-ui-riot.min.js'))
    .pipe(gulp.dest('dist/'));
});

gulp.task('watch', function () {
  gulp.watch(watch_target, function () {
    sequence(
      'htmlhint',
      'eslint',
      'clean',
      'build',
      'demo_build'
    );
  });
});

gulp.task('eslint', function () {
  return gulp.src(['**/*.tag', 'test/spec/**/*.js', '!node_modules/**'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('htmlhint', function () {
  return gulp.src(['**/*.tag', '!node_modules/**'])
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
})

// for demo
gulp.task('demo_build', function () {
  return sequence(
    'demo_escape',
    'demo_htmlhint',
    'demo_compile',
    'demo_clean',
    'demo_concat',
    'demo_browserify',
    'demo_compress',
    'demo_copy'
  );
});

gulp.task('demo_escape', function () {
  return gulp.src('docs/tags/**/*.tag')
    .pipe(escape())
    .pipe(gulp.dest('docs/temp/'));
});

gulp.task('demo_htmlhint', function () {
  return gulp.src('docs/temp/**/*.tag')
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
})

gulp.task('demo_compile', function () {
  return gulp.src('docs/temp/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('docs/dist/'));
});

gulp.task('demo_clean', function (cb) {
  return rimraf('docs/temp', cb);
});

gulp.task('demo_concat', function () {
  return gulp.src(['docs/dist/**/*.js', '!docs/dist/build.js'])
    .pipe(sort())
    .pipe(concat('build.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_browserify', function () {
  browserify({
    entries: 'docs/build.js'
  })
    .transform(babelify)
    .bundle()
    .pipe(source('build.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_compress', function (cb) {
  return gulp.src('docs/build.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_copy', function () {
  return gulp.src('dist/semantic-ui-riot.min.js')
    .pipe(gulp.dest('docs/'))
})

gulp.task('webserver', function () {
  return gulp.src('./docs')
    .pipe(webserver({
      port: 3000,
      livereload: true,
      directoryListening: true,
      open: true
    }));
});<commit_msg>Improve livereload config<commit_after>// SETTINGS
// ============================================
const gulp = require('gulp');
const del = require('del');
const riot = require('gulp-riot');
const concat = require('gulp-concat');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const sort = require('gulp-natural-sort')
const uglify = require('gulp-uglify');
const sequence = require('run-sequence');
const webserver = require('gulp-webserver-fast');
const plumber = require("gulp-plumber");
const rename = require('gulp-rename');
const eslint = require('gulp-eslint');
const htmlhint = require("gulp-htmlhint");
const escape = require('./gulp-code-escape');
const rimraf = require('rimraf');

const watch_target = [
  'tags/**/*',
  'index.js'
];
const demo_watch_target = [
  'docs/tags/**/*.tag'
]

// TASK
// ============================================
gulp.task('default', function () {
  return sequence(
    'webserver',
    'htmlhint',
    'eslint',
    'clean',
    'build',
    'demo_build',
    'watch',
    'demo_watch'
  );
});

gulp.task('clean', function () {
  return del([
    'dist/**/*'
  ]);
});

gulp.task('build', function () {
  return sequence(
    'compile',
    'concat',
    'compress',
    'demo_copy'
  );
});

gulp.task('compile', function () {
  return gulp.src('tags/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('dist/'));
});

gulp.task('concat', function () {
  return gulp.src(['dist/**/*.js', '!dist/semantic-ui-riot.*js'])
    .pipe(sort())
    .pipe(concat('semantic-ui-riot.js'))
    .pipe(gulp.dest('dist/'));
});

gulp.task('compress', function (cb) {
  return gulp.src('dist/semantic-ui-riot.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(rename('semantic-ui-riot.min.js'))
    .pipe(gulp.dest('dist/'));
});

gulp.task('watch', function () {
  gulp.watch(watch_target, function () {
    sequence(
      'htmlhint',
      'eslint',
      'clean',
      'build'
    );
  });
});

gulp.task('eslint', function () {
  return gulp.src(['**/*.tag', 'test/spec/**/*.js', '!node_modules/**'])
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.failAfterError());
});

gulp.task('htmlhint', function () {
  return gulp.src(['**/*.tag', '!node_modules/**'])
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
})

// for demo
gulp.task('demo_watch', function () {
  gulp.watch(demo_watch_target, function () {
    sequence(
      'demo_build'
    );
  });
});

gulp.task('demo_build', function () {
  return sequence(
    'demo_escape',
    'demo_htmlhint',
    'demo_compile',
    'demo_clean',
    'demo_concat',
    'demo_browserify',
    'demo_compress'
  );
});

gulp.task('demo_escape', function () {
  return gulp.src('docs/tags/**/*.tag')
    .pipe(escape())
    .pipe(gulp.dest('docs/temp/'));
});

gulp.task('demo_htmlhint', function () {
  return gulp.src('docs/temp/**/*.tag')
    .pipe(plumber())
    .pipe(htmlhint('.htmlhintrc'))
    .pipe(htmlhint.failReporter())
})

gulp.task('demo_compile', function () {
  del([
    'docs/dist/**/*'
  ]);
  return gulp.src('docs/temp/**/*.tag')
    .pipe(riot({
      type: 'es6'
    }))
    .pipe(gulp.dest('docs/dist/'));
});

gulp.task('demo_clean', function (cb) {
  return rimraf('docs/temp', cb);
});

gulp.task('demo_concat', function () {
  return gulp.src(['docs/dist/**/*.js', '!docs/dist/build.js'])
    .pipe(sort())
    .pipe(concat('build.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_browserify', function () {
  browserify({
    entries: 'docs/build.js'
  })
    .transform(babelify)
    .bundle()
    .pipe(source('build.js'))
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_compress', function (cb) {
  return gulp.src('docs/build.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('docs/'));
});

gulp.task('demo_copy', function () {
  return gulp.src('dist/semantic-ui-riot.min.js')
    .pipe(gulp.dest('docs/'))
})

gulp.task('webserver', function () {
  const target = [
    'index.html',
    'build.js',
    'semantic-ui-riot.min.js'
  ]
  return gulp.src('./docs')
    .pipe(webserver({
      port: 3000,
      livereload: {
        enable: true,
        filter: function (fileName) {
          return target.indexOf(fileName) >= 0
        }
      },
      directoryListening: true,
      open: true
    }));
});<|endoftext|>


<commit_before>const { dbMiddleware } = require('~/database');
const { acceptValidator } = require('~/requestValidators');
const authenticator = require('~/authenticator');

module.exports = (router) => {
  router.delete(
    '/access-tokens/:id',
    acceptValidator('application/json'),
    dbMiddleware(),
    authenticator(true),
    async (ctx) => {
      const [item] = await ctx.state.db.query(
        `SELECT userId FROM trackingAccessToken JOIN trackingDevice ON (deviceId = trackingDevice.id)
          WHERE trackingAccessToken.id = ? AND trackingDevice.id = ? FOR UPDATE`,
        [ctx.params.id],
      );

      if (!item) {
        ctx.status = 404;
      } else if (!ctx.state.user.isAdmin && item.userId !== ctx.state.user.id) {
        ctx.status = 403;
      } else {
        await ctx.state.db.query('DELETE FROM trackingAccessToken WHERE id = ?', [ctx.params.id]);
        ctx.status = 204;
      }
    },
  );
};
<commit_msg>fixed sql<commit_after>const { dbMiddleware } = require('~/database');
const { acceptValidator } = require('~/requestValidators');
const authenticator = require('~/authenticator');

module.exports = (router) => {
  router.delete(
    '/access-tokens/:id',
    acceptValidator('application/json'),
    dbMiddleware(),
    authenticator(true),
    async (ctx) => {
      const [item] = await ctx.state.db.query(
        `SELECT userId FROM trackingAccessToken JOIN trackingDevice ON (deviceId = trackingDevice.id)
          WHERE trackingAccessToken.id = ? FOR UPDATE`,
        [ctx.params.id],
      );

      if (!item) {
        ctx.status = 404;
      } else if (!ctx.state.user.isAdmin && item.userId !== ctx.state.user.id) {
        ctx.status = 403;
      } else {
        await ctx.state.db.query('DELETE FROM trackingAccessToken WHERE id = ?', [ctx.params.id]);
        ctx.status = 204;
      }
    },
  );
};
<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var ModuleEntry = function(props) {
    this.packageName = props.packageName || '';
    this.label = props.label || '';
    this.description = props.description || '';
    this.src = props.src || '';
    this.visiblePortNames = props.visiblePortNames || [];
    this.tags = props.tags || [];
  };

  ModuleEntry.prototype.key = function() {
    return this.packageName + '/' + this.src;
  };

  ModuleEntry.prototype.keywordScore = function(keyword) {
    if (!keyword) {
      return 0;
    }

    keyword = keyword.toLowerCase();

    var label = this.label.toLowerCase();
    if (label.indexOf(keyword) === 0) {
      return 1;
    }

    var tags = this.tags;
    for (var i = 0, len = tags.length; i < len; i++) {
      var tag = tags[i].toLowerCase();
      if (tag === keyword || (keyword.length >= 2 && tag.indexOf(keyword) !== -1)) {
        return 0.75;
      }
    }

    if (keyword.length < 2) {
      return 0;
    }

    if (label.indexOf(keyword) !== -1) {
      return 0.5;
    }

    var description = this.description.toLowerCase();
    if (description.indexOf(keyword) !== -1) {
      return 0.25;
    }

    return 0;
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = ModuleEntry;
  } else {
    app.ModuleEntry = ModuleEntry;
  }
})(this.app || (this.app = {}));
<commit_msg>Modify method for calculating a keyword score of module-entry<commit_after>(function(app) {
  'use strict';

  var ModuleEntry = function(props) {
    this.packageName = props.packageName || '';
    this.label = props.label || '';
    this.description = props.description || '';
    this.src = props.src || '';
    this.visiblePortNames = props.visiblePortNames || [];
    this.tags = props.tags || [];
  };

  ModuleEntry.prototype.key = function() {
    return this.packageName + '/' + this.src;
  };

  ModuleEntry.prototype.keywordScore = function(keyword) {
    if (!keyword) {
      return 0;
    }

    keyword = keyword.toLowerCase();

    var label = this.label.toLowerCase();
    var labelIndex = label.indexOf(keyword);
    if (labelIndex === 0) {
      return 1;
    }

    var tags = this.tags;
    for (var i = 0, len = tags.length; i < len; i++) {
      var tag = tags[i].toLowerCase();
      if (tag === keyword || (keyword.length >= 2 && tag.indexOf(keyword) !== -1)) {
        return 0.75;
      }
    }

    if (keyword.length < 2) {
      return 0;
    }

    if (labelIndex !== -1) {
      return 0.5;
    }

    var description = this.description.toLowerCase();
    if (description.indexOf(keyword) !== -1) {
      return 0.25;
    }

    return 0;
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = ModuleEntry;
  } else {
    app.ModuleEntry = ModuleEntry;
  }
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>var vm = require('vm');

// Only really makes sense when queryObj matches a single initial asset.
module.exports = function (queryObj, context) {
    return function executeJavaScriptInOrder(assetGraph) {
        if (!context) {
            context = vm.createContext();
        }
        var assetsInOrder = [];
        assetGraph.findAssets(queryObj).forEach(function (initialAsset) {
            Array.prototype.push.apply(assetsInOrder, assetGraph.collectAssetsPostOrder(initialAsset, {to: {type: 'JavaScript'}}));
        });
        assetsInOrder.forEach(function (asset) {
            vm.runInContext(asset.text, context, asset.url || '(inline)');
        });
    };
};
<commit_msg>transforms.executeJavaScriptInOrder: Compensate for Script.runInContext not reporting the file name on error until node.js 0.5.5.<commit_after>var vm = require('vm');

// Only really makes sense when queryObj matches a single initial asset.
module.exports = function (queryObj, context) {
    return function executeJavaScriptInOrder(assetGraph) {
        if (!context) {
            context = vm.createContext();
        }
        var assetsInOrder = [];
        assetGraph.findAssets(queryObj).forEach(function (initialAsset) {
            Array.prototype.push.apply(assetsInOrder, assetGraph.collectAssetsPostOrder(initialAsset, {to: {type: 'JavaScript'}}));
        });
        assetsInOrder.forEach(function (asset) {
            try {
                vm.runInContext(asset.text, context, asset.url || '(inline)');
            } catch (e) {
                // Script.runInContext won't report the file name on error until node.js 0.5.5:
                // https://github.com/joyent/node/commit/c05936ca13681059c7aeecfe3a608e4e1afa800a
                throw new Error('transforms.executeJavaScriptInOrder: Error in ' + (asset.url || '(inline script)') + ":\n" + e.stack);
            }
        });
    };
};
<|endoftext|>


<commit_before>var babel = require('gulp-babel');
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');

gulp.task(
  'compile',
  ['compile-es6', 'compile-scss']
);

gulp.task(
  'compile-es6',
  function () {
    return gulp.src('src/**/*.js')
      .pipe(babel())
      .pipe(gulp.dest('lib'));
  }
);

gulp.task(
  'compile-scss',
  function () {
    gulp.src('assets/stylesheets/**/*.scss')
      .pipe(sass({ includePaths: ['node_modules'] }).on('error', sass.logError))
      .pipe(gulp.dest('public/stylesheets'));
  }
);

gulp.task(
  'watch',
  function () {
    gulp.watch('{assets/stylesheets/**/*.scss,lib/**/*.js}', ['compile']);
  }
);
<commit_msg>Fix wrong watch path<commit_after>var babel = require('gulp-babel');
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');

gulp.task(
  'compile',
  ['compile-es6', 'compile-scss']
);

gulp.task(
  'compile-es6',
  function () {
    return gulp.src('src/**/*.js')
      .pipe(babel())
      .pipe(gulp.dest('lib'));
  }
);

gulp.task(
  'compile-scss',
  function () {
    gulp.src('assets/stylesheets/**/*.scss')
      .pipe(sass({ includePaths: ['node_modules'] }).on('error', sass.logError))
      .pipe(gulp.dest('public/stylesheets'));
  }
);

gulp.task(
  'watch',
  function () {
    gulp.watch('{assets/stylesheets/**/*.scss,src/**/*.js}', ['compile']);
  }
);
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

const panel = {
  'margin': '16px'
}

const log = {
  'width': '480px',
  'height': '320px',
  'overflow': 'scroll',
  'backgroundColor': 'rgb(0,0,0)',
  'color': 'rgb(255,255,255)',
  'margin': '0'
}

const info = {
  'width': '480px',
  'color': 'rgb(255,255,255)',
  'padding': '4px 0'
}

class PanelComponent extends React.Component {
  static propTypes = {
    containerInfo: PropTypes.object.isRequired
  }

  render() {
    let c = this.props.containerInfo
    let infoStyle
    if (c.status.includes('Exit')) {
      infoStyle = Object.assign({}, info, { 'backgroundColor': 'rgb(128,0,0)' })
    } else {
      infoStyle = Object.assign({}, info, { 'backgroundColor': 'rgb(0,128,0)' })
    }
    return (

{c.log}

id: {c.id}

status: {c.status}

name: {c.name}

    )
  }
}

export default PanelComponent
<commit_msg>change panel to display image<commit_after>import React from 'react'
import PropTypes from 'prop-types'

const panel = {
  'margin': '16px'
}

const log = {
  'width': '480px',
  'height': '320px',
  'overflow': 'scroll',
  'backgroundColor': 'rgb(0,0,0)',
  'color': 'rgb(255,255,255)',
  'margin': '0'
}

const info = {
  'width': '480px',
  'color': 'rgb(255,255,255)',
  'padding': '4px 0'
}

class PanelComponent extends React.Component {
  static propTypes = {
    containerInfo: PropTypes.object.isRequired
  }

  render() {
    let c = this.props.containerInfo
    let infoStyle
    if (c.status.includes('Exit')) {
      infoStyle = Object.assign({}, info, { 'backgroundColor': 'rgb(128,0,0)' })
    } else {
      infoStyle = Object.assign({}, info, { 'backgroundColor': 'rgb(0,128,0)' })
    }
    return (

{c.log}

id: {c.id}

status: {c.status}

image: {c.image}

    )
  }
}

export default PanelComponent
<|endoftext|>


<commit_before>'use strict';

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 21,
  });
  //only need the infoWindow if we want to display something over the map, like a message (see code above map.setCenter(pos))
  // infoWindow = new google.maps.InfoWindow;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {

      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

        var myCar = new google.maps.Circle({
          strokeColor: 'blue',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: 'blue',
          fillOpacity: 0.5,
          map: map,
          center: {lat: position.coords.latitude, lng: position.coords.longitude},
          radius: 1.5,
          draggable: true
        });
        var otherCar = new google.maps.Circle({
          strokeColor: 'red',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: 'red',
          fillOpacity: 0.5,
          map: map,
          center: {lat: position.coords.latitude, lng: position.coords.longitude},
          radius: 1.5,
          draggable: true
        });

      map.setCenter(pos);
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter());
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
  }
}
<commit_msg>tweaking where circles appear on map initially<commit_after>'use strict';

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 21,
  });
  //only need the infoWindow if we want to display something over the map, like a message (see code above map.setCenter(pos))
  // infoWindow = new google.maps.InfoWindow;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {

      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };
      console.log(pos);

        var myCar = new google.maps.Circle({
          strokeColor: 'blue',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: 'blue',
          fillOpacity: 0.5,
          map: map,
          center: {lat: position.coords.latitude, lng: position.coords.longitude},
          radius: 1,
          draggable: true
        });
        var otherCar = new google.maps.Circle({
          strokeColor: 'red',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: 'red',
          fillOpacity: 0.5,
          map: map,
          center: {lat: position.coords.latitude, lng: position.coords.longitude},
          radius: 1,
          draggable: true
        });

      map.setCenter(pos);
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter());
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
  }
}
<|endoftext|>


<commit_before>var Toolbar = Backbone.View.extend({
    tagName: "div",

    events: {
        'click #add_tab': 'add_tab',
        'click #open_query': 'open_query',
        'click #logout': 'logout',
        'click #about': 'about',
        'click #issue_tracker': 'issue_tracker'
    },

    template: function() {
        return _.template("
" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                "
" +
                "
Saiku
"
            )(this);
    },

    initialize: function() {
        this.render();
    },

    render: function() {
        $(this.el).attr('id', 'toolbar')
            .html(this.template());
        return this;
    },

    /**
     * Add a new tab to the interface
     */
    add_tab: function() {
        Saiku.tabs.add([ new Tab ]);
        return false;
    },

    /**
     * Open a query from the repository into a new tab
     */
    open_query: function() {
        return false;
    },

    /**
     * Clear the current session and show the login window
     */
    logout: function() {
        // FIXME - This is a hack (inherited from old UI)
        $('body').hide();
        location.reload(true);
        return false;
    },

    /**
     * Show the credits dialog
     */
    about: function() {
        (new AboutModal).render().open();
        return false;
    },

    /**
     * Go to the issue tracker
     */
    issue_tracker: function() {
        window.open('http://projects.analytical-labs.com/projects/saiku/issues');
        return false;
    }
});

<commit_msg>Point issue tracker link to create new<commit_after>var Toolbar = Backbone.View.extend({
    tagName: "div",

    events: {
        'click #add_tab': 'add_tab',
        'click #open_query': 'open_query',
        'click #logout': 'logout',
        'click #about': 'about',
        'click #issue_tracker': 'issue_tracker'
    },

    template: function() {
        return _.template("
" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                    "

" +
                "
" +
                "
Saiku
"
            )(this);
    },

    initialize: function() {
        this.render();
    },

    render: function() {
        $(this.el).attr('id', 'toolbar')
            .html(this.template());
        return this;
    },

    /**
     * Add a new tab to the interface
     */
    add_tab: function() {
        Saiku.tabs.add([ new Tab ]);
        return false;
    },

    /**
     * Open a query from the repository into a new tab
     */
    open_query: function() {
        return false;
    },

    /**
     * Clear the current session and show the login window
     */
    logout: function() {
        // FIXME - This is a hack (inherited from old UI)
        $('body').hide();
        location.reload(true);
        return false;
    },

    /**
     * Show the credits dialog
     */
    about: function() {
        (new AboutModal).render().open();
        return false;
    },

    /**
     * Go to the issue tracker
     */
    issue_tracker: function() {
        window.open('http://projects.analytical-labs.com/projects/saiku/issues/new');
        return false;
    }
});

<|endoftext|>


<commit_before>const gulp = require('gulp');
const rename = require('gulp-rename');
const clean = require('gulp-clean');

const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const cssnext = require('postcss-cssnext');
const cssnano = require('cssnano');

const processors = {
  pre: [ cssnext() ],
  post: [ cssnano() ],
};

gulp.task('clean', () =>
    gulp.src('./dist/**/*', { read: false })
      .pipe(clean())
);

gulp.task('css:bem', () =>
  gulp.src('./bem/all.scss')
    .pipe(postcss(processors.pre))
    .pipe(sass())
    .pipe(rename('nio.bem.css'))
    .pipe(gulp.dest('./dist'))
    .pipe(postcss(processors.post))
    .pipe(rename('nio.bem.min.css'))
    .pipe(gulp.dest('./dist'))
);

gulp.task('css:modules', () =>
  gulp.src('./modules/**/*.scss')
    .pipe(postcss(processors.pre))
    .pipe(sass())
    .pipe(gulp.dest('./dist/modules'))
);

gulp.task('default', gulp.series('clean', gulp.parallel('css:bem', 'css:modules')));

gulp.task('watch', () =>
  gulp.watch(['bem/**/*.scss', 'shared/**/*.scss', 'modules/**/*.js'], gulp.parallel('css:bem', 'css:modules'))
);
<commit_msg>make sure the precompile stage uses the SCSS syntax<commit_after>const gulp = require('gulp');
const rename = require('gulp-rename');
const clean = require('gulp-clean');

const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const scss = require('postcss-scss');
const cssnext = require('postcss-cssnext');
const cssnano = require('cssnano');

const scssConfig = { syntax: scss };
const processors = {
  pre: [ cssnext() ],
  post: [ cssnano() ],
};

gulp.task('clean', () =>
    gulp.src('./dist/**/*', { read: false })
      .pipe(clean())
);

gulp.task('css:bem', () =>
  gulp.src('./bem/all.scss')
    .pipe(postcss(processors.pre, scssConfig))
    .pipe(sass())
    .pipe(rename('nio.bem.css'))
    .pipe(gulp.dest('./dist'))
    .pipe(postcss(processors.post))
    .pipe(rename('nio.bem.min.css'))
    .pipe(gulp.dest('./dist'))
);

gulp.task('css:modules', () =>
  gulp.src('./modules/**/*.scss')
    .pipe(postcss(processors.pre, scssConfig))
    .pipe(sass())
    .pipe(gulp.dest('./dist/modules'))
);

gulp.task('default', gulp.series('clean', gulp.parallel('css:bem', 'css:modules')));

gulp.task('watch', () =>
  gulp.watch(['bem/**/*.scss', 'shared/**/*.scss', 'modules/**/*.js'], gulp.parallel('css:bem', 'css:modules'))
);
<|endoftext|>


<commit_before>angular.module('khe', ['ngRoute', 'kheStaff', 'kheAttendees']);
angular.module('kheStaff', []);
angular.module('kheAttendees', []);<commit_msg>Require angular-cookies<commit_after>angular.module('khe', ['ngRoute', 'ngCookies', 'kheStaff', 'kheAttendees']);
angular.module('kheStaff', []);
angular.module('kheAttendees', []);<|endoftext|>


<commit_before>var del = require('del');
var assign = require('lodash').assign;

var gulp = require('gulp');
var debug = require('gulp-debug');
var frontMatter = require('gulp-front-matter');
var imagemin = require('gulp-imagemin');
var less = require('gulp-less');
var livereload = require('gulp-livereload');
var gulpsmith = require('gulpsmith');

var jpegtran = require('imagemin-jpegtran');

var path = require('path');

var collections = require('metalsmith-collections');
var markdown = require('metalsmith-markdown');
var metadata = require('metalsmith-metadata');
var permalinks = require('metalsmith-permalinks');
var templates = require('metalsmith-templates');

//TODO: add pagination ?, gulp-sourcemaps
//TODO: add to jade moment or somethings

gulp.task('clean:dist', function (done) {
	del(['dist/*'], done);
});

gulp.task('build:html', function () {
	return gulp.src(['./pages/**/*.md', './config.yaml'])
		.pipe(frontMatter().on('data', function (file) {
			assign(file, file.frontMatter);
			delete file.frontMatter;
		}))
		.pipe(gulpsmith()
			.use(metadata({
				config: 'config.yaml'
			}))
			.use(collections({
				projects: {
					pattern: 'projects/*.md',
					sortBy: 'publishDate'
				}
			}))
			.use(markdown())
			.use(permalinks())
			.use(templates({
				engine: 'jade',
				stringify: function(obj) {
					var cache = [];
					var str = JSON.stringify(obj, function(key, value) {
						if (typeof value === 'object' && value !== null) {
							if (cache.indexOf(value) !== -1) {
								// Circular reference found, discard key
								return;
							}
							// Store value in our collection
							cache.push(value);
						}
						return value;
					});
					cache = null; // Enable garbage collection
					return str;
				}
			}))
		)
		.pipe(debug({title: 'build:all'}))
		.pipe(livereload())
		.pipe(gulp.dest('./dist'));
});

gulp.task('build:images:assets', function() {
	return gulp.src('assets/**/*.jpg')
		.pipe(imagemin({
			progressive: true,
			use: [jpegtran()]
		}))
		.pipe(gulp.dest('dist/images'));
});

gulp.task('build:images:projects', function() {
	return gulp.src('pages/**/*.jpg')
		.pipe(imagemin({
			progressive: true,
			use: [jpegtran()]
		}))
		.pipe(gulp.dest('dist/images'));
});

gulp.task('build:images', gulp.parallel('build:images:assets', 'build:images:projects'));

gulp.task('build:styles', function() {
	return gulp.src('./templates/styles/**/*.less')
		.pipe(less({
			paths: [ path.join(__dirname, 'node_modules', 'bootswatch') ]
		}))
		.pipe(gulp.dest('dist/css'));
});

gulp.task('build:all', gulp.parallel(
	'build:html',
	'build:images',
	'build:styles'));

gulp.task('watch', function () {
	livereload.listen();
	gulp.watch([
			'config.yaml',
			'assets/**/*',
			'pages/**/*',
			'templates/**/*'
		],
		gulp.series('build:all'));
});

gulp.task('default', gulp.series('clean:dist', 'build:all'));<commit_msg>rename build task from build:all to build<commit_after>var del = require('del');
var assign = require('lodash').assign;

var gulp = require('gulp');
var debug = require('gulp-debug');
var frontMatter = require('gulp-front-matter');
var imagemin = require('gulp-imagemin');
var less = require('gulp-less');
var livereload = require('gulp-livereload');
var gulpsmith = require('gulpsmith');

var jpegtran = require('imagemin-jpegtran');

var path = require('path');

var collections = require('metalsmith-collections');
var markdown = require('metalsmith-markdown');
var metadata = require('metalsmith-metadata');
var permalinks = require('metalsmith-permalinks');
var templates = require('metalsmith-templates');

//TODO: add pagination ?, gulp-sourcemaps
//TODO: add to jade moment or somethings

gulp.task('clean:dist', function (done) {
	del(['dist/*'], done);
});

gulp.task('build:html', function () {
	return gulp.src(['./pages/**/*.md', './config.yaml'])
		.pipe(frontMatter().on('data', function (file) {
			assign(file, file.frontMatter);
			delete file.frontMatter;
		}))
		.pipe(gulpsmith()
			.use(metadata({
				config: 'config.yaml'
			}))
			.use(collections({
				projects: {
					pattern: 'projects/*.md',
					sortBy: 'publishDate'
				}
			}))
			.use(markdown())
			.use(permalinks())
			.use(templates({
				engine: 'jade',
				stringify: function(obj) {
					var cache = [];
					var str = JSON.stringify(obj, function(key, value) {
						if (typeof value === 'object' && value !== null) {
							if (cache.indexOf(value) !== -1) {
								// Circular reference found, discard key
								return;
							}
							// Store value in our collection
							cache.push(value);
						}
						return value;
					});
					cache = null; // Enable garbage collection
					return str;
				}
			}))
		)
		.pipe(debug({title: 'build:all'}))
		.pipe(livereload())
		.pipe(gulp.dest('./dist'));
});

gulp.task('build:images:assets', function() {
	return gulp.src('assets/**/*.jpg')
		.pipe(imagemin({
			progressive: true,
			use: [jpegtran()]
		}))
		.pipe(gulp.dest('dist/images'));
});

gulp.task('build:images:projects', function() {
	return gulp.src('pages/**/*.jpg')
		.pipe(imagemin({
			progressive: true,
			use: [jpegtran()]
		}))
		.pipe(gulp.dest('dist/images'));
});

gulp.task('build:images', gulp.parallel('build:images:assets', 'build:images:projects'));

gulp.task('build:styles', function() {
	return gulp.src('./templates/styles/**/*.less')
		.pipe(less({
			paths: [ path.join(__dirname, 'node_modules', 'bootswatch') ]
		}))
		.pipe(gulp.dest('dist/css'));
});

gulp.task('build', gulp.parallel(
	'build:html',
	'build:images',
	'build:styles'));

gulp.task('watch', function () {
	livereload.listen();
	gulp.watch([
			'config.yaml',
			'assets/**/*',
			'pages/**/*',
			'templates/**/*'
		],
		gulp.series('build:all'));
});

gulp.task('default', gulp.series('clean:dist', 'build'));<|endoftext|>


<commit_before>/* Copyright 2015 Bloomberg Finance L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var widgets = require("jupyter-js-widgets");
var _ = require("underscore");
var d3 = require("d3");

var SquareMarketMap = widgets.DOMWidgetView.extend({

    render: function() {
        this.width = this.model.get("width");
        this.height = this.model.get("height");
        this.margin = this.model.get('margin');

        this.el.style["width"] = this.width + this.margin.left + this.margin.right;
        this.el.style["height"] = this.height + this.margin.top + this.margin.bottom;

        this.$el.resizable({
            aspectRatio: true
        });

        var sector_data = this.model.get('data');
        this.colors = this.model.get('colors');
        this.mode = this.model.get('mode');

        var color= d3.scale.category10();
        var that = this;
        this.d3el.append("div")
            .style("position", "relative")
            .style("width", (this.width + this.margin.left + this.margin.right) + "px")
            .style("height", (this.height + this.margin.top + this.margin.bottom) + "px")
            .style("left", this.margin.left + "px")
            .style("top", this.margin.top + "px");

        this.margin = this.model.get("margin");

        this.tree_map = d3.layout.treemap()
            .size([this.width, this.height])
            .sticky(true)
            .padding(null)
            .mode(this.mode)
            .value(function(d) {return d.size;});

        var element = this.d3el.datum(sector_data).selectAll(".node")
            .data(this.tree_map.nodes)
            .enter().append("div")
            .attr("class", "node")
            .call(this.position)
            .style({
                "background": function(d, i) {
                    return d.children ? color(d.name): null;
                },
                "border": "solid white"
            })
            .text(function(d) { return d.children ? null : d.name; })
            .style({
                'font': '11px sans-serif',
                'position': 'absolute',
                'text-align': 'center',
                'overflow': 'hidden',
                'color': 'white',
            });
    },

    position: function(){
        this.style("left", function(d) { return d.x + "px"; })
            .style("top", function(d) { return d.y + "px"; })
            .style("width", function(d) {
                return Math.max(0, d.dx - 1) + "px";
            })
            .style("height", function(d) {
                return Math.max(0, d.dy - 1) + "px";
            });
    }
});

module.exports = {
    SquareMarketMap: SquareMarketMap
};
<commit_msg>Remove resizable call<commit_after>/* Copyright 2015 Bloomberg Finance L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var widgets = require("jupyter-js-widgets");
var _ = require("underscore");
var d3 = require("d3");

var SquareMarketMap = widgets.DOMWidgetView.extend({

    render: function() {
        this.width = this.model.get("width");
        this.height = this.model.get("height");
        this.margin = this.model.get('margin');

        this.el.style["width"] = this.width + this.margin.left + this.margin.right;
        this.el.style["height"] = this.height + this.margin.top + this.margin.bottom;

        var sector_data = this.model.get('data');
        this.colors = this.model.get('colors');
        this.mode = this.model.get('mode');

        var color= d3.scale.category10();
        var that = this;
        this.d3el.append("div")
            .style("position", "relative")
            .style("width", (this.width + this.margin.left + this.margin.right) + "px")
            .style("height", (this.height + this.margin.top + this.margin.bottom) + "px")
            .style("left", this.margin.left + "px")
            .style("top", this.margin.top + "px");

        this.margin = this.model.get("margin");

        this.tree_map = d3.layout.treemap()
            .size([this.width, this.height])
            .sticky(true)
            .padding(null)
            .mode(this.mode)
            .value(function(d) {return d.size;});

        var element = this.d3el.datum(sector_data).selectAll(".node")
            .data(this.tree_map.nodes)
            .enter().append("div")
            .attr("class", "node")
            .call(this.position)
            .style({
                "background": function(d, i) {
                    return d.children ? color(d.name): null;
                },
                "border": "solid white"
            })
            .text(function(d) { return d.children ? null : d.name; })
            .style({
                'font': '11px sans-serif',
                'position': 'absolute',
                'text-align': 'center',
                'overflow': 'hidden',
                'color': 'white',
            });
    },

    position: function(){
        this.style("left", function(d) { return d.x + "px"; })
            .style("top", function(d) { return d.y + "px"; })
            .style("width", function(d) {
                return Math.max(0, d.dx - 1) + "px";
            })
            .style("height", function(d) {
                return Math.max(0, d.dy - 1) + "px";
            });
    }
});

module.exports = {
    SquareMarketMap: SquareMarketMap
};
<|endoftext|>


<commit_before>$(document).ready(function() {
    console.log('app.js loaded');

    $.ajax({
        method: 'GET',
        url: '/api/entry', // creating api of users... check on this not sure what's going on
        success: renderMultipleEntries
    });

    $('#entryForm form').on('submit', function(e) {
        e.preventDefault();
        var formData = ({
            userName: $('#userName').val(),
            dishName: $('#dishName').val(),
            origin: $('#origin').val(),
            calories: $('#calories').val(),
            ingredients: $('#ingredients').val()
        });
        console.log('formData', formData);
        $.post('/api/entry', formData, function(entry) {
            console.log('entry after post', entry);
            renderEntry(entry); // render the servers response
        });
        $(this).trigger("reset");
    });

        $.ajax({
            method: 'DELETE',
            url: '/api/entry/:EntryId',
            success: removeEntries
        });

    $('.btn btn-danger delete-entry').on('submit', function(e) {
        e.preventDefault();
        $.delete('/api/entry/:EntryId', formData, function(entry) {
            console.log('deleted post', entry);
            removeEntries(entry); // render the servers response
        });
    })
});

function renderMultipleEntries(entries) {
    console.log(entries);
    entries.forEach(function(entry) {
        renderEntry(entry);
    });
}
// this function takes a single entry and renders it to the page
function renderEntry(entry) {
    console.log('rendering entry', entry);

    var entryHtml = (`

   <form id="entry" action="" method="post" >

      <fieldset>
           ${entry.userName}
       </fieldset>
       <fieldset>
           ${entry.dishName}
       </fieldset>
       <fieldset>
           ${entry.origin}
       </fieldset>
       <fieldset>
           ${entry.calories}
       </fieldset>
       <fieldset>
           ${entry.ingredients}
       </fieldset>
       <fieldset>
           <button class='btn btn-info edit-entry'>Edit Entry</button>
       </fieldset>
       <fieldset>
           <button class='btn btn-danger delete-entry' data-id="${entry._id}">Delete Entry</button>
       </fieldset>
   </form>
   `);
    $('#savedMeals').prepend(entryHtml);
}

    function removeEntries(entries) {
        var deletedEntryId = data._id
        console.log('entries removed', deletedEntryId);
        $('div[data-entry-id=' + deletedEntryId + ']').remove();
    }
    //TODO: Prevent Default
    // AJAX REQUEST
    // delete
    // url; api/entry/ + entryID you grab from the delete button
    // success: on success, remove the entry from the view via jquery.
    // });
// When the add entry button is clicked
function handleAddEntryClick(e) {
    console.log('add-entry clicked');
    var currentEntryId = $(this).closest('.entry').data('entry-id');
    console.log('id', currentEntryId);
}
<commit_msg>what is life?<commit_after>$(document).ready(function() {
    console.log('app.js loaded');

    $.ajax({
        method: 'GET',
        url: '/api/entry', // creating api of users... check on this not sure what's going on
        success: renderMultipleEntries
    });

    $('#entryForm form').on('submit', function(e) {
        e.preventDefault();
        var formData = ({
            userName: $('#userName').val(),
            dishName: $('#dishName').val(),
            origin: $('#origin').val(),
            calories: $('#calories').val(),
            ingredients: $('#ingredients').val()
        });
        console.log('formData', formData);
        $.post('/api/entry', formData, function(entry) {
            console.log('entry after post', entry);
            renderEntry(entry); // render the servers response
        });
        $(this).trigger("reset");
    });

        $.ajax({
            method: 'DELETE',
            url: '/api/entry/:EntryId',
            success: removeEntries
        });

    $('.btn btn-danger delete-entry').on('submit', function(e) {
        e.preventDefault();
        $.delete('/api/entry/:EntryId', formData, function(entry) {
            console.log('deleted post', entry);
            removeEntries(entry); // render the servers response
        });
    })
});

function renderMultipleEntries(entries) {
    console.log(entries);
    entries.forEach(function(entry) {
        renderEntry(entry);
    });
}
// this function takes a single entry and renders it to the page
function renderEntry(entry) {
    console.log('rendering entry', entry);

    var entryHtml = (`

   <form id="entry" action="" method="post" >

      <fieldset>
           ${entry.userName}
       </fieldset>
       <fieldset>
           ${entry.dishName}
       </fieldset>
       <fieldset>
           ${entry.origin}
       </fieldset>
       <fieldset>
           ${entry.calories}
       </fieldset>
       <fieldset>
           ${entry.ingredients}
       </fieldset>
       <fieldset>
           <button class='btn btn-info edit-entry'>Edit Entry</button>
       </fieldset>
       <fieldset>
           <button class='btn btn-danger delete-entry' data-id="${entry._id}">Delete Entry</button>
       </fieldset>
   </form>
   `);
    $('#savedMeals').prepend(entryHtml);
}

    function removeEntries(entries) {
        var deletedEntryId = data._id
        console.log('entries removed', deletedEntryId);
        $('div[data-entry-id=' + deletedEntryId + ']').remove();
    }
    //TODO: Prevent Default
    // AJAX REQUEST
    // delete
    // url; api/entry/ + entryID you grab from the delete button
    // success: on success, remove the entry from the view via jquery.
    // });
// When the add entry button is clicked
function handleAddEntryClick(e) {
    console.log('add-entry clicked');
    var currentEntryId = $(this).closest('.entry').data('entry-id');
    console.log('id', currentEntryId);
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import uuid from 'node-uuid';
import Immutable from 'immutable';
import EventEmitter from 'events';

import Dispatcher from '../dispatcher/Dispatcher';
import MessagesStore from './MessagesStore';

let isActive = {};

// READ API
const ChannelStore = _.assign({}, EventEmitter.prototype, {

    isActive: function(channel) {
        return isActive[channel] || false;
    },

    emitChange: function() {
        this.emit('change');
    },

    addChangeListener: function(callback) {
        this.on('change', callback);
    },

    removeChangeListener: function(callback) {
        this.removeListener('change', callback);
    }

});

// WRITE API
ChannelStore.dispatchToken = Dispatcher.register(function(action) {

    switch(action.type) {

        case 'receive_messages':
            // waitFor means that MessagesStore should process
            // this event before it's processed here.
            Dispatcher.waitFor([MessagesStore.dispatchToken]);

            isActive[action.channel] = true;
            ChannelStore.emitChange();
            break;

        case 'receive_messages_failed':
            Dispatcher.waitFor([MessagesStore.dispatchToken]);

            isActive[action.channel] = false;
            ChannelStore.emitChange();
            break;

        default:
            // noop

    }

});

export default ChannelStore;

<commit_msg>Improve channel store<commit_after>import _ from 'lodash';
import uuid from 'node-uuid';
import Immutable from 'immutable';
import EventEmitter from 'events';

import Dispatcher from '../dispatcher/Dispatcher';
import MessagesStore from './MessagesStore';

let isActive = {};

// READ API
const ChannelStore = _.assign({}, EventEmitter.prototype, {

    isActive: function(channel) {
        return isActive[channel] || false;
    },

    emitChange: function() {
        this.emit('change');
    },

    addChangeListener: function(callback) {
        this.on('change', callback);
    },

    removeChangeListener: function(callback) {
        this.removeListener('change', callback);
    }

});

// WRITE API
ChannelStore.dispatchToken = Dispatcher.register(function(action) {

    switch(action.type) {

        case 'receive_messages':
        case 'receive_messages_failed':
            // waitFor means that MessagesStore should process
            // this event before it's processed here.
            Dispatcher.waitFor([MessagesStore.dispatchToken]);

            let messages = MessagesStore.all(action.channel);
            isActive[action.channel] = messages != null;
            ChannelStore.emitChange();
            break;

        default:
            // noop

    }

});

export default ChannelStore;

<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp')
const babel = require('gulp-babel')
const debug = require('gulp-debug')
const rename = require('gulp-rename')
const plumber = require('gulp-plumber')
const Cache = require('gulp-file-cache')
const clean = require('gulp-clean')
const browserify = require('browserify')
const source = require('vinyl-source-stream')
const glob = require('glob')
const rp = require('request-promise')
const forever = require('forever')
const assert = require('assert')

const cache = new Cache()

const paths = {
  src: 'src'
}

function notify(title, message) {
  const uri = 'http://dockermachine:3333/notify'

  rp({
    uri: uri,
    method: 'POST',
    body: {
      title: title,
      message: message
    },
    json: true
  })
}

gulp.task('browserify', function () {
  const files = glob.sync('./dist/Common/Resources/views/*/*.js')

  return browserify({
    entries: files
  })
    .bundle()
    .pipe(source('components.js'))
    .pipe(gulp.dest('./public/js'))
});

gulp.task('cleanDistDirectory', function() {
  return gulp.src('dist', {read: false})
    .pipe(clean())
})

gulp.task('jsxCompile', [ 'cleanDistDirectory' ], function () {
  return gulp
    .src('src/**/*.jsx')
//    .pipe(cache.filter())
    .pipe(plumber())
    .pipe(debug({}))
    .pipe(babel({
        presets: ['react', 'es2015']
    }))
//    .pipe(cache.cache())
    .pipe(rename(function (path) {
      path.extname = '.js'
    }))
    .pipe(gulp.dest('dist'))
})

gulp.task('jsCompile', [ 'cleanDistDirectory' ], function () {
  return gulp
    .src('src/**/*.js')
//    .pipe(cache.filter())
    .pipe(plumber())
    .pipe(debug({}))
    .pipe(babel({
      presets: [ 'es2015' ]
    }))
//    .pipe(cache.cache())
    .pipe(gulp.dest('dist/'))
})

gulp.task('notifyMainStarted', function () {
  notify('Nest - Gulp - main', 'Starting build.')
})

gulp.task('main', [ 'notifyMainStarted', 'jsxCompile', 'jsCompile' ])

gulp.task('notifyWatching', function () {
  notify('Nest - Gulp - watch', 'Starting watching.')
})

const children = []

function runProcess(command) {
  const child = new (forever.Monitor)(command)

  children.push(child)

  child.start()
}

gulp.task('mainWatch', ['main'], function () {
  children.forEach(function (child) {
    child.stop()
  })

  runProcess('dist/PublicApi/App.js')
  runProcess('dist/Front/App.js')
  runProcess('dist/Worker/App.js')
  runProcess('dist/Scheduler/App.js')
})

gulp.task('watch', [ 'notifyWatching', 'mainWatch' ], function () {
  return gulp.watch(paths.src + '/**/*', [ 'mainWatch' ])
})
<commit_msg>Work in progress.<commit_after>'use strict';

const gulp = require('gulp')
const babel = require('gulp-babel')
const debug = require('gulp-debug')
const rename = require('gulp-rename')
const plumber = require('gulp-plumber')
const Cache = require('gulp-file-cache')
const clean = require('gulp-clean')
const browserify = require('browserify')
const source = require('vinyl-source-stream')
const glob = require('glob')
const rp = require('request-promise')
const forever = require('forever')
const assert = require('assert')
const process = require('process')

const cache = new Cache()

const paths = {
  src: 'src'
}

function notify(title, message) {
  const uri = 'http://dockermachine:3333/notify'

  rp({
    uri: uri,
    method: 'POST',
    body: {
      title: title,
      message: message
    },
    json: true
  })
}

gulp.task('browserify', function () {
  const files = glob.sync('./dist/Common/Resources/views/*/*.js')

  return browserify({
    entries: files
  })
    .bundle()
    .pipe(source('components.js'))
    .pipe(gulp.dest('./public/js'))
})

gulp.task('cleanDistDirectory', function() {
  return gulp.src('dist', {read: false})
    .pipe(clean())
})

gulp.task('jsxCompile', [ 'cleanDistDirectory' ], function () {
  return gulp
    .src('src/**/*.jsx')
//    .pipe(cache.filter())
    .pipe(plumber())
    .pipe(debug({}))
    .pipe(babel({
        presets: ['react', 'es2015']
    }))
//    .pipe(cache.cache())
    .pipe(rename(function (path) {
      path.extname = '.js'
    }))
    .pipe(gulp.dest('dist'))
})

gulp.task('jsCompile', [ 'cleanDistDirectory' ], function () {
  return gulp
    .src('src/**/*.js')
//    .pipe(cache.filter())
    .pipe(plumber())
    .pipe(debug({}))
    .pipe(babel({
      presets: [ 'es2015' ]
    }))
//    .pipe(cache.cache())
    .pipe(gulp.dest('dist/'))
})

gulp.task('notifyMainStarted', function () {
  notify('Nest - Gulp - main', 'Starting build.')
})

gulp.task('main', [ 'notifyMainStarted', 'jsxCompile', 'jsCompile' ])

gulp.task('notifyWatching', function () {
  notify('Nest - Gulp - watch', 'Starting watching.')
})

const children = []

function runProcess(command) {
  const child = new (forever.Monitor)(command)

  children.push(child)

  child.start()
}

function stopChildren() {
  children.forEach(function (child) {
    console.log('Stopping child')

    child.stop()
  })
}

process.on('SIGINT', function() {
  console.log('SIGINT: aborting')

  stopChildren()

  process.exit()
})

gulp.task('mainWatch', ['main'], function () {
  stopChildren()

  runProcess('dist/PublicApi/App.js')
  runProcess('dist/Front/App.js')
  runProcess('dist/Worker/App.js')
  runProcess('dist/Scheduler/App.js')
})

gulp.task('watch', [ 'notifyWatching', 'mainWatch' ], function () {
  return gulp.watch(paths.src + '/**/*', [ 'mainWatch' ])
})
<|endoftext|>