<commit_before>(function () {
  const actions = new Map();
  function keyCombo(combo) {
    for (let k of combo) {
      document.dispatchEvent(new KeyboardEvent("keydown", { key: k }));
    }
  }
  actions.set("snooze", function () {
    keyCombo("b");
  });
  actions.set("snoozed", function () {
    keyCombo("gb");
  });
  actions.set("inbox", function () {
    keyCombo("gi");
  });
  actions.set("sent", function () {
    keyCombo("gt");
  });
  actions.set("starred", function () {
    keyCombo("gs");
  });
  actions.set("all", function () {
    keyCombo("ga");
  });
  actions.set("go to label", function () {
    keyCombo("gl");
  });
  actions.set("label", function () {
    keyCombo("l");
  });
  // add all labels
  [...document.querySelectorAll("a")]
    .filter((x) => x.href.indexOf("label") > -1)
    .map((x) => x.href.slice(x.href.indexOf("#")))
    .forEach(function (label) {
      actions.set(label, function () {
        // Looks like this doesn't work due to isTrusted property, see:
        // https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
        // It may be possible to make this work with a browser extension:
        // https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchKeyEvent
        window.location.hash = label;
      });
    });
  actions.set("select all", function () {
    keyCombo("*a");
  });

  submit = function ([k, action]) {
    action();
    console.log("ran action", k);
  };
  class Suggestions {
    constructor() {
      this.box = document.createElement("div");
      this.selected = 0;
    }

    computeSuggestions(command) {
      let pattern = new RegExp(command.replaceAll(" ", ".*"));
      let candidates = [...actions].filter(function ([k, v]) {
        return pattern.test(k);
      });
      return candidates;
    }

    render() {
      this.box.innerHTML = "";
      for (let i = 0; i < this.suggestions.length; i++) {
        let k = this.suggestions[i][0];
        let li = document.createElement("li");
        li.innerHTML = k;
        if (i === this.selected) {
          li.style = "background: #add8e6";
        }
        this.box.appendChild(li);
      }
    }

    update(command) {
      this.command = command;
      this.suggestions = this.computeSuggestions(command);
      this.nextPrevSelected(0);
      this.render();
    }

    getBox() {
      return this.box;
    }

    nextPrevSelected(i) {
      if (this.suggestions.length > 0) {
        this.selected =
          (this.selected + i + this.suggestions.length) %
          this.suggestions.length;
      }
      this.render();
    }

    nextSelected() {
      this.nextPrevSelected(1);
    }

    prevSelected() {
      this.nextPrevSelected(-1);
    }

    getSelected() {
      return this.suggestions[this.selected]; // TODO: select with arrows and mouse
    }
  }

  let suggestions = new Suggestions();
  let box;

  function close() {
    if (box) {
      box.parentNode.removeChild(box);
    }
    box = null;
  }

  f = function () {
    box = document.createElement("div");
    let form = document.createElement("form");
    box.appendChild(form);
    box.appendChild(suggestions.getBox());
    let input = document.createElement("input");
    input.onkeyup = function () {
      suggestions.update(input.value);
    };
    form.appendChild(input);
    document.body.appendChild(box);
    box.style =
      "position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 40px; border-radius: 20px; z-index: 1000";
    input.focus();
    form.onsubmit = function () {
      close();
      let suggestion = suggestions.getSelected();
      if (suggestion) {
        submit(suggestions.getSelected());
      }
      return false;
    };
  };
  document.onkeydown = function (e) {
    if (e.ctrlKey && e.key === "k") {
      f();
      return false;
    }
    if (e.key === "ArrowUp") {
      suggestions.prevSelected();
    }
    if (e.key === "ArrowDown") {
      suggestions.nextSelected();
    }
    if (e.key === "Escape") {
      close();
    }
  };
})();
<commit_msg>More tweaks<commit_after>(function () {
  const actions = new Map();
  function keyCombo(combo) {
    for (let k of combo) {
      document.dispatchEvent(new KeyboardEvent("keydown", { key: k }));
    }
  }
  actions.set("snooze", function () {
    keyCombo("b");
  });
  actions.set("snoozed", function () {
    keyCombo("gb");
  });
  actions.set("inbox", function () {
    keyCombo("gi");
  });
  actions.set("sent", function () {
    keyCombo("gt");
  });
  actions.set("starred", function () {
    keyCombo("gs");
  });
  actions.set("all", function () {
    keyCombo("ga");
  });
  actions.set("label", function () {
    keyCombo("l");
  });
  // add all labels
  [...document.querySelectorAll("a")]
    .filter((x) => x.href.indexOf("label") > -1)
    .map((x) => x.href.slice(x.href.indexOf("#")))
    .forEach(function (label) {
      actions.set(label.replace("#label/", "#"), function () {
        // Looks like this doesn't work due to isTrusted property, see:
        // https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
        // It may be possible to make this work with a browser extension:
        // https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchKeyEvent
        window.location.hash = label;
      });
    });
  actions.set("select all", function () {
    keyCombo("*a");
  });

  submit = function ([k, action]) {
    action();
    console.log("ran action", k);
  };
  class Suggestions {
    constructor() {
      this.box = document.createElement("div");
      this.box.style = "overflow: scroll; max-height: 200px";
      this.selected = 0;
    }

    computeSuggestions(command) {
      let pattern = new RegExp(command.replaceAll(" ", ".*"));
      let candidates = [...actions].filter(function ([k, v]) {
        return pattern.test(k);
      });
      return candidates;
    }

    render() {
      console.log(this.selected);
      this.box.innerHTML = "";
      let selectedLi;
      for (let i = 0; i < this.suggestions.length; i++) {
        let k = this.suggestions[i][0];
        let li = document.createElement("li");
        li.innerHTML = k;
        if (i === this.selected) {
          li.style = "background: #add8e6";
          selectedLi = li;
        }
        this.box.appendChild(li);
      }
      if (selectedLi) selectedLi.scrollIntoView({ block: "nearest" });
    }

    update(command) {
      this.command = command;
      this.suggestions = this.computeSuggestions(command);
      this.nextPrevSelected(0);
      this.render();
    }

    getBox() {
      return this.box;
    }

    nextPrevSelected(i) {
      if (this.suggestions.length > 0) {
        this.selected =
          (this.selected + i + this.suggestions.length) %
          this.suggestions.length;
      }
      this.render();
    }

    nextSelected() {
      this.nextPrevSelected(1);
    }

    prevSelected() {
      this.nextPrevSelected(-1);
    }

    getSelected() {
      return this.suggestions[this.selected]; // TODO: select with arrows and mouse
    }
  }

  let suggestions = new Suggestions();
  let box;

  function close() {
    if (box) {
      box.parentNode.removeChild(box);
    }
    box = null;
  }

  f = function () {
    box = document.createElement("div");
    let form = document.createElement("form");
    box.appendChild(form);
    box.appendChild(suggestions.getBox());
    let input = document.createElement("input");
    input.style.width = "100%";
    input.onkeyup = function () {
      suggestions.update(input.value);
    };
    form.appendChild(input);
    document.body.appendChild(box);
    box.style =
      "position: absolute; top: 50%; left: 50%; width:400px; transform: translate(-50%, -50%); background: white; padding: 40px; border-radius: 20px; z-index: 1000";
    input.focus();
    form.onsubmit = function () {
      close();
      let suggestion = suggestions.getSelected();
      if (suggestion) {
        submit(suggestions.getSelected());
      }
      return false;
    };
  };
  document.onkeydown = function (e) {
    if (e.ctrlKey && e.key === "k") {
      f();
      return false;
    }
    if (e.key === "ArrowUp") {
      suggestions.prevSelected();
    }
    if (e.key === "ArrowDown") {
      suggestions.nextSelected();
    }
    if (e.key === "Escape") {
      close();
    }
  };
})();
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    del = require('del'),
    reload = browserSync.reload,
    runSequence = require('run-sequence');

var src = 'src',
    dist = 'dist',
    dirs = {
        css: src + '/assets/css',
        html: src + '/assets/html',
        img: src + '/assets/img',
        js: src + '/assets/js',
        sass: src + '/assets/sass',
        vend: src + '/assets/vendor'
    },
    build = {
        css: dist + '/assets/css',
        img: dist + '/assets/img',
        js: dist + '/assets/js',
        sass: dist + '/assets/sass',
        vend: dist + '/assets/vendor'
    };

// 'full' or 'assets'
var distMode = 'assets',
    minCss = false,
    minJs = false;

// browser-sync task for starting the server.
gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: src
        },
        port: 9000
    });
});

gulp.task('build', function(cb) {
    runSequence(
        'cleanByDistMode', ['styles', 'concat'],
        'copyByDistMode', ['clean:sprite'],
        'imagemin',
        'clean:release',
        'copy:vendors',
        cb
    );
});

gulp.task('clean:release', function(cb) {
    return del([
        build.sass,
        build.js + '/**/*',
        '!' + build.js + '/scripts.js',
        build.vend
    ], {
        force: true
    }, cb);
});

gulp.task('clean:sprite', function(cb) {
    return del([
        build.img + '/sprite/hd',
        build.img + '/sprite/standard'
    ], {
        force: true
    }, cb);
});

gulp.task('cleanByDistMode', function(cb) {
    switch (distMode) {
        case 'assets':
            return del(dist + '/assets', {
                force: true
            }, cb);
            break;
        default:
            return del(dist, {
                force: true
            }, cb);
    }
});

gulp.task('concat', function() {
    return gulp.src([
            // Plugins
            dirs.js + '/plugins.js',
            // Vendors
            dirs.vend + '/bootstrap-sass-official/assets/javascripts/bootstrap.js',
            dirs.vend + '/**/*jquery.mask.min.js',
            dirs.vend + '/**/*retina.min.js',
            // Main
            dirs.js + '/main.js',
            // Modules
            dirs.js + '/modules/**/*.js'
        ])
        .pipe($.plumber())
        .pipe($.concat('scripts.js'))
        .pipe($.if(minJs, $.uglify().on('error', console.error.bind(console, 'Uglify error:'))))
        .pipe(gulp.dest(dirs.js))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('copyByDistMode', function() {
    switch (distMode) {
        case 'assets':
            return gulp.src([
                    src + '/assets/**/*'
                ])
                .pipe(gulp.dest(dist + '/assets'));
            break;
        default:
            return gulp.src([
                    src + '/**/*'
                ])
                .pipe(gulp.dest(dist));
    }
});

gulp.task('copy:vendors', function() {
    return gulp.src([
            dirs.vend + '/**/*jquery.min.js'
        ])
        .pipe(gulp.dest(build.vend));
});

gulp.task('default', ['browser-sync'], function() {
    gulp.watch(dirs.sass + '/**/*.scss', ['styles']);
    gulp.watch([
        dirs.js + '/plugins.js',
        dirs.js + '/main.js',
        dirs.js + '/modules/**/*.js'
    ], ['concat']);
    gulp.watch(src + '/**/*.html').on('change', reload);
});

gulp.task('html', function() {
    return gulp.src(dirs.html + '/*.tpl.html')
        .pipe($.fileInclude())
        .pipe($.rename({
            extname: ''
        }))
        .pipe($.rename({
            extname: '.html'
        }))
        .pipe(gulp.dest(src));
});

gulp.task('imagemin', function() {
    return gulp.src(build.img + '/**/*.{svg,png,jpg,jpeg,gif}')
        .pipe($.imagemin({
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest(build.img))
        .pipe($.size({
            title: 'imagemin',
            showFiles: true
        }));
});

gulp.task('styles', function() {
    return gulp.src(dirs.sass + '/main.scss')
        .pipe($.cssGlobbing({
            extensions: ['.scss']
        }))
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            outputStyle: 'nested', // libsass doesn't support expanded yet
            precision: 10,
            includePaths: ['.'],
            onError: console.error.bind(console, 'Sass error:')
        }))
        .pipe($.postcss([
            require('autoprefixer-core')({
                browsers: ['last 1 version']
            })
        ]))
        .pipe($.sourcemaps.write())
        .pipe($.if(minCss, $.csso()))
        .pipe(gulp.dest(dirs.css))
        .pipe(reload({
            stream: true
        }));
});
<commit_msg>Reindentando o gulpfile<commit_after>var gulp = require('gulp'),
	$ = require('gulp-load-plugins')(),
	browserSync = require('browser-sync'),
	del = require('del'),
	reload = browserSync.reload,
	runSequence = require('run-sequence');

var src = 'src',
	dist = 'dist',
	dirs = {
		css: src + '/assets/css',
		html: src + '/assets/html',
		img: src + '/assets/img',
		js: src + '/assets/js',
		sass: src + '/assets/sass',
		vend: src + '/assets/vendor'
	},
	build = {
		css: dist + '/assets/css',
		img: dist + '/assets/img',
		js: dist + '/assets/js',
		sass: dist + '/assets/sass',
		vend: dist + '/assets/vendor'
	};

// 'full' or 'assets'
var distMode = 'assets',
	minCss = false,
	minJs = false;

// browser-sync task for starting the server.
gulp.task('browser-sync', function() {
	browserSync({
		server: {
			baseDir: src
		},
		port: 9000
	});
});

gulp.task('build', function(cb) {
	runSequence(
		'cleanByDistMode', ['styles', 'concat'],
		'copyByDistMode', ['clean:sprite'],
		'imagemin',
		'clean:release',
		'copy:vendors',
		cb
	);
});

gulp.task('clean:release', function(cb) {
	return del([
		build.sass,
		build.js + '/**/*',
		'!' + build.js + '/scripts.js',
		build.vend
	], {
		force: true
	}, cb);
});

gulp.task('clean:sprite', function(cb) {
	return del([
		build.img + '/sprite/hd',
		build.img + '/sprite/standard'
	], {
		force: true
	}, cb);
});

gulp.task('cleanByDistMode', function(cb) {
	switch (distMode) {
		case 'assets':
			return del(dist + '/assets', {
				force: true
			}, cb);
			break;
		default:
			return del(dist, {
				force: true
			}, cb);
	}
});

gulp.task('concat', function() {
	return gulp.src([
			// Plugins
			dirs.js + '/plugins.js',
			// Vendors
			dirs.vend + '/bootstrap-sass-official/assets/javascripts/bootstrap.js',
			dirs.vend + '/**/*jquery.mask.min.js',
			dirs.vend + '/**/*retina.min.js',
			// Main
			dirs.js + '/main.js',
			// Modules
			dirs.js + '/modules/**/*.js'
		])
		.pipe($.plumber())
		.pipe($.concat('scripts.js'))
		.pipe($.if(minJs, $.uglify().on('error', console.error.bind(console, 'Uglify error:'))))
		.pipe(gulp.dest(dirs.js))
		.pipe(reload({
			stream: true
		}));
});

gulp.task('copyByDistMode', function() {
	switch (distMode) {
		case 'assets':
			return gulp.src([
					src + '/assets/**/*'
				])
				.pipe(gulp.dest(dist + '/assets'));
			break;
		default:
			return gulp.src([
					src + '/**/*'
				])
				.pipe(gulp.dest(dist));
	}
});

gulp.task('copy:vendors', function() {
	return gulp.src([
			dirs.vend + '/**/*jquery.min.js'
		])
		.pipe(gulp.dest(build.vend));
});

gulp.task('default', ['browser-sync'], function() {
	gulp.watch(dirs.sass + '/**/*.scss', ['styles']);
	gulp.watch([
		dirs.js + '/plugins.js',
		dirs.js + '/main.js',
		dirs.js + '/modules/**/*.js'
	], ['concat']);
	gulp.watch(src + '/**/*.html').on('change', reload);
});

gulp.task('html', function() {
	return gulp.src(dirs.html + '/*.tpl.html')
		.pipe($.fileInclude())
		.pipe($.rename({
			extname: ''
		}))
		.pipe($.rename({
			extname: '.html'
		}))
		.pipe(gulp.dest(src));
});

gulp.task('imagemin', function() {
	return gulp.src(build.img + '/**/*.{svg,png,jpg,jpeg,gif}')
		.pipe($.imagemin({
			progressive: true,
			interlaced: true
		}))
		.pipe(gulp.dest(build.img))
		.pipe($.size({
			title: 'imagemin',
			showFiles: true
		}));
});

gulp.task('styles', function() {
	return gulp.src(dirs.sass + '/main.scss')
		.pipe($.cssGlobbing({
			extensions: ['.scss']
		}))
		.pipe($.sourcemaps.init())
		.pipe($.sass({
			outputStyle: 'nested', // libsass doesn't support expanded yet
			precision: 10,
			includePaths: ['.'],
			onError: console.error.bind(console, 'Sass error:')
		}))
		.pipe($.postcss([
			require('autoprefixer-core')({
				browsers: ['last 1 version']
			})
		]))
		.pipe($.sourcemaps.write())
		.pipe($.if(minCss, $.csso()))
		.pipe(gulp.dest(dirs.css))
		.pipe(reload({
			stream: true
		}));
});

<|endoftext|>


<commit_before>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    cache = require('gulp-cache'),
    del = require('del'),
    git = require('gulp-git'),
    bump = require('gulp-bump'),
    tag = require('gulp-tag-version');

var proc = require('child_process');

var css_src = './public/scss/*.scss';
var js_src = [
  './public/js/dnss.js',
  './public/js/skill.js',
  './public/js/description.js'
];

gulp.task('css', function () {
  gulp.src(css_src)
      .pipe(concat('dnss.scss'))
      .pipe(sass({outputStyle: 'compressed'}))
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest('./public/css'));
});

gulp.task('js', function() {
  return gulp.src(js_src)
    .pipe(concat('dnss.js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('./public/js'))
});

gulp.task('watch', function() {
  gulp.watch(css_src, ['css']);
  gulp.watch(js_src, ['js']);
});

function inc(importance) {
  return function() {
    gulp.src('./package.json')
        .pipe(bump({type: importance}))
        .pipe(gulp.dest('./'))
        .pipe(git.commit('[gulp] bumping package version'))
        .pipe(tag());
    git.push('origin', 'master', {args: ' --folow-tags' });
  };
}

gulp.task('patch', inc('patch'));
gulp.task('feature', inc('minor'));
gulp.task('release', inc('major'));
gulp.task('default', ['css', 'js'], function() {});<commit_msg>More changes..<commit_after>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    cache = require('gulp-cache'),
    del = require('del'),
    git = require('gulp-git'),
    bump = require('gulp-bump'),
    tag = require('gulp-tag-version');

var proc = require('child_process');

var css_src = './public/scss/*.scss';
var js_src = [
  './public/js/dnss.js',
  './public/js/skill.js',
  './public/js/description.js'
];

gulp.task('css', function () {
  gulp.src(css_src)
      .pipe(concat('dnss.scss'))
      .pipe(sass({outputStyle: 'compressed'}))
      .pipe(rename({suffix: '.min'}))
      .pipe(gulp.dest('./public/css'));
});

gulp.task('js', function() {
  return gulp.src(js_src)
    .pipe(concat('dnss.js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gulp.dest('./public/js'))
});

gulp.task('watch', function() {
  gulp.watch(css_src, ['css']);
  gulp.watch(js_src, ['js']);
});

function inc(importance) {
  return function() {
    gulp.src('./package.json')
        .pipe(bump({type: importance}))
        .pipe(gulp.dest('./'))
        .pipe(git.commit('[gulp] bumping package version'))
        .pipe(tag());
    git.push('origin', 'master');
    git.push('origin', {args: '--tags'});
  };
}

gulp.task('patch', inc('patch'));
gulp.task('feature', inc('minor'));
gulp.task('release', inc('major'));
gulp.task('default', ['css', 'js'], function() {});<|endoftext|>


<commit_before>uniChat.controller('homeCtrl', function($scope, ChatService) {

	$scope.courses = function(){
		return ChatService.getCourses();
	}

	$scope.startCC = function(course){
		ChatService.setSelectedCourse(course);
	}

	//get uni

	var KTHcoords= {lat:59.349249, lng:18.071340};

	$scope.getPosition = function() {
	    navigator.geolocation.getCurrentPosition(function(position) {
	       var lat = position.coords.latitude;
	       var lon = position.coords.longitude;
	       //array.push(lat, lon);

	       if (lat <= 59.355717 && lat >=59.343750 && lon >= 18.053783 && lon <= 18.085455){
	        //unsub();
	        var channel = 'KTH';
	        $scope.setPosition(channel);
	        $scope.setPosition(channel)
	      }
	  });
	}

	$scope.getUni = function() {
  		return ChatService.getSelectedUni();
	}

	$scope.setPosition = function(Uni){
		ChatService.setSelectedUni(Uni);
		$scope.$apply();
	}

$scope.getPosition();

});
<commit_msg>removed duplicate<commit_after>uniChat.controller('homeCtrl', function($scope, ChatService) {

	$scope.courses = function(){
		return ChatService.getCourses();
	}

	$scope.startCC = function(course){
		ChatService.setSelectedCourse(course);
	}

	//get uni

	var KTHcoords= {lat:59.349249, lng:18.071340};

	$scope.getPosition = function() {
	    navigator.geolocation.getCurrentPosition(function(position) {
	       var lat = position.coords.latitude;
	       var lon = position.coords.longitude;
	       //array.push(lat, lon);

	       if (lat <= 59.355717 && lat >=59.343750 && lon >= 18.053783 && lon <= 18.085455){
	        //unsub();
	        var channel = 'KTH';
	        $scope.setPosition(channel);
	      }
	  });
	}

	$scope.getUni = function() {
  		return ChatService.getSelectedUni();
	}

	$scope.setPosition = function(Uni){
		ChatService.setSelectedUni(Uni);
		$scope.$apply();
	}

$scope.getPosition();

});
<|endoftext|>


<commit_before>var gulp = require('gulp-help')(require('gulp'), {description: ''});
var $ = require('gulp-load-plugins')();
var through = require('through2');
var runSequence = require('run-sequence');
var del = require('del');
var buildBranch = require('buildbranch');
var webpackMiddleware = require('webpack-dev-middleware');
var webpack = require('webpack');
var path = require('path');

var webpackConfigTemplate = {
  entry: {
    index: './src/scripts/index.js',
    thirdparty: [
      'd3', 'moment', 'pikaday', 'query-string', 'superagent', 'vue',
      'fastclick', 'strkio-storage-githubgist'
    ],
    'dev-mode': './src/scripts/dev-mode.js'
  },
  resolve: {
    modulesDirectories: ['bower_components', 'node_modules'],
    alias: {
      superagent: 'superagent/superagent.js'
    }
  },
  externals: {
    jsonify: 'JSON'
  },
  module: {
    noParse: [/(d3|moment|pikaday|query-string|superagent|vue|fastclick)/],
    loaders: [
      {
        test: /\.html/,
        loader: 'html',
        query: {
          removeRedundantAttributes: false // because of foundation
        }
      }
    ]
  },
  plugins: [
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(
        '.bower.json', ['main']
      )
    ),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};

var optimize = false;

var src = {
  js: ['gulpfile.js', 'src/scripts/**/*.js'],
  css: 'src/stylesheets/**/*.css',
  html: 'src/*.html'
};

gulp.task('build', function (cb) {
  optimize = true;
  runSequence('clean', [
    'build:favicon',
    'build:fonts',
    'build:html',
    'build:scripts',
    'build:stylesheets'
  ], 'build:rev', cb);
});

gulp.task('build:favicon', function () {
  gulp.src('src/favicon.ico')
    .pipe(gulp.dest('build'));
});

gulp.task('build:fonts', function () {
  return gulp.src('src/fonts/*.ttf', {base: 'src'})
    .pipe(gulp.dest('build'));
});

gulp.task('build:html', function () {
  var htmlminConfig = {};
  var preprocessctx = {};
  if (optimize) {
    htmlminConfig.removeComments = true;
    htmlminConfig.collapseWhitespace = true;
    preprocessctx.NODE_ENV = 'production';
  }
  return gulp.src(src.html)
    .pipe($.preprocess({context: preprocessctx}))
    .pipe($.htmlmin(htmlminConfig))
    .pipe(gulp.dest('build'));
});

gulp.task('build:rev', function () {
  var revved = [];
  var filter = $.filter(['**', '!index.html']);
  return gulp.src([
    'build/scripts/*.js',
    'build/stylesheets/*.css',
    'build/favicon.ico',
    'build/index.html'
  ], {base: path.join(__dirname, 'build')})
    .pipe(filter)
    .pipe($.rev())
    .pipe(filter.restore())
    .pipe(through.obj(function (file, enc, callback) {
      if (file.revOrigPath) {
        revved.push(file.revOrigPath);
      }
      this.push(file);
      callback();
    }))
    .pipe($.revReplace({replaceInExtensions: '.html'}))
    .pipe(gulp.dest('build'))
    .on('end', function (cb) {
      del(revved, cb);
    });
});

gulp.task('build:scripts', function (cb) {
  var webpackConfig = Object.create(webpackConfigTemplate);
  if (optimize) {
    webpackConfig.plugins || (webpackConfig.plugins = []);
    webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
      'thirdparty', 'build/scripts/thirdparty.js'));
    webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }));
  }
  webpackConfig.output = {filename: 'build/scripts/[name].js'};
  webpack(webpackConfig, function (err, stats) {
    if (err) {
      return cb(err);
    }
    console.log(stats.toString());
    cb();
  });
});

gulp.task('build:stylesheets', function () {
  return gulp.src([
    'src/stylesheets/index.css',
    'src/stylesheets/thirdparty.css' // todo: replace with concat
  ], {base: 'src'})
    .pipe($.myth())
    .on('error', console.log)
    .pipe(optimize ? $.csso() : through.obj())
    .pipe(gulp.dest('build'));
});

gulp.task('clean', function (cb) {
  del(['build'], {force: true}, cb);
});

gulp.task('deploy', function (cb) {
  buildBranch({
    folder: 'build',
    domain: 'strk.io',
    branch: 'master'
  }, cb);
});

gulp.task('lint', ['lint:scripts']);

gulp.task('lint:scripts', function () {
  return gulp.src(src.js)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jscs());
});

gulp.task('serve', ['clean', 'build:stylesheets', 'build:html'], function () {
  var webpackConfig = Object.create(webpackConfigTemplate);
  webpackConfig.devtool = 'eval'; // http://webpack.github.io/docs/configuration.html#devtool
  webpackConfig.output = {path: '/', filename: 'scripts/[name].js'};
  webpackConfig.plugins || (webpackConfig.plugins = []);
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
    'thirdparty', 'scripts/thirdparty.js'));
  $.connect.server({
    root: ['build', 'src', '.'],
    port: 8000,
    middleware: function () {
      return [
        webpackMiddleware(webpack(webpackConfig))
      ];
    }
  });
  gulp.watch(src.css, ['build:stylesheets']);
  gulp.watch(src.js, ['lint:scripts']);
  gulp.watch(src.html, ['build:html']);
});

gulp.task('serve:build', function () {
  $.connect.server({root: 'build', port: 9000});
});

gulp.task('usemin', function () {
  return gulp.src('src/index.html')
    .pipe($.usemin())
    .pipe(gulp.dest('build/'));
});
<commit_msg>Fixed serve task definition<commit_after>var gulp = require('gulp-help')(require('gulp'), {description: ''});
var $ = require('gulp-load-plugins')();
var through = require('through2');
var runSequence = require('run-sequence');
var del = require('del');
var buildBranch = require('buildbranch');
var webpackMiddleware = require('webpack-dev-middleware');
var webpack = require('webpack');
var path = require('path');

var webpackConfigTemplate = {
  entry: {
    index: './src/scripts/index.js',
    thirdparty: [
      'd3', 'moment', 'pikaday', 'query-string', 'superagent', 'vue',
      'fastclick', 'strkio-storage-githubgist'
    ],
    'dev-mode': './src/scripts/dev-mode.js'
  },
  resolve: {
    modulesDirectories: ['bower_components', 'node_modules'],
    alias: {
      superagent: 'superagent/superagent.js'
    }
  },
  externals: {
    jsonify: 'JSON'
  },
  module: {
    noParse: [/(d3|moment|pikaday|query-string|superagent|vue|fastclick)/],
    loaders: [
      {
        test: /\.html/,
        loader: 'html',
        query: {
          removeRedundantAttributes: false // because of foundation
        }
      }
    ]
  },
  plugins: [
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(
        '.bower.json', ['main']
      )
    ),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};

var optimize = false;

var src = {
  js: ['gulpfile.js', 'src/scripts/**/*.js'],
  css: 'src/stylesheets/**/*.css',
  html: 'src/*.html'
};

gulp.task('build', function (cb) {
  optimize = true;
  runSequence('clean', [
    'build:favicon',
    'build:fonts',
    'build:html',
    'build:scripts',
    'build:stylesheets'
  ], 'build:rev', cb);
});

gulp.task('build:favicon', function () {
  gulp.src('src/favicon.ico')
    .pipe(gulp.dest('build'));
});

gulp.task('build:fonts', function () {
  return gulp.src('src/fonts/*.ttf', {base: 'src'})
    .pipe(gulp.dest('build'));
});

gulp.task('build:html', function () {
  var htmlminConfig = {};
  var preprocessctx = {};
  if (optimize) {
    htmlminConfig.removeComments = true;
    htmlminConfig.collapseWhitespace = true;
    preprocessctx.NODE_ENV = 'production';
  }
  return gulp.src(src.html)
    .pipe($.preprocess({context: preprocessctx}))
    .pipe($.htmlmin(htmlminConfig))
    .pipe(gulp.dest('build'));
});

gulp.task('build:rev', function () {
  var revved = [];
  var filter = $.filter(['**', '!index.html']);
  return gulp.src([
    'build/scripts/*.js',
    'build/stylesheets/*.css',
    'build/favicon.ico',
    'build/index.html'
  ], {base: path.join(__dirname, 'build')})
    .pipe(filter)
    .pipe($.rev())
    .pipe(filter.restore())
    .pipe(through.obj(function (file, enc, callback) {
      if (file.revOrigPath) {
        revved.push(file.revOrigPath);
      }
      this.push(file);
      callback();
    }))
    .pipe($.revReplace({replaceInExtensions: '.html'}))
    .pipe(gulp.dest('build'))
    .on('end', function (cb) {
      del(revved, cb);
    });
});

gulp.task('build:scripts', function (cb) {
  var webpackConfig = Object.create(webpackConfigTemplate);
  if (optimize) {
    webpackConfig.plugins || (webpackConfig.plugins = []);
    webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
      'thirdparty', 'build/scripts/thirdparty.js'));
    webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }));
  }
  webpackConfig.output = {filename: 'build/scripts/[name].js'};
  webpack(webpackConfig, function (err, stats) {
    if (err) {
      return cb(err);
    }
    console.log(stats.toString());
    cb();
  });
});

gulp.task('build:stylesheets', function () {
  return gulp.src([
    'src/stylesheets/index.css',
    'src/stylesheets/thirdparty.css' // todo: replace with concat
  ], {base: 'src'})
    .pipe($.myth())
    .on('error', console.log)
    .pipe(optimize ? $.csso() : through.obj())
    .pipe(gulp.dest('build'));
});

gulp.task('clean', function (cb) {
  del(['build'], {force: true}, cb);
});

gulp.task('deploy', function (cb) {
  buildBranch({
    folder: 'build',
    domain: 'strk.io',
    branch: 'master'
  }, cb);
});

gulp.task('lint', ['lint:scripts']);

gulp.task('lint:scripts', function () {
  return gulp.src(src.js)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jscs());
});

gulp.task('serve', ['clean'], function (cb) {
  var webpackConfig = Object.create(webpackConfigTemplate);
  webpackConfig.devtool = 'eval'; // http://webpack.github.io/docs/configuration.html#devtool
  webpackConfig.output = {path: '/', filename: 'scripts/[name].js'};
  webpackConfig.plugins || (webpackConfig.plugins = []);
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
    'thirdparty', 'scripts/thirdparty.js'));
  runSequence(['build:stylesheets', 'build:html'], function () {
    $.connect.server({
      root: ['build', 'src', '.'],
      port: 8000,
      middleware: function () {
        return [
          webpackMiddleware(webpack(webpackConfig))
        ];
      }
    });
    gulp.watch(src.css, ['build:stylesheets']);
    gulp.watch(src.js, ['lint:scripts']);
    gulp.watch(src.html, ['build:html']);
    cb();
  });
});

gulp.task('serve:build', function () {
  $.connect.server({root: 'build', port: 9000});
});

gulp.task('usemin', function () {
  return gulp.src('src/index.html')
    .pipe($.usemin())
    .pipe(gulp.dest('build/'));
});
<|endoftext|>


<commit_before>// Custom JavaScript settings for Jupyter notebook

$([IPython.events]).on('command_mode.Cell', function (event, data) {

      function clearRulers(cm) {
        for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) {
          var node = cm.display.lineSpace.childNodes[i];
          if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className))
            node.parentNode.removeChild(node);
        }
      }

      selected_cell = IPython.notebook.get_selected_cell();
        if ((selected_cell instanceof IPython.CodeCell)) {
            var cm = selected_cell.code_mirror;
            clearRulers(cm);
        }

});

$([IPython.events]).on('edit_mode.Cell', function (event, data) {

    function setRulers(cm) {
        var val = cm.getOption("rulers");
        var cw = cm.defaultCharWidth();
        var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
        var minH = cm.display.scroller.offsetHeight + 30;
        for (var i = 0; i < val.length; i++) {
          var elt = document.createElement("div");
          elt.className = "CodeMirror-ruler";
          var col, cls = null, conf = val[i];
          if (typeof conf == "number") {
            col = conf;
          } else {
            col = conf.column;
            if (conf.className) elt.className += " " + conf.className;
            if (conf.color) elt.style.borderColor = conf.color;
            if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle;
            if (conf.width) elt.style.borderLeftWidth = conf.width;
            cls = val[i].className;
          }
          elt.style.left = (left + col * cw) + "px";
          elt.style.top = "-60px";
          elt.style.bottom = "-20px";
          elt.style.minHeight = minH + "px";
          cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv);
        }
      }

    var ruler = [{column: 79}];

    selected_cell = IPython.notebook.get_selected_cell();
    if ((selected_cell instanceof IPython.CodeCell)) {
        var cm = selected_cell.code_mirror;
        cm.setOption('rulers', ruler);
        setRulers(cm);
    }
});
<commit_msg>Fixed styling of JS<commit_after>// Custom JavaScript settings for Jupyter notebook

$([IPython.events]).on('command_mode.Cell', function (event, data) {

    function clearRulers(cm) {
      for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) {
        var node = cm.display.lineSpace.childNodes[i];
        if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className))
          node.parentNode.removeChild(node);
      }
    }

    selected_cell = IPython.notebook.get_selected_cell();
      if ((selected_cell instanceof IPython.CodeCell)) {
          var cm = selected_cell.code_mirror;
          clearRulers(cm);
      }

});

$([IPython.events]).on('edit_mode.Cell', function (event, data) {

    function setRulers(cm) {
        var val = cm.getOption("rulers");
        var cw = cm.defaultCharWidth();
        var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
        var minH = cm.display.scroller.offsetHeight + 30;
        for (var i = 0; i < val.length; i++) {
          var elt = document.createElement("div");
          elt.className = "CodeMirror-ruler";
          var col, cls = null, conf = val[i];
          if (typeof conf == "number") {
            col = conf;
          } else {
            col = conf.column;
            if (conf.className) elt.className += " " + conf.className;
            if (conf.color) elt.style.borderColor = conf.color;
            if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle;
            if (conf.width) elt.style.borderLeftWidth = conf.width;
            cls = val[i].className;
          }
          elt.style.left = (left + col * cw) + "px";
          elt.style.top = "-60px";
          elt.style.bottom = "-20px";
          elt.style.minHeight = minH + "px";
          cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv);
        }
      }

    var ruler = [{column: 79}];

    selected_cell = IPython.notebook.get_selected_cell();
    if ((selected_cell instanceof IPython.CodeCell)) {
        var cm = selected_cell.code_mirror;
        cm.setOption('rulers', ruler);
        setRulers(cm);
    }
});
<|endoftext|>


<commit_before>const querystring = require('querystring');
const $ = require('jquery');
const Board = require('./board');
const BoardElement = require('./board-element');
const DataElement = require('./data-element');
const Panel = require('./panel');
const api = require('./api');

const params = querystring.parse(location.search.slice(1));

class Stage {
	constructor(game, config) {
		this.game = game;
		this.config = config;
		this.$stage = this.game.$stage;
		this.blockSize = 50;
		this.caseIndex = 0;
		this.maxClock = 0;

		this.board = new Board(this.config, this.blockSize);
		this.boardElement = new BoardElement(this, this.board);
		this.panel = new Panel(this);

		this.$ranking = this.$stage.siblings('.result-layer').find('.ranking');
		this.$result = this.$stage.siblings('.result-layer').find('.result');

		this.updateStyles();
		this.updateClockElement();

		this.board.on('output', (value) => this.output(value));
		this.board.on('halt', () => this.onHalt());

		this.$stage.find('.statement').text(config.statement);

		this.$selectedBlock = this.$stage.find('.panel .block[selected]').first();

		this.$stage.find('.board .block').click((event) => {
			const $block = $(event.target);
			if (!this.board.executing) {
				const type = this.$selectedBlock.data('type');
				this.panel.takeAndPlace($block.data('x'), $block.data('y'), type);
			}
		});

		this.$stage.find('.board .block').bind('contextmenu', (event) => {
			const $block = $(event.target);
			if (!this.board.executing) {
				this.panel.takeAndPlace($block.data('x'), $block.data('y'), 'empty');
			}
			return false;
		});

		this.$stage.find('button.execute').click(() => {
			$.fx.off = params.fx === 'off';
			this.execute();
		});

		this.$stage.find('button.stop').click(() => {
			this.board.halt();
			$.fx.off = params.fx === 'off';
		});

		this.$stage.find('button.exit').click(() => {
			$.fx.off = params.fx === 'off';
			this.game.exitStage();
		});

		this.$stage.find('button.ranking').click(() => {
			this.$ranking.find('.stage-name').text(this.config.title);
			this.$ranking.addClass('loading');
			this.$ranking.show();

			api.get(`/stages/${this.config.name}/submissions`).then((submissions) => {
				this.$ranking.removeClass('loading');
				this.$ranking.find('.ranks').empty().append(submissions.map((submission) => (
					$('<li/>', {
						class: 'rank',
					}).append([
						$('<div/>', {
							class: 'name',
							text: submission.name,
						}),
						$('<div/>', {
							class: 'data',
						}).append([
							$('<div/>', {
								class: 'clocks',
								text: submission.clocks,
							}),
							$('<div/>', {
								class: 'blocks',
								text: submission.blocks,
							}),
						]),
						$('<div/>', {
							class: 'score',
							text: submission.score,
						}),
					])
				)));
			});
		});

		this.$stage.find('button.rapid').click(() => {
			if ($.fx.off) {
				$.fx.off = params.fx === 'off';
			} else {
				$.fx.off = true;
				this.boardElement.dataElements.forEach((element) => element.$data.finish());
			}
			if (!this.board.executing) {
				this.execute();
			}
		});

		this.$stage.find('.inputs').empty().append(config.input.map((input) => {
			let inputString = (typeof input === 'number') ? input.toString()
				: input.map((x) => (typeof x === 'number')
					? x.toString() : `[${x.toString()}]`).join(',');
			if (inputString.length > 15) {
				inputString = `${inputString.substring(0, 13)}...`;
			}

			return $('<div/>', {class: 'input'}).append($('<span/>', {
				class: 'inner-text',
				text: inputString,
			}));
		}));

		this.$stage.find('.inputs .input').each((index, input) => {
			const $span = $(input).find('.inner-text');
			const inputWidth = $(input).outerWidth();
			const spanWidth = $span.width();
			if (inputWidth < spanWidth) {
				$span.css({fontSize: `${inputWidth / spanWidth * 100 - 2}%`});
			}
		});

		this.$stage.find('.arrows').empty().append(config.output.map(() => (
			$('<div/>', {class: 'arrow'})
		)));

		this.$stage.find('.user-outputs').empty().append(config.output.map(() => (
			$('<div/>', {class: 'output'})
		)));

		this.$stage.find('.correct-outputs').empty().append(config.output.map((output) => (
			$('<div/>', {class: 'output'}).append($('<span/>', {
				class: 'inner-text',
				text: output,
			}
		)))));

		this.$stage.find('.outputs .output').each((index, output) => {
			const $span = $(output).find('.inner-text');
			const outputWidth = $(output).outerWidth();
			const spanWidth = $span.width();
			if (outputWidth < spanWidth) {
				$span.css({fontSize: `${outputWidth / spanWidth * 100 - 2}%`});
			}
		});

		this.$stage.find('button.stop').hide();
		this.$stage.find('button.execute').show();

		this.$ranking.find('button.close').click(() => {
			this.$ranking.hide();
		});

		// TODO: CSSでテキスト管理したい
		this.$result.find('.register').text('ランキングに登録する').attr('disabled', false).removeClass('success error');

		this.updateStyles();
	}

	execute() {
		this.caseIndex = 0;
		this.maxClock = 0;
		this.$stage.find('.user-outputs .output').empty().removeClass('correct wrong');

		this.executeCase();
	}

	executeCase() {
		const inputs = this.board.input(this.config.input[this.caseIndex]);
		inputs.forEach((input, index) => {
			input.forEach((value) => {
				new DataElement(this.boardElement, value, this.board.inputBlock[index].top);
			});
		});

		this.$stage.find('button.stop').show();
		this.$stage.find('button.execute').hide();

		this.clockUp();
	}

	clockUp() {
		this.board.step();
		this.updateClockElement();

		if (this.board.executing && !this.board.paused) {
			Promise.all(this.boardElement.animations).then(() => {
				this.boardElement.animations = [];
				this.board.pass();

				if (this.board.executing && !this.board.paused) {
					if (this.board.clock >= this.board.clockLimit) {
						this.board.halt();
						$.fx.off = params.fx === 'off';

						const $clockLimit = this.$stage.siblings('.result-layer').find('.clock-limit');

						$clockLimit.find('.limit-value').text(this.board.clockLimit);
						$clockLimit.show();

						return;
					}

					if (this.board.dataCount > 100) {
						this.board.halt();
						$.fx.off = params.fx === 'off';

						const $dataLimit = this.$stage.siblings('.result-layer').find('.data-limit');

						$dataLimit.show();

						return;
					}

					this.clockUp();
				}
			});
		}
	}

	updateClockElement() {
		this.$stage.find('.clock-value').text(`${this.board.clock}/${this.board.clockLimit}`);
	}

	onHalt() {
		this.boardElement.animations = [];
		this.boardElement.eraseData();
		this.$stage.find('button.stop').hide();
		this.$stage.find('button.execute').show();
	}

	output(value) {
		const $output = this.$stage.find('.user-outputs .output').eq(this.caseIndex);

		$output.text(value);
		$output.removeClass('correct wrong');

		if (this.config.output[this.caseIndex] === value) {
			$output.addClass('correct');

			this.maxClock = Math.max(this.maxClock, this.board.clock);

			if (this.config.output.length === this.caseIndex + 1) {
				$.fx.off = params.fx === 'off';
				this.game.answer();
			} else {
				this.caseIndex++;
				this.executeCase();
			}
		} else {
			$.fx.off = params.fx === 'off';
			$output.addClass('wrong');
		}
	}

	updateStyles() {
		const boardWidth = this.$stage.find('.board-area').width() - 50;
		const boardHeight = this.$stage.find('.board-area').height() - 70;
		const boardSize = Math.min(boardWidth, boardHeight); // 上下のmarginは固定と仮定
		const stageSize = Math.max(this.config.width, this.config.height);
		if (boardSize > 50 * stageSize) {
			this.blockSize = 50;
		} else {
			this.blockSize = boardSize / stageSize;
		}

		this.board.setBlockSize(this.blockSize);

		this.$stage.find('.board .block').height(this.blockSize);
		this.$stage.find('.board .block').width(this.blockSize);
		this.$stage.find('.board-frame-wrapper').css({
			width: `${50 + this.config.width * this.blockSize}px`,
		});
		this.$stage.find('.board-frame').css({
			height: `${50 + this.config.height * this.blockSize}px`,
			flexBasis: `${50 + this.config.height * this.blockSize}px`,
		});

		const $leftPipe = this.$stage.find('.case-joint-top-pipe');
		const leftMargin = ($leftPipe.parent().width() - $leftPipe.width()) / 2;

		const $boardArea = this.$stage.find('.board-area');
		const $rightPipe = this.$stage.find('.board-joint-top-pipe');
		const rightMargin = ($boardArea.width() - $rightPipe.width()) / 2;

		this.$stage.find('.upper-pipe-area, .downer-pipe-area').css({
			marginLeft: `${leftMargin}px`,
			marginRight: `${rightMargin}px`,
		});
	}

	onRegister(event) {
		const name = this.$result.find('.name').val();
		if (name.length === 0) {
			return;
		}

		$(event.target).attr('disabled', true);

		api.post(`/stages/${this.config.name}/submissions`, {
			name,
			board: this.board.boardData,
		}).then((data) => {
			if (data.error) {
				if (data.message === 'user name existing') {
					this.$result.find('.register').text('すでに登録されています').addClass('success');
				} else {
					this.$result.find('.register').text('エラーが発生しました').addClass('error');
				}

				return;
			}

			this.$result.find('.register').text('登録しました!!').addClass('success');
		});
	}
}

module.exports = Stage;
<commit_msg>Add more event about ranking<commit_after>/* global ga */

const querystring = require('querystring');
const $ = require('jquery');
const Board = require('./board');
const BoardElement = require('./board-element');
const DataElement = require('./data-element');
const Panel = require('./panel');
const api = require('./api');

const params = querystring.parse(location.search.slice(1));

class Stage {
	constructor(game, config) {
		this.game = game;
		this.config = config;
		this.$stage = this.game.$stage;
		this.blockSize = 50;
		this.caseIndex = 0;
		this.maxClock = 0;

		this.board = new Board(this.config, this.blockSize);
		this.boardElement = new BoardElement(this, this.board);
		this.panel = new Panel(this);

		this.$ranking = this.$stage.siblings('.result-layer').find('.ranking');
		this.$result = this.$stage.siblings('.result-layer').find('.result');

		this.updateStyles();
		this.updateClockElement();

		this.board.on('output', (value) => this.output(value));
		this.board.on('halt', () => this.onHalt());

		this.$stage.find('.statement').text(config.statement);

		this.$selectedBlock = this.$stage.find('.panel .block[selected]').first();

		this.$stage.find('.board .block').click((event) => {
			const $block = $(event.target);
			if (!this.board.executing) {
				const type = this.$selectedBlock.data('type');
				this.panel.takeAndPlace($block.data('x'), $block.data('y'), type);
			}
		});

		this.$stage.find('.board .block').bind('contextmenu', (event) => {
			const $block = $(event.target);
			if (!this.board.executing) {
				this.panel.takeAndPlace($block.data('x'), $block.data('y'), 'empty');
			}
			return false;
		});

		this.$stage.find('button.execute').click(() => {
			$.fx.off = params.fx === 'off';
			this.execute();
		});

		this.$stage.find('button.stop').click(() => {
			this.board.halt();
			$.fx.off = params.fx === 'off';
		});

		this.$stage.find('button.exit').click(() => {
			$.fx.off = params.fx === 'off';
			this.game.exitStage();
		});

		this.$stage.find('button.ranking').click(() => {
			this.$ranking.find('.stage-name').text(this.config.title);
			this.$ranking.addClass('loading');
			this.$ranking.show();

			api.get(`/stages/${this.config.name}/submissions`).then((submissions) => {
				this.$ranking.removeClass('loading');
				this.$ranking.find('.ranks').empty().append(submissions.map((submission) => (
					$('<li/>', {
						class: 'rank',
					}).append([
						$('<div/>', {
							class: 'name',
							text: submission.name,
						}),
						$('<div/>', {
							class: 'data',
						}).append([
							$('<div/>', {
								class: 'clocks',
								text: submission.clocks,
							}),
							$('<div/>', {
								class: 'blocks',
								text: submission.blocks,
							}),
						]),
						$('<div/>', {
							class: 'score',
							text: submission.score,
						}),
					])
				)));
			});
		});

		this.$stage.find('button.rapid').click(() => {
			if ($.fx.off) {
				$.fx.off = params.fx === 'off';
			} else {
				$.fx.off = true;
				this.boardElement.dataElements.forEach((element) => element.$data.finish());
			}
			if (!this.board.executing) {
				this.execute();
			}
		});

		this.$stage.find('.inputs').empty().append(config.input.map((input) => {
			let inputString = (typeof input === 'number') ? input.toString()
				: input.map((x) => (typeof x === 'number')
					? x.toString() : `[${x.toString()}]`).join(',');
			if (inputString.length > 15) {
				inputString = `${inputString.substring(0, 13)}...`;
			}

			return $('<div/>', {class: 'input'}).append($('<span/>', {
				class: 'inner-text',
				text: inputString,
			}));
		}));

		this.$stage.find('.inputs .input').each((index, input) => {
			const $span = $(input).find('.inner-text');
			const inputWidth = $(input).outerWidth();
			const spanWidth = $span.width();
			if (inputWidth < spanWidth) {
				$span.css({fontSize: `${inputWidth / spanWidth * 100 - 2}%`});
			}
		});

		this.$stage.find('.arrows').empty().append(config.output.map(() => (
			$('<div/>', {class: 'arrow'})
		)));

		this.$stage.find('.user-outputs').empty().append(config.output.map(() => (
			$('<div/>', {class: 'output'})
		)));

		this.$stage.find('.correct-outputs').empty().append(config.output.map((output) => (
			$('<div/>', {class: 'output'}).append($('<span/>', {
				class: 'inner-text',
				text: output,
			}
		)))));

		this.$stage.find('.outputs .output').each((index, output) => {
			const $span = $(output).find('.inner-text');
			const outputWidth = $(output).outerWidth();
			const spanWidth = $span.width();
			if (outputWidth < spanWidth) {
				$span.css({fontSize: `${outputWidth / spanWidth * 100 - 2}%`});
			}
		});

		this.$stage.find('button.stop').hide();
		this.$stage.find('button.execute').show();

		this.$ranking.find('button.close').click(() => {
			this.$ranking.hide();
		});

		// TODO: CSSでテキスト管理したい
		this.$result.find('.register').text('ランキングに登録する').attr('disabled', false).removeClass('success error');

		this.updateStyles();
	}

	execute() {
		this.caseIndex = 0;
		this.maxClock = 0;
		this.$stage.find('.user-outputs .output').empty().removeClass('correct wrong');

		this.executeCase();
	}

	executeCase() {
		const inputs = this.board.input(this.config.input[this.caseIndex]);
		inputs.forEach((input, index) => {
			input.forEach((value) => {
				new DataElement(this.boardElement, value, this.board.inputBlock[index].top);
			});
		});

		this.$stage.find('button.stop').show();
		this.$stage.find('button.execute').hide();

		this.clockUp();
	}

	clockUp() {
		this.board.step();
		this.updateClockElement();

		if (this.board.executing && !this.board.paused) {
			Promise.all(this.boardElement.animations).then(() => {
				this.boardElement.animations = [];
				this.board.pass();

				if (this.board.executing && !this.board.paused) {
					if (this.board.clock >= this.board.clockLimit) {
						this.board.halt();
						$.fx.off = params.fx === 'off';

						const $clockLimit = this.$stage.siblings('.result-layer').find('.clock-limit');

						$clockLimit.find('.limit-value').text(this.board.clockLimit);
						$clockLimit.show();

						return;
					}

					if (this.board.dataCount > 100) {
						this.board.halt();
						$.fx.off = params.fx === 'off';

						const $dataLimit = this.$stage.siblings('.result-layer').find('.data-limit');

						$dataLimit.show();

						return;
					}

					this.clockUp();
				}
			});
		}
	}

	updateClockElement() {
		this.$stage.find('.clock-value').text(`${this.board.clock}/${this.board.clockLimit}`);
	}

	onHalt() {
		this.boardElement.animations = [];
		this.boardElement.eraseData();
		this.$stage.find('button.stop').hide();
		this.$stage.find('button.execute').show();
	}

	output(value) {
		const $output = this.$stage.find('.user-outputs .output').eq(this.caseIndex);

		$output.text(value);
		$output.removeClass('correct wrong');

		if (this.config.output[this.caseIndex] === value) {
			$output.addClass('correct');

			this.maxClock = Math.max(this.maxClock, this.board.clock);

			if (this.config.output.length === this.caseIndex + 1) {
				$.fx.off = params.fx === 'off';
				this.game.answer();
			} else {
				this.caseIndex++;
				this.executeCase();
			}
		} else {
			$.fx.off = params.fx === 'off';
			$output.addClass('wrong');
		}
	}

	updateStyles() {
		const boardWidth = this.$stage.find('.board-area').width() - 50;
		const boardHeight = this.$stage.find('.board-area').height() - 70;
		const boardSize = Math.min(boardWidth, boardHeight); // 上下のmarginは固定と仮定
		const stageSize = Math.max(this.config.width, this.config.height);
		if (boardSize > 50 * stageSize) {
			this.blockSize = 50;
		} else {
			this.blockSize = boardSize / stageSize;
		}

		this.board.setBlockSize(this.blockSize);

		this.$stage.find('.board .block').height(this.blockSize);
		this.$stage.find('.board .block').width(this.blockSize);
		this.$stage.find('.board-frame-wrapper').css({
			width: `${50 + this.config.width * this.blockSize}px`,
		});
		this.$stage.find('.board-frame').css({
			height: `${50 + this.config.height * this.blockSize}px`,
			flexBasis: `${50 + this.config.height * this.blockSize}px`,
		});

		const $leftPipe = this.$stage.find('.case-joint-top-pipe');
		const leftMargin = ($leftPipe.parent().width() - $leftPipe.width()) / 2;

		const $boardArea = this.$stage.find('.board-area');
		const $rightPipe = this.$stage.find('.board-joint-top-pipe');
		const rightMargin = ($boardArea.width() - $rightPipe.width()) / 2;

		this.$stage.find('.upper-pipe-area, .downer-pipe-area').css({
			marginLeft: `${leftMargin}px`,
			marginRight: `${rightMargin}px`,
		});
	}

	onRegister(event) {
		const registrationStartTime = Date.now();

		const name = this.$result.find('.name').val();
		if (name.length === 0) {
			return;
		}

		$(event.target).attr('disabled', true);

		api.post(`/stages/${this.config.name}/submissions`, {
			name,
			board: this.board.boardData,
		}).then((data) => {
			const registrationDuration = Date.now() - registrationStartTime;

			if (data.error) {
				if (data.message === 'user name existing') {
					this.$result.find('.register').text('すでに登録されています').addClass('success');
					ga('send', 'event', 'stage', 'register ranking', 'duplicated', registrationDuration);
				} else {
					this.$result.find('.register').text('エラーが発生しました').addClass('error');
					ga('send', 'event', 'stage', 'register ranking', 'errored', registrationDuration);
				}

				return;
			}

			this.$result.find('.register').text('登録しました!!').addClass('success');

			ga('send', 'event', 'stage', 'register ranking', 'succeeded', registrationDuration);
		});
	}
}

module.exports = Stage;
<|endoftext|>


<commit_before>// Include gulp and Our Plugins
var gulp = require('gulp'),
    jshint = require('gulp-rename'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    ngAnnotate = require('gulp-ng-annotate'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    ngHtml2Js = require("gulp-ng-html2js"),
    inject = require("gulp-inject"),
    bowerFiles = require('main-bower-files'),
    debug = require('gulp-debug'),
    sourcemaps = require('gulp-sourcemaps'),
    args = require('yargs').argv,
    plumber = require('gulp-plumber'),
    es = require('event-stream');

var fileAppLocation = 'src/main/webapp/app/';

// Location Files :
var angularAppLocation = [  fileAppLocation.concat('js/**/*.js'), '!'.concat(fileAppLocation).concat('js/all*.js'),
        '!'.concat(fileAppLocation).concat('js/*.min.js'), '!'.concat(fileAppLocation).concat('js/lib/**/*.js'),
        '!'.concat(fileAppLocation).concat('js/**/*.module.js')],
    angularAppModule = [fileAppLocation.concat('js/**/*.module.js')],
    lessLocation = fileAppLocation.concat('less/*.less'),
    htmlLocation = fileAppLocation.concat('html/*.html'),
    indexLocation = 'src/main/webapp/WEB-INF/pages/index.jsp';

var cssDestionation = fileAppLocation.concat('css'),
    jsDestination = fileAppLocation.concat('js');

var env = args.env  || 'prod';

// Lint Task
gulp.task('lint', function() {
    return gulp.src(angularAppLocation)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('js', function() {
    es.merge(
        gulp.src(htmlLocation).pipe(plumber()).pipe(ngHtml2Js({ moduleName: "ps.partial", prefix: "html/" })).pipe(concat("partials.js")),
        gulp.src(angularAppModule),
        gulp.src(angularAppLocation)
    )
    .pipe(sourcemaps.init())
    .pipe(concat('all.js'))
    .pipe(gulp.dest(jsDestination))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(rename('all.min.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(jsDestination));
});

gulp.task('less', function () {
    gulp.src(lessLocation)
        .pipe(less())
        .pipe(minifyCSS({keepBreaks: true}))
        .pipe(gulp.dest(cssDestionation));
});

// Watch Files For Changes
gulp.task('watch', function() {
    //gulp.watch(angularAppLocation, ['lint']);
    gulp.start("js", "less", 'inject');
    gulp.watch([angularAppLocation, htmlLocation], ['js']);
    gulp.watch(lessLocation, ['less']);
});

gulp.task('inject', function() {
    gulp.src(indexLocation)
        .pipe(inject(gulp.src(bowerFiles({read: false, debugging : false, env : env})), { ignorePath : "/bower_components/", addPrefix : "/app/js/lib"}))
        .pipe(gulp.dest("src/main/webapp/WEB-INF/pages/"));

    gulp.src(bowerFiles({checkExistence : true, read: true, debugging : false, env : env}), {base: 'bower_components'})
        .pipe(gulp.dest("src/main/webapp/app/js/lib/"));
});

// Default Task
gulp.task('default', ['less', 'js', 'inject']);<commit_msg>chore(less): merge all files into one css<commit_after>// Include gulp and Our Plugins
var gulp = require('gulp'),
    jshint = require('gulp-rename'),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    ngAnnotate = require('gulp-ng-annotate'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    ngHtml2Js = require("gulp-ng-html2js"),
    inject = require("gulp-inject"),
    bowerFiles = require('main-bower-files'),
    debug = require('gulp-debug'),
    sourcemaps = require('gulp-sourcemaps'),
    args = require('yargs').argv,
    plumber = require('gulp-plumber'),
    es = require('event-stream');

var fileAppLocation = 'src/main/webapp/app/';

// Location Files :
var angularAppLocation = [  fileAppLocation.concat('js/**/*.js'), '!'.concat(fileAppLocation).concat('js/all*.js'),
        '!'.concat(fileAppLocation).concat('js/*.min.js'), '!'.concat(fileAppLocation).concat('js/lib/**/*.js'),
        '!'.concat(fileAppLocation).concat('js/**/*.module.js')],
    angularAppModule = [fileAppLocation.concat('js/**/*.module.js')],
    lessLocation = fileAppLocation.concat('less/*.less'),
    htmlLocation = fileAppLocation.concat('html/*.html'),
    indexLocation = 'src/main/webapp/WEB-INF/pages/index.jsp';

var cssDestionation = fileAppLocation.concat('css'),
    jsDestination = fileAppLocation.concat('js');

var env = args.env  || 'prod';

// Lint Task
gulp.task('lint', function() {
    return gulp.src(angularAppLocation)
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

gulp.task('js', function() {
    es.merge(
        gulp.src(htmlLocation).pipe(plumber()).pipe(ngHtml2Js({ moduleName: "ps.partial", prefix: "html/" })).pipe(concat("partials.js")),
        gulp.src(angularAppModule),
        gulp.src(angularAppLocation)
    )
    .pipe(sourcemaps.init())
    .pipe(concat('all.js'))
    .pipe(gulp.dest(jsDestination))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(rename('all.min.js'))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(jsDestination));
});

gulp.task('less', function () {
    gulp.src(lessLocation)
        .pipe(less())
        .pipe(concat('podcastserver.css'))
        .pipe(minifyCSS({keepBreaks: true}))
        .pipe(gulp.dest(cssDestionation));
});

// Watch Files For Changes
gulp.task('watch', function() {
    //gulp.watch(angularAppLocation, ['lint']);
    gulp.start("js", "less", 'inject');
    gulp.watch([angularAppLocation, htmlLocation], ['js']);
    gulp.watch(lessLocation, ['less']);
});

gulp.task('inject', function() {
    gulp.src(indexLocation)
        .pipe(inject(gulp.src(bowerFiles({read: false, debugging : false, env : env})), { ignorePath : "/bower_components/", addPrefix : "/app/js/lib"}))
        .pipe(gulp.dest("src/main/webapp/WEB-INF/pages/"));

    gulp.src(bowerFiles({checkExistence : true, read: true, debugging : false, env : env}), {base: 'bower_components'})
        .pipe(gulp.dest("src/main/webapp/app/js/lib/"));
});

// Default Task
gulp.task('default', ['less', 'js', 'inject']);<|endoftext|>


<commit_before>
module.exports = stage;

stage.usage = "\nfhc stage <appId> "
            + "\nfhc stage <appId> --live "
            +"\nfhc stage <appId> [number_of_instances] --live"
            + "\nStage is made to Live environment if the '--live' flag is used";

var log = require("./utils/log");
var fhc = require("./fhc");
var fhreq = require("./utils/request");
var common = require("./common");
var util = require('util');
var async = require('async');
var ini = require('./utils/ini');

// main stage entry point
function stage (args, cb) {
  if(args.length > 4 || args.length == 0) return unknown("stage", cb);

  var clean = ini.get('clean');
  var target = ini.get('live') ? 'live' : 'development';
  var numinstances = 1;

  if (args[1] === "live" || args[1] === "develop") target = args[1];
  else if(Number(args[1])) numinstances = Number(args[1]);
  if (args[2]) clean = args[2] === 'clean';
  if (args[3]) clean = args[3] === 'clean';

  doStage(fhc.appId(args[0]), target, clean, numinstances, cb);
};

function unknown (action, cb) {
  cb("Wrong arguments for or unknown action: " + action + "\nUsage:\n" + stage.usage);
};

// do our staging..
function doStage(app, target, clean, numinstances, cb) {
  var type = 'stage';

  log.verbose(target, 'Staging Target');
  if(target === 'live' || target === 'Live') {
    type = 'releasestage';
  }

  // constuct uri and payload
  var uri = "box/srv/1.1/ide/" + fhc.domain + "/app/" + type;
  var payload = {payload:{guid: app, clean: clean, 'numappinstances':numinstances}};
  // finally do our call

  common.doApiCall(fhreq.getFeedHenryUrl(), uri, payload, "Error staging app: ", function(err, data) {
    if (err) return cb(err);
    async.map([data.cacheKey], common.waitFor, function(err, results) {
      if (results && results[0] && results[0][0] && results[0][0].status === 'complete') {
        stage.message = "App staged ok..";
      }
      return cb(err, results);
    });
  });
};

// bash completion
stage.completion = function (opts, cb) {
  common.getAppIds(cb);
};<commit_msg>multiple instances for stage command<commit_after>
module.exports = stage;

stage.usage = "\nfhc stage <appId> "
            + "\nfhc stage <appId> --live "
            +"\nfhc stage <appId> [number_of_instances] --live"
            + "\nStage is made to Live environment if the '--live' flag is used";

var log = require("./utils/log");
var fhc = require("./fhc");
var fhreq = require("./utils/request");
var common = require("./common");
var util = require('util');
var async = require('async');
var ini = require('./utils/ini');

// main stage entry point
function stage (args, cb) {
  if(args.length > 4 || args.length == 0) return unknown("stage", cb);

  var clean = ini.get('clean');
  var target = ini.get('live') ? 'live' : 'development';
  var numinstances = 1;

  if (args[1] === "live" || args[1] === "develop") target = args[1];
  else if(Number(args[1])) numinstances = Number(args[1]);
  if (args[2]) clean = args[2] === 'clean';
  if (args[3]) clean = args[3] === 'clean';

  doStage(fhc.appId(args[0]), target, clean, numinstances, cb);
};

function unknown (action, cb) {
  cb("Wrong arguments for or unknown action: " + action + "\nUsage:\n" + stage.usage);
};

// do our staging..
function doStage(app, target, clean, numinstances, cb) {
  var type = 'stage';

  log.verbose(target, 'Staging Target');
  if(target === 'live' || target === 'Live') {
    type = 'releasestage';
  }

  // constuct uri and payload
  var uri = "box/srv/1.1/ide/" + fhc.domain + "/app/" + type;
  var payload = {payload:{guid: app, clean: clean, 'numappinstances':numinstances}};
  // finally do our call

  common.doApiCall(fhreq.getFeedHenryUrl(), uri, payload, "Error staging app: ", function(err, data) {
    if (err) return cb(err);
    async.map([data.cacheKey], common.waitFor, function(err, results) {
      if (results && results[0] && results[0][0] && results[0][0].status === 'complete') {
        stage.message = "App staged ok..";
      }
      return cb(err, results);
    });
  });
};

// bash completion
stage.completion = function (opts, cb) {
  common.getAppIds(cb);
};<|endoftext|>


<commit_before>'use strict';
var gulp = require('gulp');
var replace = require('gulp-replace');
var cssFilter = require('gulp-filter')('**/*.css');
var useref = require('gulp-useref');
var minifyCSS = require('gulp-minify-css');
var gutil = require('gulp-util');

var del = require('del');
var webpack = require('webpack');
var webpackConfig = require('./webpack.config');
var buildDestination = 'app-dist';

gulp.task('clean', function (callback) {
  del(buildDestination, { force: true }, callback);
});

gulp.task('copy-fonts', ['clean'], function () {
  return gulp.src('app/bower_components/font-awesome/fonts/*')
    .pipe(gulp.dest('app-dist/fonts/'));
});

gulp.task('copy-images', ['clean'], function () {
  return gulp.src('app/images/*')
    .pipe(gulp.dest('app-dist/images/'));
});

gulp.task('build-css-html', ['clean'], function () {
  // read build: statements from html
  // and transform them with other gulp plugins
  var assets = useref.assets();
  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe(cssFilter)
    .pipe(replace('../fonts', 'fonts'))
    .pipe(minifyCSS())
    .pipe(cssFilter.restore())
    .pipe(assets.restore())
    .pipe(useref())
    .pipe(gulp.dest('app-dist'));
});

gulp.task('build-js', ['clean'], function (callback) {
  // modify some webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.plugins = myConfig.plugins.concat(
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin()
  );

  // run webpack
  webpack(myConfig, function (err, stats) {
    if (err) {
      throw new gutil.PluginError("[build-js]", err);
    }

    gutil.log("[build-js]", stats.toString({ colors: true }));
    callback();
  });
});

gulp.task('build', ['clean', 'build-js', 'build-css-html', 'copy-fonts', 'copy-images']);
<commit_msg>dont wipe out app-dist completely, only what is necessary<commit_after>'use strict';
var gulp = require('gulp');
var replace = require('gulp-replace');
var cssFilter = require('gulp-filter')('**/*.css');
var useref = require('gulp-useref');
var minifyCSS = require('gulp-minify-css');
var gutil = require('gulp-util');

var del = require('del');
var webpack = require('webpack');
var webpackConfig = require('./webpack.config');
var buildDestination = 'app-dist';

gulp.task('clean', function (callback) {
  var cleanPattern = [
    buildDestination + '/fonts/**',
    buildDestination + '/images/**',
    buildDestination + '/index.html',
    buildDestination + '/production.css',
    buildDestination + '/production.js'
  ];

  del(cleanPattern, { force: true }, callback);
});

gulp.task('copy-fonts', ['clean'], function () {
  return gulp.src('app/bower_components/font-awesome/fonts/*')
    .pipe(gulp.dest('app-dist/fonts/'));
});

gulp.task('copy-images', ['clean'], function () {
  return gulp.src('app/images/*')
    .pipe(gulp.dest('app-dist/images/'));
});

gulp.task('build-css-html', ['clean'], function () {
  // read build: statements from html
  // and transform them with other gulp plugins
  var assets = useref.assets();
  return gulp.src('app/*.html')
    .pipe(assets)
    .pipe(cssFilter)
    .pipe(replace('../fonts', 'fonts'))
    .pipe(minifyCSS())
    .pipe(cssFilter.restore())
    .pipe(assets.restore())
    .pipe(useref())
    .pipe(gulp.dest('app-dist'));
});

gulp.task('build-js', ['clean'], function (callback) {
  // modify some webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.plugins = myConfig.plugins.concat(
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin()
  );

  // run webpack
  webpack(myConfig, function (err, stats) {
    if (err) {
      throw new gutil.PluginError("[build-js]", err);
    }

    gutil.log("[build-js]", stats.toString({ colors: true }));
    callback();
  });
});

gulp.task('build', ['clean', 'build-js', 'build-css-html', 'copy-fonts', 'copy-images']);
<|endoftext|>


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

  var shell = require('shelljs');
  var path = require('path');
  var nconf = require('nconf');
  var configFile = path.join(process.env.npm_config_quichean_nconf_path,
    'pytools', 'config.json');
  var user = process.env.npm_package_config_user;
  var service = path.join(__dirname, 'service.py');
  // jscs:disable maximumLineLength
  var args = '--logpath ' +
    path.join(process.env.npm_config_quichean_logging_path, user, 'service.log') +
    ' --logfmt "%(asctime)s %(levelname)s %(module)s.%(funcName)s : %(message)s"';
  // jscs:enable maximumLineLength
  var venv;

  nconf.file({file: configFile});
  venv = path.join(nconf.get('virtualenvs:path'), user, 'bin/activate');
  shell.exec('. ' + venv);
  shell.exec('sudo -u ' + user + ' -g ' + user + ' -E python ' + service +
    ' ' + args);
})();
<commit_msg>Pass log format to service from config.<commit_after>(function() {
  'use strict';

  var shell = require('shelljs');
  var path = require('path');
  var nconf = require('nconf');
  var configFile = path.join(process.env.npm_config_quichean_nconf_path,
    'pytools', 'config.json');
  var user = process.env.npm_package_config_user;
  var service = path.join(__dirname, 'service.py');
  var args;
  var venv;

  nconf.file({file: configFile});
  // jscs:disable maximumLineLength
  args = '--logpath ' +
    path.join(process.env.npm_config_quichean_logging_path, user, 'service.log') +
    ' --logfmt "' + nconf.get('python:logging:format') + '"';
  // jscs:enable maximumLineLength
  venv = path.join(nconf.get('virtualenvs:path'), user, 'bin/activate');
  shell.exec('. ' + venv);
  shell.exec('sudo -u ' + user + ' -g ' + user + ' -E python ' + service +
    ' ' + args);
})();
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    clean = require('gulp-clean'),
    argv = require('yargs').argv,
    replace = require('gulp-replace'),
    exec = require('child_process').exec;

gulp.task('release', ['copy']);

gulp.task('copy', ['clean'], function () {
    return gulp.src('./client/build/**/*.*')
        .pipe(gulp.dest('./build/public'));
});

gulp.task('clean', ['compilerClient'], function () {
    return gulp.src('./build/public/*.*', {
            read: false
        })
        .pipe(clean());
});

gulp.task('compilerClient', ['config'], function (cb) {
    process.chdir('./client');
    exec('yarn build', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        process.chdir('../');
        cb();
    });
});

gulp.task('config', ['compilerServer'], function () {
    gulp.src('./client/src/utils/urls.ts')
        .pipe(replace('http://localhost:3000/', 'HITCHHIKER_APP_HOST'))
        .pipe(gulp.dest('./client/src/utils/'));
    gulp.src('./appconfig.json')
        .pipe(replace('localhost:3000', `localhost:8080`))
        .pipe(replace('localhost:81', `localhost:8080`))
        .pipe(replace('DEV', `PROD`))
        .pipe(gulp.dest('./'));
    gulp.src('./client/package.json')
        .pipe(replace('localhost:81', `localhost:8080`))
        .pipe(gulp.dest('./client/'));
    gulp.src('./api/index.ts')
        .pipe(replace('81', `8080`))
        .pipe(gulp.dest('./api/'));
});

gulp.task('compilerServer', [], function (cb) {
    exec('tsc -p . -w false', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb();
    });
});<commit_msg>update gulp file<commit_after>var gulp = require('gulp'),
    clean = require('gulp-clean'),
    argv = require('yargs').argv,
    replace = require('gulp-replace'),
    exec = require('child_process').exec;

gulp.task('release', ['copy']);

gulp.task('copy', ['clean'], function () {
    return gulp.src('./client/build/**/*.*')
        .pipe(gulp.dest('./build/public'));
});

gulp.task('clean', ['compilerClient'], function () {
    return gulp.src('./build/public/*.*', {
            read: false
        })
        .pipe(clean());
});

gulp.task('compilerClient', ['compilerServer'], function (cb) {
    process.chdir('./client');
    exec('yarn build', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        process.chdir('../');
        cb();
    });
});

gulp.task('compilerServer', ['config'], function (cb) {
    exec('tsc -p . -w false', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb();
    });
});

gulp.task('config', [], function () {
    gulp.src('./client/src/utils/urls.ts')
        .pipe(replace('http://localhost:3000/', 'HITCHHIKER_APP_HOST'))
        .pipe(gulp.dest('./client/src/utils/'));
    gulp.src('./appconfig.json')
        .pipe(replace('localhost:3000', `localhost:8080`))
        .pipe(replace('localhost:81', `localhost:8080`))
        .pipe(replace('DEV', `PROD`))
        .pipe(gulp.dest('./'));
    gulp.src('./client/package.json')
        .pipe(replace('localhost:81', `localhost:8080`))
        .pipe(gulp.dest('./client/'));
    gulp.src('./api/index.ts')
        .pipe(replace('81', `8080`))
        .pipe(gulp.dest('./api/'));
});<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');
var fs = require('fs');
var glob = require("glob");
var through2 = require('through2');
var runSequence = require('run-sequence');
var exec = require('child_process').exec;
var uiIndex = require('./lib/findBy/tagname/searchIndex/build-stream');
var codeIndex = require('./lib/findBy/code/searchIndex/build-stream');
var Promise = require("bluebird");
var execAsync = Promise.promisify(exec);
var config = require("config");
var mongo = require('./lib/db/connection');
var DATASET_ROOT = config.get('dataset.root');

gulp.task('index:ui', function () {
    gulp.src(path.join(DATASET_ROOT, 'ui', '*.xml'))
        .pipe(uiIndex())
        .pipe(gulp.dest('indexes/tagname'));
});

gulp.task('solr:indexCode', function (callback) {
    glob(path.join(DATASET_ROOT, 'code', '*.txt'), function (er, files) {
        codeIndex.index(files);
        callback();
    });
});

gulp.task('solr:commit', function () {
    codeIndex.commit();
});

gulp.task('extract:archives', function (done) {
    var untarListings = 'tar xvjf ' + path.join(DATASET_ROOT, 'listing',
            'listing.tar.bz2') + ' -C ' + path.join(DATASET_ROOT, 'listing');
    var untarUI = 'tar xvjf ' + path.join(DATASET_ROOT, 'ui', 'ui-xml.tar.bz2') +
        ' -C ' + path.join(DATASET_ROOT, 'ui');
    var untarCode = 'tar xvjf ' + path.join(DATASET_ROOT, 'code',
            'smali-invoked-methods.tar.bz2') + ' -C ' + path.join(DATASET_ROOT,
            'code');
    console.log("Extracting listing details json files...");
    execAsync(untarListings)
        .then(function () {
            console.log("Extracting UI xml files...");
            return execAsync(untarUI);
        })
        .then(function () {
            console.log("Extracting code text files...");
            return execAsync(untarCode);
        })
        .then(function () {
            console.log("All archives have been extracted.");
            done();
        })
        .error(function (error) {
            console.error(error);
            done(error);
        });
});

gulp.task('start:db', function (callback) {
    try {
        fs.mkdirSync(path.join(DATASET_ROOT, 'db'));
    } catch (error) {
        if (error.code != 'EEXIST') callback(error);
    }
    // start Solr in SolrCloud mode as a daemon
    var solr = 'solr start -cloud -V -h ' + config.get('dbConfig.solr.host') +
        ' -p ' + config.get('dbConfig.solr.port');
    console.log("Starting Solr server in SolrCloud mode. " + solr);
    exec(solr,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
    // start MongoDB
    var mongod = 'mongod --port ' + config.get('dbConfig.mongo.port') +
        ' --config ' + config.get('dbConfig.mongo.config') +
        ' --dbpath ' + path.join(DATASET_ROOT, 'db');
    console.log("Starting MongoDB server: " + mongod);
    exec(mongod,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
});

gulp.task('mongo:insertListing', function (done) {
    gulp.src(path.join(DATASET_ROOT, 'listing', '*.json'))
        .pipe(new through2.obj(function (file, enc, cb) {
            var doc = JSON.parse(file.contents);
            doc['id'] = doc['n'] + '-' + doc['verc'];
            mongo.upsertOne('listings', doc, doc)
                .then(function () {
                    cb();
                })
                .error(function (e) {
                    console.error('Error in insert:listing task: ' + e.message);
                });
        }, function () {
            done();
        }));

});

gulp.task('mongo:indexListing', function (done) {
    mongo.createIndex('listings', {id: 1}, {unique: true})
        .then(function () {
            done();
        })
        .error(function (e) {
            console.error('Error in mongoIndex task: ' + e.message);
        })
});

gulp.task('mongo:close', function () {
    mongo.close();
});

gulp.task('load:db', function (callback) {
    runSequence('mongo:insertListing', 'mongo:indexListing', 'mongo:close', callback)
});

gulp.task('default', function (callback) {
    runSequence('extract:archives', 'load:db', callback);
});<commit_msg>add extract manifest files<commit_after>var gulp = require('gulp');
var path = require('path');
var fs = require('fs');
var glob = require("glob");
var through2 = require('through2');
var runSequence = require('run-sequence');
var exec = require('child_process').exec;
var uiIndex = require('./lib/findBy/tagname/searchIndex/build-stream');
var codeIndex = require('./lib/findBy/code/searchIndex/build-stream');
var Promise = require("bluebird");
var execAsync = Promise.promisify(exec);
var config = require("config");
var mongo = require('./lib/db/connection');
var DATASET_ROOT = config.get('dataset.root');

gulp.task('index:ui', function () {
    gulp.src(path.join(DATASET_ROOT, 'ui', '*.xml'))
        .pipe(uiIndex())
        .pipe(gulp.dest('indexes/tagname'));
});

gulp.task('solr:indexCode', function (callback) {
    glob(path.join(DATASET_ROOT, 'code', '*.txt'), function (er, files) {
        codeIndex.index(files);
        callback();
    });
});

gulp.task('solr:commit', function () {
    codeIndex.commit();
});

gulp.task('extract:archives', function (done) {
    var untarListings = 'tar xvjf ' + path.join(DATASET_ROOT, 'listing',
            'listing.tar.bz2') + ' -C ' + path.join(DATASET_ROOT, 'listing');
    var untarUI = 'tar xvjf ' + path.join(DATASET_ROOT, 'ui', 'ui-xml.tar.bz2') +
        ' -C ' + path.join(DATASET_ROOT, 'ui');
    var untarManifest = 'tar xvjf ' + path.join(DATASET_ROOT, 'manifest',
            'manifest.tar.bz2') + ' -C ' + path.join(DATASET_ROOT,
            'manifest');
    var untarCode = 'tar xvjf ' + path.join(DATASET_ROOT, 'code',
            'smali-invoked-methods.tar.bz2') + ' -C ' + path.join(DATASET_ROOT,
            'code');

    console.log("Extracting listing details json files...");
    execAsync(untarListings)
        .then(function () {
            console.log("Extracting UI xml files...");
            return execAsync(untarUI);
        })
        .then(function () {
            console.log("Extracting Manifest xml files...");
            return execAsync(untarManifest);
        })
        .then(function () {
            console.log("Extracting code text files...");
            return execAsync(untarCode);
        })
        .then(function () {
            console.log("All archives have been extracted.");
            done();
        })
        .error(function (error) {
            console.error(error);
            done(error);
        });
});

gulp.task('start:db', function (callback) {
    try {
        fs.mkdirSync(path.join(DATASET_ROOT, 'db'));
    } catch (error) {
        if (error.code != 'EEXIST') callback(error);
    }
    // start Solr in SolrCloud mode as a daemon
    var solr = 'solr start -cloud -V -h ' + config.get('dbConfig.solr.host') +
        ' -p ' + config.get('dbConfig.solr.port');
    console.log("Starting Solr server in SolrCloud mode. " + solr);
    exec(solr,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
    // start MongoDB
    var mongod = 'mongod --port ' + config.get('dbConfig.mongo.port') +
        ' --config ' + config.get('dbConfig.mongo.config') +
        ' --dbpath ' + path.join(DATASET_ROOT, 'db');
    console.log("Starting MongoDB server: " + mongod);
    exec(mongod,
        function (error, stdout, stderr) {
            console.log(stdout);
            console.log(stderr);
            callback(stderr);
        });
});

gulp.task('mongo:insertListing', function (done) {
    gulp.src(path.join(DATASET_ROOT, 'listing', '*.json'))
        .pipe(new through2.obj(function (file, enc, cb) {
            var doc = JSON.parse(file.contents);
            doc['id'] = doc['n'] + '-' + doc['verc'];
            mongo.upsertOne('listings', doc, doc)
                .then(function () {
                    cb();
                })
                .error(function (e) {
                    console.error('Error in insert:listing task: ' + e.message);
                });
        }, function () {
            done();
        }));

});

gulp.task('mongo:indexListing', function (done) {
    mongo.createIndex('listings', {id: 1}, {unique: true})
        .then(function () {
            done();
        })
        .error(function (e) {
            console.error('Error in mongoIndex task: ' + e.message);
        })
});

gulp.task('mongo:close', function () {
    mongo.close();
});

gulp.task('load:db', function (callback) {
    runSequence('mongo:insertListing', 'mongo:indexListing', 'mongo:close', callback)
});

gulp.task('default', function (callback) {
    runSequence('extract:archives', 'load:db', callback);
});<|endoftext|>


<commit_before>var app = angular.module('app', ['ui.bootstrap', 'ngRoute'])

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/dashboard', {
        templateUrl: 'partials/dashboard.html',
        controller: 'Market'
      }).
      when('/orders/sales', {
        templateUrl: 'partials/orders.html',
        controller: 'Orders'
      }).
      when('/orders/purchases', {
        templateUrl: 'partials/orders.html',
        controller: 'Orders'
      }).
      when('/contracts', {
        templateUrl: 'partials/contracts.html',
        controller: 'Contracts'
      }).
      when('/settings', {
        templateUrl: 'partials/settings.html',
        controller: 'Settings'
      }).
      when('/search', {
        templateUrl: 'partials/search.html',
        controller: 'Search'
      }).
      when('/arbiter', {
        templateUrl: 'partials/arbiter.html',
        controller: 'Arbiter'
      }).
      when('/messages', {
        templateUrl: 'partials/messages.html',
        controller: 'Messages'
      }).
      when('/user/:userId/products', {
        templateUrl: 'partials/user.html',
        controller: 'User'
      }).
      when('/user/:userId/services', {
        templateUrl: 'partials/user.html',
        controller: 'User'
      }).
      when('/user/:userId', {
        templateUrl: 'partials/user.html',
        controller: 'User'
      }).
      when('/settings/:section', {
        templateUrl: 'partials/settings.html',
        controller: 'Settings'
      }).
      otherwise({
        redirectTo: '/dashboard'
      });
}]);

/**
 * This directive is used for converting identicon tags
 * to actual identicons in the HTML
 */
angular.module('app').directive('identicon', function() {
    return {
        restrict: 'E', // element
        scope: {
            hash: '=',
            iconSize: '='
        },
        link: function(scope, element, attrs) {
            var iconSize = scope.iconSize || 32;

            // Create the identicon
            function createFromHex(dataHex) {
                    var data = new Identicon(dataHex, iconSize).toString();
                    element.html('');
                }
                // Watch for hash changes
            scope.$watch('hash', function() {
                if (scope.hash) {
                    var tohash = scope.hash.substring(32, 64)
                    createFromHex(tohash);
                }
            })
        }
    }
});

app.directive('numberOnlyInput', function () {
    return {
        restrict: 'EA',
        template: '<input name="{{inputName}}" ng-model="inputValue" placeholder="" class="form-control" />',
        scope: {
            inputValue: '=',
            inputName: '=',
            inputPlaceholder: '='
        },
        link: function (scope) {
            scope.$watch('inputValue', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.inputValue = oldValue;
                }
            });
        }
    };
});

/**
 * This configuration item allows us to safely use the bitcoin:
 * URI for applications that register that URI
 */
angular.module('app')
    .config([
        '$compileProvider',
        function($compileProvider) {
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|bitcoin):/);
            // Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
        }
    ]);

app.directive("validateOnBlur", [function() {
    var ddo = {
        restrict: "A",
        require: "ngModel",
        scope: {},
        link: function(scope, element, attrs, modelCtrl) {
            element.on('blur', function () {
                modelCtrl.$showValidationMessage = modelCtrl.$dirty;
                scope.$apply();
            });
        }
    };
    return ddo;
}]);
<commit_msg>JS style fixes on app.js<commit_after>var app = angular.module('app', ['ui.bootstrap', 'ngRoute']);

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/dashboard', {
        templateUrl: 'partials/dashboard.html',
        controller: 'Market'
      }).
      when('/orders/sales', {
        templateUrl: 'partials/orders.html',
        controller: 'Orders'
      }).
      when('/orders/purchases', {
        templateUrl: 'partials/orders.html',
        controller: 'Orders'
      }).
      when('/contracts', {
        templateUrl: 'partials/contracts.html',
        controller: 'Contracts'
      }).
      when('/settings', {
        templateUrl: 'partials/settings.html',
        controller: 'Settings'
      }).
      when('/search', {
        templateUrl: 'partials/search.html',
        controller: 'Search'
      }).
      when('/arbiter', {
        templateUrl: 'partials/arbiter.html',
        controller: 'Arbiter'
      }).
      when('/messages', {
        templateUrl: 'partials/messages.html',
        controller: 'Messages'
      }).
      when('/user/:userId/products', {
        templateUrl: 'partials/user.html',
        controller: 'User'
      }).
      when('/user/:userId/services', {
        templateUrl: 'partials/user.html',
        controller: 'User'
      }).
      when('/user/:userId', {
        templateUrl: 'partials/user.html',
        controller: 'User'
      }).
      when('/settings/:section', {
        templateUrl: 'partials/settings.html',
        controller: 'Settings'
      }).
      otherwise({
        redirectTo: '/dashboard'
      });
}]);

/**
 * This directive is used for converting identicon tags
 * to actual identicons in the HTML
 */
angular.module('app').directive('identicon', function() {
    return {
        restrict: 'E', // element
        scope: {
            hash: '=',
            iconSize: '='
        },
        link: function(scope, element, attrs) {
            var iconSize = scope.iconSize || 32;

            // Create the identicon
            function createFromHex(dataHex) {
                    var data = new Identicon(dataHex, iconSize).toString();
                    element.html('');
                }
                // Watch for hash changes
            scope.$watch('hash', function() {
                if (scope.hash) {
                    var tohash = scope.hash.substring(32, 64);
                    createFromHex(tohash);
                }
            });
        }
    };
});

app.directive('numberOnlyInput', function () {
    return {
        restrict: 'EA',
        template: '<input name="{{inputName}}" ng-model="inputValue" placeholder="" class="form-control" />',
        scope: {
            inputValue: '=',
            inputName: '=',
            inputPlaceholder: '='
        },
        link: function (scope) {
            scope.$watch('inputValue', function(newValue,oldValue) {
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.inputValue = oldValue;
                }
            });
        }
    };
});

/**
 * This configuration item allows us to safely use the bitcoin:
 * URI for applications that register that URI
 */
angular.module('app')
    .config([
        '$compileProvider',
        function($compileProvider) {
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|bitcoin):/);
            // Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
        }
    ]);

app.directive("validateOnBlur", [function() {
    var ddo = {
        restrict: "A",
        require: "ngModel",
        scope: {},
        link: function(scope, element, attrs, modelCtrl) {
            element.on('blur', function () {
                modelCtrl.$showValidationMessage = modelCtrl.$dirty;
                scope.$apply();
            });
        }
    };
    return ddo;
}]);
<|endoftext|>


<commit_before>var gulp          = require("gulp"),

    del           = require("del"),
    rename        = require("gulp-rename"),

    Notification  = require("node-notifier"),
    util          = require("gulp-util"),

    browserify    = require("browserify"),
    watchify      = require("watchify"),
    source        = require("vinyl-source-stream"),

    reactify      = require("reactify"),
    uglify        = require("gulp-uglify"),

    browserSync   = require("browser-sync"),

    less          = require("gulp-less"),

    reload        = browserSync.reload;

var config = {
    lessMainFolder: "src/less",
    lessEntry:      "main.less",
    cssDestFolder:  "dist/css",
    cssFinalName:   "main.css",

    jsMainFolder:   "src/js",
    jsEntry:        "main.jsx",
    jsDestFolder:   "dist/js",
    jsFinalName:    "main.js",
};

function standardHandler(err){
  // Notification
  Notification.notify({ message: "Error: " + err.message });
  // Log to console
  util.log(util.colors.red("Error"), err.message);
}

function browserifyHandler(err){
  standardHandler(err);
  this.end();
}

//delete dist folder by calling: gulp clean
gulp.task("clean", function(cb) {
  del(["dist"], cb);
});

gulp.task("browserSync", function() {
  browserSync({
    server: {
      baseDir: "./"
    }
  });
});

/////////////////////// LESS -> CSS
gulp.task("less", function () {
  var link = gulp.src("./" + config.lessMainFolder + "/" + config.lessEntry)
              .on("error", standardHandler)
              .pipe(less({ paths: [ config.lessMainFolder ] }))
              .on("error", standardHandler)
              .pipe(rename(config.cssFinalName))
              .on("error", standardHandler)
              .pipe(gulp.dest("./" + config.cssDestFolder));

  if (process.env.NODE_ENV === "development") {
    link = link.pipe(reload({ stream: true }));
  }

  return link;
});

gulp.task("watch-less", function () {
  gulp.watch("./" + config.lessMainFolder + "/**/*.less", ["less"]);
});
///////////////////////////////////////////////////////////////////////////////

/////////////////////// jsx -> js
gulp.task("js", function () {
  var link;

  function bundle() {
    link.bundle()
      .on("error", browserifyHandler)
      .pipe(source(config.jsEntry))
      .on("error", browserifyHandler)
      .pipe(rename(config.jsFinalName))
      .on("error", browserifyHandler)
      .pipe(gulp.dest(config.jsDestFolder))
      .on("error", browserifyHandler)
      .pipe(reload({ stream: true }));
  }

  link = browserify({
    cache: {},
    packageCache: {},
    fullPaths: true
  }).on("error", browserifyHandler);

  if (process.env.NODE_ENV === "development") {
    link = watchify(link);
    link.on("update", function () {
      console.log("update");
      bundle();
    });
  }

  link.add("./" + config.jsMainFolder + "/" + config.jsEntry);
  link.transform(reactify);
  bundle();
});
///////////////////////////////////////////////////////////////////////////////

gulp.task("dev", ["clean"], function () {
  process.env.NODE_ENV = "development";
  gulp.start([ "watch-less", "js", "browserSync" ]);
});

gulp.task("prod", ["clean"], function () {
  process.env.NODE_ENV = "production";
  gulp.start([ "less", "js" ]);
});

gulp.task("default", function() {
  console.log("Run 'gulp dev or gulp prod'");
});
<commit_msg>fixed gulp which doesn't compile less at the dev mode<commit_after>var gulp          = require("gulp"),

    del           = require("del"),
    rename        = require("gulp-rename"),

    Notification  = require("node-notifier"),
    util          = require("gulp-util"),

    browserify    = require("browserify"),
    watchify      = require("watchify"),
    source        = require("vinyl-source-stream"),

    reactify      = require("reactify"),
    uglify        = require("gulp-uglify"),

    browserSync   = require("browser-sync"),

    less          = require("gulp-less"),

    reload        = browserSync.reload;

var config = {
    lessMainFolder: "src/less",
    lessEntry:      "main.less",
    cssDestFolder:  "dist/css",
    cssFinalName:   "main.css",

    jsMainFolder:   "src/js",
    jsEntry:        "main.jsx",
    jsDestFolder:   "dist/js",
    jsFinalName:    "main.js",
};

function standardHandler(err){
  // Notification
  Notification.notify({ message: "Error: " + err.message });
  // Log to console
  util.log(util.colors.red("Error"), err.message);
}

function browserifyHandler(err){
  standardHandler(err);
  this.end();
}

//delete dist folder by calling: gulp clean
gulp.task("clean", function(cb) {
  del(["dist"], cb);
});

gulp.task("browserSync", function() {
  browserSync({
    server: {
      baseDir: "./"
    }
  });
});

/////////////////////// LESS -> CSS
gulp.task("less", function () {
  var link = gulp.src("./" + config.lessMainFolder + "/" + config.lessEntry)
              .on("error", standardHandler)
              .pipe(less({ paths: [ config.lessMainFolder ] }))
              .on("error", standardHandler)
              .pipe(rename(config.cssFinalName))
              .on("error", standardHandler)
              .pipe(gulp.dest("./" + config.cssDestFolder));

  if (process.env.NODE_ENV === "development") {
    link = link.pipe(reload({ stream: true }));
  }

  return link;
});

gulp.task("watch-less", ["less"], function () {
  gulp.watch("./" + config.lessMainFolder + "/**/*.less", ["less"]);
});
///////////////////////////////////////////////////////////////////////////////

/////////////////////// jsx -> js
gulp.task("js", function () {
  var link;

  function bundle() {
    link.bundle()
      .on("error", browserifyHandler)
      .pipe(source(config.jsEntry))
      .on("error", browserifyHandler)
      .pipe(rename(config.jsFinalName))
      .on("error", browserifyHandler)
      .pipe(gulp.dest(config.jsDestFolder))
      .on("error", browserifyHandler)
      .pipe(reload({ stream: true }));
  }

  link = browserify({
    cache: {},
    packageCache: {},
    fullPaths: true
  }).on("error", browserifyHandler);

  if (process.env.NODE_ENV === "development") {
    link = watchify(link);
    link.on("update", function () {
      console.log("update");
      bundle();
    });
  }

  link.add("./" + config.jsMainFolder + "/" + config.jsEntry);
  link.transform(reactify);
  bundle();
});
///////////////////////////////////////////////////////////////////////////////

gulp.task("dev", ["clean"], function () {
  process.env.NODE_ENV = "development";
  gulp.start([ "watch-less", "js", "browserSync" ]);
});

gulp.task("prod", ["clean"], function () {
  process.env.NODE_ENV = "production";
  gulp.start([ "less", "js" ]);
});

gulp.task("default", function() {
  console.log("Run 'gulp dev or gulp prod'");
});
<|endoftext|>