<commit_before>#!/usr/bin/env node

var path         = require('path')

var program      = require('commander')
var gulp         = require('gulp')
var sass         = require('gulp-sass')
var less         = require('gulp-less')
var babel        = require('gulp-babel')
var rename       = require("gulp-rename")
var gutil        = require('gulp-util')
var plumber      = require('gulp-plumber')
var gap          = require('gulp-append-prepend')
var pug          = require('gulp-pug')
var sourcemaps   = require('gulp-sourcemaps')
var bro          = require("gulp-bro")
var markdown     = require('gulp-markdown')
var uglify       = require('gulp-uglify')
var autoprefixer = require('gulp-autoprefixer')
var cleanCSS     = require('gulp-clean-css')
var imagemin     = require('gulp-imagemin')

var CWD        = process.cwd()
var ROOT       = __dirname

program
    .option('-p, --babelpolyfill', 'use babel-polyfill. Default: false')
    .option('-b, --build', 'build only')
    .option('-w, --browserify', 'browserify modules')
    .option('-s, --sourcemap', 'write sourcemap')
    .option('-m, --minify', 'minify')
    .option('-x, --exclude <string>', 'exclude glob pattern. E.g. "**/*.min.js:**/*.min.css"')
    .parse(process.argv);

// console.log(program.exclude);

var excludeArr = program.exclude ? program.exclude.split(':').map(v => "!" + v) : [];

var build = {
    sass: function () {
        console.log('begin: \t sass built');

        var srcArr = [path.resolve(CWD, '**/*.scss'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(program.sourcemap ? sourcemaps.init() : gutil.noop())
            .pipe(sass().on('error', sass.logError))
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            }))
            .pipe(program.minify ? cleanCSS({ compatibility: 'ie8' }) : gutil.noop())
            .pipe(program.sourcemap ? sourcemaps.write('./maps') : gutil.noop())
            .on('end', function () {
                console.log('done: \t sass built');
            })
            .pipe(gulp.dest(dist));
    },
    less: function () {
        console.log('begin: \t less built');
        var srcArr = [path.resolve(CWD, '**/*.less'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(program.sourcemap ? sourcemaps.init() : gutil.noop())
            .pipe(less().on('error', sass.logError))
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            }))
            .pipe(program.minify ? cleanCSS({ compatibility: 'ie8' }) : gutil.noop())
            .pipe(program.sourcemap ? sourcemaps.write('./maps') : gutil.noop())
            .on('end', function () {
                console.log('done: \t less built');
            })
            .pipe(gulp.dest(dist));
    },
    es6: function () {
        console.log('begin: \t es6 built');
        var srcArr = [path.resolve(CWD, '**/*.es6'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(plumber())
            .pipe(babel({
                // presets: ["babel-preset-es2015", "babel-preset-es2016", "babel-preset-es2017"].map(require.resolve)
                presets: [
                    [require.resolve('babel-preset-env'), {
                        "targets": {
                            "browsers": ["last 2 versions", "safari >= 7"]
                        }
                    }], require.resolve("babel-preset-stage-0"), require.resolve("babel-preset-stage-1"), require.resolve("babel-preset-stage-2"), require.resolve("babel-preset-stage-3")
                ]
            }))
            // .pipe(program.browserify ? bro() : gutil.noop())
            .pipe(program.babelpolyfill ? gap.prependFile(path.resolve(ROOT, 'lib/polyfill.min.js')) : gutil.noop())
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t es6 built');
            })
            .pipe(rename(function (path) {
                path.extname = ".js"
            }))
            .pipe(program.minify ? uglify() : gutil.noop())
            .pipe(gulp.dest(dist))
            .pipe(program.browserify ? bro() : gutil.noop())
            .pipe(program.browserify ? gulp.dest(dist) : gutil.noop())
    },
    pug: function () {
        console.log('begin: \t pug built');
        var srcArr = [path.resolve(CWD, '**/*.pug'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(pug({
                pretty: true
            }))
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t pug built');
            })
            .pipe(rename(function (path) {
                path.extname = ".html"
            }))
            .pipe(gulp.dest(dist));
    },
    markdown: function(){
        console.log('begin: \t markdown built');
        var srcArr = [path.resolve(CWD, '**/*.md'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(markdown())
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t markdown built');
            })
            .pipe(rename(function (path) {
                path.extname = ".html"
            }))
            .pipe(gulp.dest(dist));
    },
    imageMin: function () {
        console.log('begin: \t markdown built');
        var srcArr = [path.resolve(CWD, '**/*.png'), path.resolve(CWD, '**/*.jpg'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t markdown built');
            })
            .pipe(imagemin())
            .pipe(gulp.dest(dist));
    }
};

gulp.task('sass:watch', function () {
    gulp.watch(['**/*.scss', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.sass);
});
gulp.task('less:watch', function () {
    gulp.watch(['**/*.less', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.less);
});
gulp.task('es6:watch', function () {
    gulp.watch(['**/*.es6', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.es6);
});
gulp.task('pug:watch', function () {
    gulp.watch(['**/*.pug', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.pug);
});
gulp.task('markdown:watch', function () {
    gulp.watch(['**/*.md', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.markdown);
});

if (program.build) {
    build.sass();
    build.less();
    build.es6();
    build.pug();
    build.markdown();
    build.imageMin();
} else {
    gulp.start(["sass:watch", 'less:watch', 'es6:watch', 'pug:watch', 'markdown:watch'], function () {
        console.log('laziness is ready...');
    });
}
<commit_msg>add optimization level to image min<commit_after>#!/usr/bin/env node

var path         = require('path')

var program      = require('commander')
var gulp         = require('gulp')
var sass         = require('gulp-sass')
var less         = require('gulp-less')
var babel        = require('gulp-babel')
var rename       = require("gulp-rename")
var gutil        = require('gulp-util')
var plumber      = require('gulp-plumber')
var gap          = require('gulp-append-prepend')
var pug          = require('gulp-pug')
var sourcemaps   = require('gulp-sourcemaps')
var bro          = require("gulp-bro")
var markdown     = require('gulp-markdown')
var uglify       = require('gulp-uglify')
var autoprefixer = require('gulp-autoprefixer')
var cleanCSS     = require('gulp-clean-css')
var imagemin     = require('gulp-imagemin')

var CWD        = process.cwd()
var ROOT       = __dirname

program
    .option('-p, --babelpolyfill', 'use babel-polyfill. Default: false')
    .option('-b, --build', 'build only')
    .option('-w, --browserify', 'browserify modules')
    .option('-s, --sourcemap', 'write sourcemap')
    .option('-m, --minify', 'minify')
    .option('-x, --exclude <string>', 'exclude glob pattern. E.g. "**/*.min.js:**/*.min.css"')
    .parse(process.argv);

// console.log(program.exclude);

var excludeArr = program.exclude ? program.exclude.split(':').map(v => "!" + v) : [];

var build = {
    sass: function () {
        console.log('begin: \t sass built');

        var srcArr = [path.resolve(CWD, '**/*.scss'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(program.sourcemap ? sourcemaps.init() : gutil.noop())
            .pipe(sass().on('error', sass.logError))
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            }))
            .pipe(program.minify ? cleanCSS({ compatibility: 'ie8' }) : gutil.noop())
            .pipe(program.sourcemap ? sourcemaps.write('./maps') : gutil.noop())
            .on('end', function () {
                console.log('done: \t sass built');
            })
            .pipe(gulp.dest(dist));
    },
    less: function () {
        console.log('begin: \t less built');
        var srcArr = [path.resolve(CWD, '**/*.less'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(program.sourcemap ? sourcemaps.init() : gutil.noop())
            .pipe(less().on('error', sass.logError))
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            }))
            .pipe(program.minify ? cleanCSS({ compatibility: 'ie8' }) : gutil.noop())
            .pipe(program.sourcemap ? sourcemaps.write('./maps') : gutil.noop())
            .on('end', function () {
                console.log('done: \t less built');
            })
            .pipe(gulp.dest(dist));
    },
    es6: function () {
        console.log('begin: \t es6 built');
        var srcArr = [path.resolve(CWD, '**/*.es6'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(plumber())
            .pipe(babel({
                // presets: ["babel-preset-es2015", "babel-preset-es2016", "babel-preset-es2017"].map(require.resolve)
                presets: [
                    [require.resolve('babel-preset-env'), {
                        "targets": {
                            "browsers": ["last 2 versions", "safari >= 7"]
                        }
                    }], require.resolve("babel-preset-stage-0"), require.resolve("babel-preset-stage-1"), require.resolve("babel-preset-stage-2"), require.resolve("babel-preset-stage-3")
                ]
            }))
            // .pipe(program.browserify ? bro() : gutil.noop())
            .pipe(program.babelpolyfill ? gap.prependFile(path.resolve(ROOT, 'lib/polyfill.min.js')) : gutil.noop())
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t es6 built');
            })
            .pipe(rename(function (path) {
                path.extname = ".js"
            }))
            .pipe(program.minify ? uglify() : gutil.noop())
            .pipe(gulp.dest(dist))
            .pipe(program.browserify ? bro() : gutil.noop())
            .pipe(program.browserify ? gulp.dest(dist) : gutil.noop())
    },
    pug: function () {
        console.log('begin: \t pug built');
        var srcArr = [path.resolve(CWD, '**/*.pug'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(pug({
                pretty: true
            }))
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t pug built');
            })
            .pipe(rename(function (path) {
                path.extname = ".html"
            }))
            .pipe(gulp.dest(dist));
    },
    markdown: function(){
        console.log('begin: \t markdown built');
        var srcArr = [path.resolve(CWD, '**/*.md'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .pipe(markdown())
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t markdown built');
            })
            .pipe(rename(function (path) {
                path.extname = ".html"
            }))
            .pipe(gulp.dest(dist));
    },
    imageMin: function () {
        console.log('begin: \t markdown built');
        var srcArr = [path.resolve(CWD, '**/*.png'), path.resolve(CWD, '**/*.jpg'), '!**/node_modules/**/*'].concat(excludeArr);
        var dist   = path.resolve(CWD, './');
        return gulp.src(srcArr)
            .on('error', function (e) {
                gutil.log(e);
            })
            .on('end', function () {
                console.log('done: \t markdown built');
            })
            .pipe(imagemin([
                imagemin.gifsicle({ interlaced: true }),
                imagemin.jpegtran({ progressive: true }),
                imagemin.optipng({ optimizationLevel: 5 }),
            ]))
            .pipe(gulp.dest(dist));
    }
};

gulp.task('sass:watch', function () {
    gulp.watch(['**/*.scss', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.sass);
});
gulp.task('less:watch', function () {
    gulp.watch(['**/*.less', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.less);
});
gulp.task('es6:watch', function () {
    gulp.watch(['**/*.es6', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.es6);
});
gulp.task('pug:watch', function () {
    gulp.watch(['**/*.pug', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.pug);
});
gulp.task('markdown:watch', function () {
    gulp.watch(['**/*.md', '!**/node_modules/**/*'], {
        cwd: CWD
    }, build.markdown);
});

if (program.build) {
    build.sass();
    build.less();
    build.es6();
    build.pug();
    build.markdown();
    build.imageMin();
} else {
    gulp.start(["sass:watch", 'less:watch', 'es6:watch', 'pug:watch', 'markdown:watch'], function () {
        console.log('laziness is ready...');
    });
}
<|endoftext|>


<commit_before>/*global require*/
'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var when = require('when');
var http = require('http');
var fs = require('fs-extra');
var url = require('url');
var GitHubApi = require('github');
var DecompressZip = require('decompress-zip');
var tar = require('tar-fs');
var zlib = require('zlib');

/*jshint camelcase: false*/
var proxy = process.env.http_proxy || process.env.HTTP_PROXY || process.env.https_proxy || process.env.HTTPS_PROXY || null;
var githubOptions = {
  version: '3.0.0'
};

if (proxy) {
  githubOptions.proxy = {};
  githubOptions.proxy.host = url.parse(proxy).hostname;
  githubOptions.proxy.port = url.parse(proxy).port;
}

var github = new GitHubApi(githubOptions);

var suggestAppNameFromPath = function (_) {
  var basePath = path.basename(process.env.PWD);
  return _.slugify(basePath);
};

var NodeWebkitGenerator = module.exports = function NodeWebkitGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({
      skipInstall: options['skip-install']
    });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
  this.nodeWebkitVersion = 'v0.9.2';
  this.nodeWebkitBaseUrl = 'http://dl.node-webkit.org/' + this.nodeWebkitVersion + '/node-webkit-' + this.nodeWebkitVersion + '-';
  console.log(this.yeoman);
};

util.inherits(NodeWebkitGenerator, yeoman.generators.Base);

NodeWebkitGenerator.prototype.askForAppName = function askForAppName() {
  var done = this.async();
  var basePath = path.basename(process.env.PWD);
  var appName = this._.camelize(basePath);

  var prompts = [
    {
      name: 'appName',
      message: 'What do you want to call your app? Allowed characters ^[a-zA-Z0-9]+$',
      default: appName,
      validate: function (answer) {
        if (!/^[a-zA-Z0-9]+$/.test(answer)) {
          return 'The application name should only consist of the following characters a-z, A-Z and 0-9.';
        }
        return true;
      }
    }
  ];

  this.prompt(prompts, function (props) {
    this.appName = props.appName;
    done();
  }.bind(this));

};

NodeWebkitGenerator.prototype.askForDescription = function askForDescription() {
  var done = this.async();
  var prompts = [
    {
      name: 'appDescription',
      message: 'A little description for your app?'
    }
  ];

  this.prompt(prompts, function (props) {
    this.appDescription = props.appDescription;
    done();
  }.bind(this));

};

NodeWebkitGenerator.prototype.askForGithubName = function askForGithubName() {
  var done = this.async();
  var prompts = [
    {
      name: 'githubUser',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someuser'
    }
  ];

  this.prompt(prompts, function (props) {
    this.githubUser = props.githubUser;
    done();
  }.bind(this));
};

NodeWebkitGenerator.prototype.askForInstallNodeWebkit = function askForInstallNodeWebkit() {
  var done = this.async();
  var prompts = [
    {
      type: 'confirm',
      name: 'downloadNodeWebkit',
      message: 'Do you want to download latest node-webkit?',
      default: true
    },
    {
      type: 'checkbox',
      name: 'platforms',
      message: 'Which platform do you wanna support?',
      choices: [
        {
          name: 'MacOS',
          checked: true
        },
        {
          name: 'Linux 64',
          checked: true
        },
        {
          name: 'Windows',
          checked: true
        }
      ],
      when: function (answers) {
        return answers.downloadNodeWebkit;
      },
      validate: function (answer) {
        if (answer.length < 1) {
          return 'You must choose at least one platform.';
        }
        return true;
      }
    }
  ];

  this.prompt(prompts, function (props) {
    this.platforms = props.platforms;
    this.downloadNodeWebkit = props.downloadNodeWebkit;
    this.MacOS = false;
    this.Linux64 = false;
    this.Windows = false;
    this.github = false;
    if (props.downloadNodeWebkit) {
      props.platforms.forEach(function (platform) {
        switch (platform) {
        case 'MacOS':
          this.MacOS = true;
          break;
        case 'Linux 64':
          this.Linux64 = true;
          break;
        case 'Windows':
          this.Windows = true;
          break;
        }
      }.bind(this));
    }
    done();
  }.bind(this));
};

NodeWebkitGenerator.prototype.getGithubUserInfo = function getGithubUserInfo() {
  var done = this.async();
  var _this = this;
  var responseClbk = function (err, responseText) {
    if (err) {
      _this.log.info('Error while fetching github user information.', err);
      _this.log.skip('Skip fetching github user information.');
      done();
    } else {
      var responseObject = JSON.parse(JSON.stringify(responseText));
      _this.log.ok('Github informations successfully retrieved.');
      _this.github = true;
      _this.realname = responseObject.name;
      _this.githubUrl = responseObject.html_url;
      done();
    }
  };

  if (this.githubUser !== 'someuser') {
    this.log.info('Get GitHub informations');
    github.user.getFrom({
      user: this.githubUser
    }, responseClbk);
  } else {
    done();
  }
};

NodeWebkitGenerator.prototype.createFolder = function createFolder() {
  this.mkdir('app');
  this.mkdir('app/img');
  this.mkdir('resources/node-webkit');
  if (this.MacOS) {
    this.mkdir('resources/node-webkit/MacOS');
  }
  if (this.Linux64) {
    this.mkdir('resources/node-webkit/Linux64');
  }
  if (this.Windows) {
    this.mkdir('resources/node-webkit/Windows');
  }
  this.mkdir('tmp');
};

NodeWebkitGenerator.prototype.getNodeWebkit = function getNodeWebkit() {
  var done = this.async();

  var successClbk = function () {
    done();
  };
  var failureClbk = function (error) {
    throw error;
  };
  if (this.downloadNodeWebkit) {
    when.all(this._getNodeWebkit()).then(successClbk, failureClbk);
  } else {
    when.all(this._createFolder()).then(successClbk, failureClbk);
  }
};

NodeWebkitGenerator.prototype._createFolder = function _createFolder() {
  var promises = [];
  var basePath = 'resources/node-webkit/';
  var platforms = ['MacOS', 'Linux64', 'Windows'];
  platforms.forEach(function (platform) {
    var defer = when.defer();
    promises.push(defer.promise);
    fs.mkdirs(basePath + '/' + platform, function (err) {
      if (err) {
        defer.reject(err);
      } else {
        defer.resolve();
      }
    });
  });
  return promises;
};

NodeWebkitGenerator.prototype._getNodeWebkit = function _getNodeWebkit() {
  var promises = [];
  if (this.MacOS) {
    promises.push(this._requestNodeWebkit('osx-ia32', '.zip', 'MacOS'));
  }
  if (this.Linux64) {
    promises.push(this._requestNodeWebkit('linux-x64', '.tar.gz', 'Linux64'));
  }
  if (this.Windows) {
    promises.push(this._requestNodeWebkit('win-ia32', '.zip', 'Windows'));
  }
  return promises;
};

NodeWebkitGenerator.prototype._requestNodeWebkit = function _requestNodeWebkit(versionString, extension, platform) {
  var defer = when.defer();
  var _this = this;
  if (!fs.existsSync('tmp/' + platform + extension)) {
    if (fs.existsSync('tmp/' + platform + extension + '.part')) {
      fs.unlinkSync('tmp/' + platform + extension + '.part');
    }
    this.log.info('Downloading node-webkit for ' + platform);
    http.get(this.nodeWebkitBaseUrl + versionString + extension, function (res) {
      if (200 === res.statusCode) {
        res.on('data', function (chunk) {
          fs.appendFileSync('tmp/' + platform + extension + '.part', chunk);
        }).on('end', function () {
          fs.renameSync('tmp/' + platform + extension + '.part', 'tmp/' + platform + extension);
          _this.log.ok('Node-webkit for ' + platform + ' downloaded');
          defer.resolve();
        }).on('error', function (error) {
          _this.log.conflict('Error while downloading node-webkit for ' + platform, error);
          defer.reject(error);
        });
      } else {
        _this.log.conflict('Wrong content type for %s', platform);
        defer.reject('Wrong content type for ' + platform);
      }
    }).on('error', function (error) {
      _this.log.conflict('Error while downloading node-webkit for ' + platform, error);
      defer.reject(error);
    });
  } else {
    this.log.ok('Node-webkit for ' + platform + ' already downloaded');
    defer.resolve();
  }
  return defer.promise;
};

NodeWebkitGenerator.prototype.unzipNodeWebkit = function unzipNodeWebkit() {
  var done = this.async();
  var successClbk = function () {
    done();
  };
  var failureClbk = function (error) {
    throw error;
  };
  when.all(this._unzipNodeWebkit()).then(successClbk, failureClbk);
};

NodeWebkitGenerator.prototype._unzipNodeWebkit = function _unzipNodeWebkit() {
  var promises = [];

  if (this.MacOS) {
    promises.push(this._extract('MacOS', '.zip'));
  }
  if (this.Linux64) {
    promises.push(this._extract('Linux64', '.tar.gz'));
  }
  if (this.Windows) {
    promises.push(this._extract('Windows', '.zip'));
  }
  return promises;
};

NodeWebkitGenerator.prototype._extract = function _extract(platform, extension) {
  var _this = this;
  var defer = when.defer();
  if ('.zip' === extension) {
    if (fs.existsSync('tmp/' + platform + extension)) {
      this.log.info('Unzip %s files.', platform);
      var unzipper = new DecompressZip('tmp/' + platform + extension);

      unzipper.on('error', function (error) {
        _this.log.conflict('Error while unzipping "tmp/' + platform + extension + '"', error);
        defer.reject(error);
      });

      unzipper.on('extract', function () {
        _this.log.ok('"tmp/%s.zip" successfully unzipped', platform);
        defer.resolve();
      });

      unzipper.extract({
        path: 'resources/node-webkit/' + platform
      });
    } else {
      defer.resolve();
    }
  } else if ('.tar.gz' === extension) {
    this.log.info('Un.tar.gz %s files.', platform);
    var src = 'tmp/' + platform + extension;
    var dst = 'resources/node-webkit/' + platform;
    fs.createReadStream(src).pipe(zlib.createGunzip()).pipe(tar.extract(dst)).on('finish', function (error) {
      if (!error) {
        fs.copy('resources/node-webkit/' + platform + '/node-webkit-' + _this.nodeWebkitVersion + '-linux-x64', 'resources/node-webkit/' + platform, function (error) {
          if (error) {
            defer.reject(error);
          } else {
            fs.remove('resources/node-webkit/' + platform + '/node-webkit-' + _this.nodeWebkitVersion + '-linux-x64');
            _this.log.ok('%s directory successfully copied.', platform);
            defer.resolve();
          }
        });
      } else {
        defer.reject(error);
      }
    });
  }
  return defer.promise;
};

NodeWebkitGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};

NodeWebkitGenerator.prototype.copyFiles = function copyFiles() {
  this.copy('_bower.json', 'bower.json');
  this.copy('app/_main.css', 'app/css/main.css');
  this.copy('app/_index.js', 'app/js/index.js');
  this.template('_package.json', 'package.json');
  this.template('app/_package.json', 'app/package.json');
  this.template('app/_index.html', 'app/views/index.html');
  this.template('_Gruntfile.js', 'Gruntfile.js');
  this.template('mac/_Info.plist.tmp', 'resources/mac/Info.plist.tmp');
  this.template('mac/_Info.plist', 'resources/mac/Info.plist');
  this.copy('mac/dmgStyler.applescript', 'resources/mac/dmgStyler.applescript');
  this.copy('mac/package.sh', 'resources/mac/package.sh');
  this.copy('mac/background.png', 'resources/mac/background.png');
};
<commit_msg>* move github API initialisation in github step<commit_after>/*global require*/
'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var when = require('when');
var http = require('http');
var fs = require('fs-extra');
var url = require('url');
var GitHubApi = require('github');
var DecompressZip = require('decompress-zip');
var tar = require('tar-fs');
var zlib = require('zlib');

/*jshint camelcase: false*/
var NodeWebkitGenerator = module.exports = function NodeWebkitGenerator(args, options) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({
      skipInstall: options['skip-install']
    });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
  this.nodeWebkitVersion = 'v0.9.2';
  this.nodeWebkitBaseUrl = 'http://dl.node-webkit.org/' + this.nodeWebkitVersion + '/node-webkit-' + this.nodeWebkitVersion + '-';
  this.github = false;
  console.log(this.yeoman);
};

util.inherits(NodeWebkitGenerator, yeoman.generators.Base);

NodeWebkitGenerator.prototype.askForAppName = function askForAppName() {
  var done = this.async();
  var basePath = path.basename(process.env.PWD);
  var appName = this._.camelize(basePath);

  var prompts = [
    {
      name: 'appName',
      message: 'What do you want to call your app? Allowed characters ^[a-zA-Z0-9]+$',
      default: appName,
      validate: function (answer) {
        if (!/^[a-zA-Z0-9]+$/.test(answer)) {
          return 'The application name should only consist of the following characters a-z, A-Z and 0-9.';
        }
        return true;
      }
    }
  ];

  this.prompt(prompts, function (props) {
    this.appName = props.appName;
    done();
  }.bind(this));

};

NodeWebkitGenerator.prototype.askForDescription = function askForDescription() {
  var done = this.async();
  var prompts = [
    {
      name: 'appDescription',
      message: 'A little description for your app?'
    }
  ];

  this.prompt(prompts, function (props) {
    this.appDescription = props.appDescription;
    done();
  }.bind(this));

};

NodeWebkitGenerator.prototype.askForGithubName = function askForGithubName() {
  var done = this.async();
  var prompts = [
    {
      name: 'githubUser',
      message: 'Would you mind telling me your username on GitHub?',
      default: 'someuser'
    }
  ];

  this.prompt(prompts, function (props) {
    this.githubUser = props.githubUser;
    done();
  }.bind(this));
};

NodeWebkitGenerator.prototype.askForInstallNodeWebkit = function askForInstallNodeWebkit() {
  var done = this.async();
  var prompts = [
    {
      type: 'confirm',
      name: 'downloadNodeWebkit',
      message: 'Do you want to download latest node-webkit?',
      default: true
    },
    {
      type: 'checkbox',
      name: 'platforms',
      message: 'Which platform do you wanna support?',
      choices: [
        {
          name: 'MacOS',
          checked: true
        },
        {
          name: 'Linux 64',
          checked: true
        },
        {
          name: 'Windows',
          checked: true
        }
      ],
      when: function (answers) {
        return answers.downloadNodeWebkit;
      },
      validate: function (answer) {
        if (answer.length < 1) {
          return 'You must choose at least one platform.';
        }
        return true;
      }
    }
  ];

  this.prompt(prompts, function (props) {
    this.platforms = props.platforms;
    this.downloadNodeWebkit = props.downloadNodeWebkit;
    this.MacOS = false;
    this.Linux64 = false;
    this.Windows = false;
    if (props.downloadNodeWebkit) {
      props.platforms.forEach(function (platform) {
        switch (platform) {
        case 'MacOS':
          this.MacOS = true;
          break;
        case 'Linux 64':
          this.Linux64 = true;
          break;
        case 'Windows':
          this.Windows = true;
          break;
        }
      }.bind(this));
    }
    done();
  }.bind(this));
};

NodeWebkitGenerator.prototype.getGithubUserInfo = function getGithubUserInfo() {
  var done = this.async();
  var _this = this;
  var responseClbk = function (err, responseText) {
    if (err) {
      _this.log.info('Error while fetching github user information.', err);
      _this.log.skip('Skip fetching github user information.');
      done();
    } else {
      var responseObject = JSON.parse(JSON.stringify(responseText));
      _this.log.ok('Github informations successfully retrieved.');
      _this.github = true;
      _this.realname = responseObject.name;
      _this.githubUrl = responseObject.html_url;
      done();
    }
  };

  if (this.githubUser !== 'someuser') {
    var proxy = process.env.http_proxy || process.env.HTTP_PROXY || process.env.https_proxy || process.env.HTTPS_PROXY || null;
    var githubOptions = {
      version: '3.0.0'
    };

    if (proxy) {
      githubOptions.proxy = {};
      githubOptions.proxy.host = url.parse(proxy).hostname;
      githubOptions.proxy.port = url.parse(proxy).port;
    }

    var github = new GitHubApi(githubOptions);
    this.log.info('Get GitHub informations');
    github.user.getFrom({
      user: this.githubUser
    }, responseClbk);
  } else {
    done();
  }
};

NodeWebkitGenerator.prototype.createFolder = function createFolder() {
  this.mkdir('app');
  this.mkdir('app/img');
  this.mkdir('resources/node-webkit');
  if (this.MacOS) {
    this.mkdir('resources/node-webkit/MacOS');
  }
  if (this.Linux64) {
    this.mkdir('resources/node-webkit/Linux64');
  }
  if (this.Windows) {
    this.mkdir('resources/node-webkit/Windows');
  }
  this.mkdir('tmp');
};

NodeWebkitGenerator.prototype.getNodeWebkit = function getNodeWebkit() {
  var done = this.async();

  var successClbk = function () {
    done();
  };
  var failureClbk = function (error) {
    throw error;
  };
  if (this.downloadNodeWebkit) {
    when.all(this._getNodeWebkit()).then(successClbk, failureClbk);
  } else {
    when.all(this._createFolder()).then(successClbk, failureClbk);
  }
};

NodeWebkitGenerator.prototype._createFolder = function _createFolder() {
  var promises = [];
  var basePath = 'resources/node-webkit/';
  var platforms = ['MacOS', 'Linux64', 'Windows'];
  platforms.forEach(function (platform) {
    var defer = when.defer();
    promises.push(defer.promise);
    fs.mkdirs(basePath + '/' + platform, function (err) {
      if (err) {
        defer.reject(err);
      } else {
        defer.resolve();
      }
    });
  });
  return promises;
};

NodeWebkitGenerator.prototype._getNodeWebkit = function _getNodeWebkit() {
  var promises = [];
  if (this.MacOS) {
    promises.push(this._requestNodeWebkit('osx-ia32', '.zip', 'MacOS'));
  }
  if (this.Linux64) {
    promises.push(this._requestNodeWebkit('linux-x64', '.tar.gz', 'Linux64'));
  }
  if (this.Windows) {
    promises.push(this._requestNodeWebkit('win-ia32', '.zip', 'Windows'));
  }
  return promises;
};

NodeWebkitGenerator.prototype._requestNodeWebkit = function _requestNodeWebkit(versionString, extension, platform) {
  var defer = when.defer();
  var _this = this;
  if (!fs.existsSync('tmp/' + platform + extension)) {
    if (fs.existsSync('tmp/' + platform + extension + '.part')) {
      fs.unlinkSync('tmp/' + platform + extension + '.part');
    }
    this.log.info('Downloading node-webkit for ' + platform);
    http.get(this.nodeWebkitBaseUrl + versionString + extension, function (res) {
      if (200 === res.statusCode) {
        res.on('data', function (chunk) {
          fs.appendFileSync('tmp/' + platform + extension + '.part', chunk);
        }).on('end', function () {
          fs.renameSync('tmp/' + platform + extension + '.part', 'tmp/' + platform + extension);
          _this.log.ok('Node-webkit for ' + platform + ' downloaded');
          defer.resolve();
        }).on('error', function (error) {
          _this.log.conflict('Error while downloading node-webkit for ' + platform, error);
          defer.reject(error);
        });
      } else {
        _this.log.conflict('Wrong content type for %s', platform);
        defer.reject('Wrong content type for ' + platform);
      }
    }).on('error', function (error) {
      _this.log.conflict('Error while downloading node-webkit for ' + platform, error);
      defer.reject(error);
    });
  } else {
    this.log.ok('Node-webkit for ' + platform + ' already downloaded');
    defer.resolve();
  }
  return defer.promise;
};

NodeWebkitGenerator.prototype.unzipNodeWebkit = function unzipNodeWebkit() {
  var done = this.async();
  var successClbk = function () {
    done();
  };
  var failureClbk = function (error) {
    throw error;
  };
  when.all(this._unzipNodeWebkit()).then(successClbk, failureClbk);
};

NodeWebkitGenerator.prototype._unzipNodeWebkit = function _unzipNodeWebkit() {
  var promises = [];

  if (this.MacOS) {
    promises.push(this._extract('MacOS', '.zip'));
  }
  if (this.Linux64) {
    promises.push(this._extract('Linux64', '.tar.gz'));
  }
  if (this.Windows) {
    promises.push(this._extract('Windows', '.zip'));
  }
  return promises;
};

NodeWebkitGenerator.prototype._extract = function _extract(platform, extension) {
  var _this = this;
  var defer = when.defer();
  if ('.zip' === extension) {
    if (fs.existsSync('tmp/' + platform + extension)) {
      this.log.info('Unzip %s files.', platform);
      var unzipper = new DecompressZip('tmp/' + platform + extension);

      unzipper.on('error', function (error) {
        _this.log.conflict('Error while unzipping "tmp/' + platform + extension + '"', error);
        defer.reject(error);
      });

      unzipper.on('extract', function () {
        _this.log.ok('"tmp/%s.zip" successfully unzipped', platform);
        defer.resolve();
      });

      unzipper.extract({
        path: 'resources/node-webkit/' + platform
      });
    } else {
      defer.resolve();
    }
  } else if ('.tar.gz' === extension) {
    this.log.info('Un.tar.gz %s files.', platform);
    var src = 'tmp/' + platform + extension;
    var dst = 'resources/node-webkit/' + platform;
    fs.createReadStream(src).pipe(zlib.createGunzip()).pipe(tar.extract(dst)).on('finish', function (error) {
      if (!error) {
        fs.copy('resources/node-webkit/' + platform + '/node-webkit-' + _this.nodeWebkitVersion + '-linux-x64', 'resources/node-webkit/' + platform, function (error) {
          if (error) {
            defer.reject(error);
          } else {
            fs.remove('resources/node-webkit/' + platform + '/node-webkit-' + _this.nodeWebkitVersion + '-linux-x64');
            _this.log.ok('%s directory successfully copied.', platform);
            defer.resolve();
          }
        });
      } else {
        defer.reject(error);
      }
    });
  }
  return defer.promise;
};

NodeWebkitGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
};

NodeWebkitGenerator.prototype.copyFiles = function copyFiles() {
  this.copy('_bower.json', 'bower.json');
  this.copy('app/_main.css', 'app/css/main.css');
  this.copy('app/_index.js', 'app/js/index.js');
  this.template('_package.json', 'package.json');
  this.template('app/_package.json', 'app/package.json');
  this.template('app/_index.html', 'app/views/index.html');
  this.template('_Gruntfile.js', 'Gruntfile.js');
  this.template('mac/_Info.plist.tmp', 'resources/mac/Info.plist.tmp');
  this.template('mac/_Info.plist', 'resources/mac/Info.plist');
  this.copy('mac/dmgStyler.applescript', 'resources/mac/dmgStyler.applescript');
  this.copy('mac/package.sh', 'resources/mac/package.sh');
  this.copy('mac/background.png', 'resources/mac/background.png');
};
<|endoftext|>


<commit_before>
scify.ConsultationIndexPageHandler = function( consultationid,userId,fullName,
                                               discussionThreads,
                                               relevantLaws,
                                               consultationIsActive,
                                               imagesPath,
                                               consultationEndDate){
    this.consultationid= consultationid;
    this.consultationIsActive = consultationIsActive;
    this.userId = userId;
    this.fullName = fullName;
    this.imagesPath = imagesPath;

    this.discussionThreads ={};
    for (var i=0; i<discussionThreads.length; i++) //create a map for quick access with id: The discussion thread client id and value: a object with info.
    {
        this.discussionThreads[discussionThreads[i].clientId]= { id: discussionThreads[i].id, num:discussionThreads[i].numberOfComments }
    }

    this.relevantLaws = [];
    for (var i=0; i<relevantLaws.length; i++) {
        this.relevantLaws[i] = {article_id: relevantLaws[i].article_id ,entity_text : relevantLaws[i].entity_text, pdf_url: relevantLaws[i].pdf_url}
    }

    this.consultationEndDate = consultationEndDate;

    this.tutorialAnnotator = null;

};
scify.ConsultationIndexPageHandler.prototype = function(){

    var expandArticleOnClick = function(){
        var article = $(this).closest(".article");
        if (!article.find(".article-body").hasClass("in"))
            article.find(".show-hide").trigger("click");
    },
    getDiscussionThreadNumberOfComments = function(articleId,annotationId){
        if (this.discussionThreads.hasOwnProperty(getDiscussionThreadClientId(articleId,annotationId)))
            return this.discussionThreads[getDiscussionThreadClientId(articleId,annotationId)].num

        return 0;
    },
    getDiscussionThreadId = function(articleId,annotationId){

        if (this.discussionThreads.hasOwnProperty(getDiscussionThreadClientId(articleId,annotationId)))
            return this.discussionThreads[getDiscussionThreadClientId(articleId,annotationId)].id

        return -1;

    },
    createDiscussionRooms = function(){
        var instance = this;
        //todo: load existing rooms from database
        scify.discussionRooms={}; //an object that will contain reference to all the React divs that host the comments
        $(".article").each(function(index,articleDiv){
            var articleid =$(articleDiv).data("id");

            var commentBoxProperties= {
                consultationid          : instance.consultationid,
                consultationEndDate    : instance.consultationEndDate,
                articleid               : articleid,
                discussionthreadid      : -1,
                discussionthreadclientid: getDiscussionThreadClientId(articleid),
                source :"opengov",
                isdiscussionForTheWholeArticle:true,
                commentsCount : $(articleDiv).find(".open-gov").data("count"),  //for open gov we retrieve the counter from
                parent: "consultation"
            };
            var domElementToAddComponent = $(articleDiv).find(".open-gov")[0];
            scify.discussionRooms[commentBoxProperties.discussionthreadclientid] = React.render(React.createElement(scify.CommentBox, commentBoxProperties),domElementToAddComponent );

            $(articleDiv).find(".ann").each(function(i,ann){
                var annId = $(ann).data("id");
                commentBoxProperties.discussionthreadclientid = getDiscussionThreadClientId(articleid,annId );
                commentBoxProperties.discussionthreadid = getDiscussionThreadId.call(instance,articleid,annId );
                commentBoxProperties.commentsCount  = getDiscussionThreadNumberOfComments.call(instance,articleid,annId )
                commentBoxProperties.source="dm";
                commentBoxProperties.userId = instance.userId;
                commentBoxProperties.fullName = instance.fullName;
                commentBoxProperties.discussionThreadText = $(this).text().replace($(this).find(".ann-icon").text(),"");
                commentBoxProperties.isdiscussionForTheWholeArticle = false;

                var commentBox = $('

')
                if ($(ann).parents(".article-title-text").length>0) // for article titles position comment box inside the body
                {
                    commentBoxProperties.isdiscussionForTheWholeArticle=true;
                    $(ann).parents(".article").find(".open-gov").before(commentBox );
                }
                else
                    $(ann).after(commentBox );

                domElementToAddComponent = commentBox[0];
                scify.discussionRooms[commentBoxProperties.discussionthreadclientid]=
                       React.render(React.createElement(scify.CommentBox, commentBoxProperties),domElementToAddComponent );
            });
        });
    },
    getDiscussionRoom = function(articleid,annId){
        return scify.discussionRooms[getDiscussionThreadClientId(articleid,annId)];
    },
    getDiscussionThreadClientId = function(articleid,annId){
        return articleid+(annId ? annId :"");
    },
    addRelevantLawsHandler = function(){
        $(".relevantLawsBtn").on("click", function(){
            console.log($(this).context.id);
            $(".relevantLaw #" + $(this).context.id + " .relevantLawsBtn").toggleClass("clicked");
            if($(".relevantLaw #" + $(this).context.id + " .relevantLawsBtn").hasClass("clicked")) {
                $(".relevantLaw #" + $(this).context.id + " .childLaws").show("slow");
            }
            else {
                $(".relevantLaw #" + $(this).context.id + " .childLaws").hide("fast");
            }
        });
    },
    handleAnnotationSave = function(data){
        getDiscussionRoom(data.articleid,data.discussionroomannotationtagid).saveComment(data.action,data);
     },
    replaceRelevantLaws = function(relevantLaws) {
            for (var i=0; i<relevantLaws.length; i++) {
                var replaceText = relevantLaws[i].entity_text;
                var replacedHtml = $("div[data-id="+ relevantLaws[i].article_id +"]").html().replace(relevantLaws[i].entity_text, "" + replaceText + "");
                $("div[data-id="+ relevantLaws[i].article_id +"]").html(replacedHtml);
            }
        },
    removeParagraphsWithNoText = function(){
            $(".message").find("p").each(function(i,el){
                if ($.trim($(this).text()).length==0)
                    $(this).remove();
            });
        },
    createWordCloudChart = function(instance) {
        var domElementWordCloud = document.getElementById("wordCloudDiv");
        var consWordCloudProperties = {
            chartId : "wordCloudChart"
        };
        window.WordCloudComponent = React.render(React.createElement(scify.WordCloud, consWordCloudProperties), domElementWordCloud);
        loadWordCloud(instance.consultationid);
    },
    loadWordCloud = function(consultationId) {
        window.WordCloudComponent.getConsWordCloudFromServer(consultationId);
    }
    init = function(){
        var instance= this;
        moment.locale('el');

        this.annotator = new scify.Annotator(false, handleAnnotationSave);
        this.annotator.init();

        replaceRelevantLaws(this.relevantLaws);
        addRelevantLawsHandler();
        $(".article-title-text").click(expandArticleOnClick);
        $(".article-title-text").first().trigger("click");

        createDiscussionRooms.call(instance);
        removeParagraphsWithNoText();

        //tinymce.init({selector:'textarea'})

        this.tutorialAnnotator = new scify.TutorialAnnotator(this.consultationIsActive, this.imagesPath);
        this.tutorialAnnotator.init();
        createWordCloudChart(instance);
    };

    return {
        init:init
    }
}();

<commit_msg>Removed debug messages<commit_after>
scify.ConsultationIndexPageHandler = function( consultationid,userId,fullName,
                                               discussionThreads,
                                               relevantLaws,
                                               consultationIsActive,
                                               imagesPath,
                                               consultationEndDate){
    this.consultationid= consultationid;
    this.consultationIsActive = consultationIsActive;
    this.userId = userId;
    this.fullName = fullName;
    this.imagesPath = imagesPath;

    this.discussionThreads ={};
    for (var i=0; i<discussionThreads.length; i++) //create a map for quick access with id: The discussion thread client id and value: a object with info.
    {
        this.discussionThreads[discussionThreads[i].clientId]= { id: discussionThreads[i].id, num:discussionThreads[i].numberOfComments }
    }

    this.relevantLaws = [];
    for (var i=0; i<relevantLaws.length; i++) {
        this.relevantLaws[i] = {article_id: relevantLaws[i].article_id ,entity_text : relevantLaws[i].entity_text, pdf_url: relevantLaws[i].pdf_url}
    }

    this.consultationEndDate = consultationEndDate;

    this.tutorialAnnotator = null;

};
scify.ConsultationIndexPageHandler.prototype = function(){

    var expandArticleOnClick = function(){
        var article = $(this).closest(".article");
        if (!article.find(".article-body").hasClass("in"))
            article.find(".show-hide").trigger("click");
    },
    getDiscussionThreadNumberOfComments = function(articleId,annotationId){
        if (this.discussionThreads.hasOwnProperty(getDiscussionThreadClientId(articleId,annotationId)))
            return this.discussionThreads[getDiscussionThreadClientId(articleId,annotationId)].num

        return 0;
    },
    getDiscussionThreadId = function(articleId,annotationId){

        if (this.discussionThreads.hasOwnProperty(getDiscussionThreadClientId(articleId,annotationId)))
            return this.discussionThreads[getDiscussionThreadClientId(articleId,annotationId)].id

        return -1;

    },
    createDiscussionRooms = function(){
        var instance = this;
        //todo: load existing rooms from database
        scify.discussionRooms={}; //an object that will contain reference to all the React divs that host the comments
        $(".article").each(function(index,articleDiv){
            var articleid =$(articleDiv).data("id");

            var commentBoxProperties= {
                consultationid          : instance.consultationid,
                consultationEndDate    : instance.consultationEndDate,
                articleid               : articleid,
                discussionthreadid      : -1,
                discussionthreadclientid: getDiscussionThreadClientId(articleid),
                source :"opengov",
                isdiscussionForTheWholeArticle:true,
                commentsCount : $(articleDiv).find(".open-gov").data("count"),  //for open gov we retrieve the counter from
                parent: "consultation"
            };
            var domElementToAddComponent = $(articleDiv).find(".open-gov")[0];
            scify.discussionRooms[commentBoxProperties.discussionthreadclientid] = React.render(React.createElement(scify.CommentBox, commentBoxProperties),domElementToAddComponent );

            $(articleDiv).find(".ann").each(function(i,ann){
                var annId = $(ann).data("id");
                commentBoxProperties.discussionthreadclientid = getDiscussionThreadClientId(articleid,annId );
                commentBoxProperties.discussionthreadid = getDiscussionThreadId.call(instance,articleid,annId );
                commentBoxProperties.commentsCount  = getDiscussionThreadNumberOfComments.call(instance,articleid,annId )
                commentBoxProperties.source="dm";
                commentBoxProperties.userId = instance.userId;
                commentBoxProperties.fullName = instance.fullName;
                commentBoxProperties.discussionThreadText = $(this).text().replace($(this).find(".ann-icon").text(),"");
                commentBoxProperties.isdiscussionForTheWholeArticle = false;

                var commentBox = $('

')
                if ($(ann).parents(".article-title-text").length>0) // for article titles position comment box inside the body
                {
                    commentBoxProperties.isdiscussionForTheWholeArticle=true;
                    $(ann).parents(".article").find(".open-gov").before(commentBox );
                }
                else
                    $(ann).after(commentBox );

                domElementToAddComponent = commentBox[0];
                scify.discussionRooms[commentBoxProperties.discussionthreadclientid]=
                       React.render(React.createElement(scify.CommentBox, commentBoxProperties),domElementToAddComponent );
            });
        });
    },
    getDiscussionRoom = function(articleid,annId){
        return scify.discussionRooms[getDiscussionThreadClientId(articleid,annId)];
    },
    getDiscussionThreadClientId = function(articleid,annId){
        return articleid+(annId ? annId :"");
    },
    addRelevantLawsHandler = function(){
        $(".relevantLawsBtn").on("click", function(){
            $(".relevantLaw #" + $(this).context.id + " .relevantLawsBtn").toggleClass("clicked");
            if($(".relevantLaw #" + $(this).context.id + " .relevantLawsBtn").hasClass("clicked")) {
                $(".relevantLaw #" + $(this).context.id + " .childLaws").show("slow");
            }
            else {
                $(".relevantLaw #" + $(this).context.id + " .childLaws").hide("fast");
            }
        });
    },
    handleAnnotationSave = function(data){
        getDiscussionRoom(data.articleid,data.discussionroomannotationtagid).saveComment(data.action,data);
     },
    replaceRelevantLaws = function(relevantLaws) {
            for (var i=0; i<relevantLaws.length; i++) {
                var replaceText = relevantLaws[i].entity_text;
                var replacedHtml = $("div[data-id="+ relevantLaws[i].article_id +"]").html().replace(relevantLaws[i].entity_text, "" + replaceText + "");
                $("div[data-id="+ relevantLaws[i].article_id +"]").html(replacedHtml);
            }
        },
    removeParagraphsWithNoText = function(){
            $(".message").find("p").each(function(i,el){
                if ($.trim($(this).text()).length==0)
                    $(this).remove();
            });
        },
    createWordCloudChart = function(instance) {
        var domElementWordCloud = document.getElementById("wordCloudDiv");
        var consWordCloudProperties = {
            chartId : "wordCloudChart"
        };
        window.WordCloudComponent = React.render(React.createElement(scify.WordCloud, consWordCloudProperties), domElementWordCloud);
        loadWordCloud(instance.consultationid);
    },
    loadWordCloud = function(consultationId) {
        window.WordCloudComponent.getConsWordCloudFromServer(consultationId);
    }
    init = function(){
        var instance= this;
        moment.locale('el');

        this.annotator = new scify.Annotator(false, handleAnnotationSave);
        this.annotator.init();

        replaceRelevantLaws(this.relevantLaws);
        addRelevantLawsHandler();
        $(".article-title-text").click(expandArticleOnClick);
        $(".article-title-text").first().trigger("click");

        createDiscussionRooms.call(instance);
        removeParagraphsWithNoText();

        //tinymce.init({selector:'textarea'})

        this.tutorialAnnotator = new scify.TutorialAnnotator(this.consultationIsActive, this.imagesPath);
        this.tutorialAnnotator.init();
        createWordCloudChart(instance);
    };

    return {
        init:init
    }
}();

<|endoftext|>


<commit_before>'use strict';

var spawn = require('child_process').spawn;
var EE = require('events').EventEmitter;
var util = require('util');
var async = require('async');
var node_path = require('path');

module.exports = spawns;

function spawns(commands, options) {
  return new Spawns(commands, options);
}
spawns.Spawns = Spawns;

// @param {Array.<string>} commands
function Spawns(commands, options) {
  if (!util.isArray(commands)) {
    commands = [commands];
  }

  // [
  //     // single command
  //     [command],

  //     // piped commands
  //     [command, command]
  // ]
  this._commands = this._parse_commands(commands);
  this._options = options;
  var self = this;

  // run in the next tick,
  // so that forward event buidings could be applied
  process.nextTick(function() {
    self._process();
  });
}

util.inherits(Spawns, EE);

// events for all processes
// this.emit('close');
// this.emit('exit');
// this.emit('error');

// // child process events
// this.emit('child_close');
// this.emit('child_exit');

Spawns.prototype._process = function() {
  var self = this;
  async.series(this._commands.map(function(command) {
    return function(done) {
      if (command.length === 1) {
        self._spawn(command[0], done);
      }
    };

  }), function(code, status) {
    var last = status.pop();

    self.emit('close', last[0], last[1]);
  });
};

// spawns a child command
// @param {Object} command {
//      name:
//      args:
// }
Spawns.prototype._spawn = function(command, done) {
  this.emit('spawn', command.origin);

  var child = spawn(command.name, command.args, this._options);
  var self = this;

  child.on('error', function(err) {
    self.emit('error', err);
  });

  child.on('exit', function(code, signal) {
    self.emit('child_exit', code, signal);
  });

  child.on('close', function(code, signal) {
    self.emit('child_close', code, signal);
    done(code, code, signal);
  });

  return child;
};

// @param {Array.<string>} commands
Spawns.prototype._parse_commands = function(commands) {
  return commands.map(this._parse_piped, this);
};

Spawns.prototype._parse_piped = function(command) {
  return command.split('|')
    .map(function(pipe) {
      return pipe.trim();
    })
    .filter(Boolean)
    .map(this._parse_command, this);
};

var is_windows = process.platform === 'win32';

// @param {string} command
Spawns.prototype._parse_command = function(command) {
  // // #4,
  // // We should reserve quoted spaces, so never use `/\s+/`
  // var slices = command.split(/\s/).map(function(slice) {
  //   return slice.trim();
  // });

  // var name
  // if (this._is_windows_spawn(slices)) {
  //   name = '/c/cmd';
  // } else {
  //   name = slices.shift();
  // }

  // return {
  //   name: name,
  //   args: this._balance_args(slices),
  //   origin: command
  // };

  return is_windows
    ? {
      name: 'cmd',
      args: ['/c', command],
      origin: command
    }
    : {
      name: 'sh',
      args: ['-c', command],
      origin: command
    };
};

var DOUBLE_QUOTE_START = /^".*[^"]$/;
var DOUBLE_QUOTE_END = /"$/;
var SINGLE_QUOTE_START = /^'.*[^']$/;
var SINGLE_QUOTE_END = /'$/;

// empty argument is allowed
// git commit -a -m "" -> empty value is allow by bash, but git commit will fail
var QUOTE_PAIR = /^(['"])(.*)\1$/;
function trim (str) {
  var match = str.match(QUOTE_PAIR);
  return match
    ? match[2]
    : str;
}

// #4,
// Deal with quotes
Spawns.prototype._balance_args = function(slices) {
  var double_quoted;
  var single_quoted;
  var stack = [];
  var max = slices.length - 1;
  return slices.reduce(function(prev, current, index) {
    if (double_quoted) {
      stack.push(current);
      if (DOUBLE_QUOTE_END.test(current)) {
        double_quoted = false;

        prev.push( trim(stack.join(' ')) );
        stack.length = 0;

      // -a "a b
      // -> ['-a', '"a', 'b']
      // balance quotes teminated
      } else if (index === max) {
        prev = prev.concat(stack);
        stack.length = 0;
      }

    } else if (single_quoted) {
      stack.push(current);
      if (SINGLE_QUOTE_END.test(current)) {
        single_quoted = false;

        prev.push( trim(stack.join(' ')) );
        stack.length = 0;

      } else if (index === max) {
        prev = prev.concat(stack);
        stack.length = 0;
      }

    // if not quoted, and current is empty, just skip
    } else if (current) {
      if (DOUBLE_QUOTE_START.test(current)) {
        stack.push(current);
        double_quoted = true;

      } else if (SINGLE_QUOTE_START.test(current)) {
        stack.push( current );
        single_quoted = true;

      } else {
        prev.push( trim(current) );
      }
    }

    return prev;
  }, []);
};
<commit_msg>complete<commit_after>'use strict';

var spawn = require('child_process').spawn;
var EE = require('events').EventEmitter;
var util = require('util');
var async = require('async');
var node_path = require('path');
var mix = require('mix2');

module.exports = spawns;

function spawns(commands, options) {
  return new Spawns(commands, options || {});
}
spawns.Spawns = Spawns;

// @param {Array.<string>} commands
function Spawns(commands, options) {
  if (!util.isArray(commands)) {
    commands = [commands];
  }

  // [
  //     // single command
  //     [command],

  //     // piped commands
  //     [command, command]
  // ]
  this._commands = this._parse_commands(commands);
  this._options = options;
  var self = this;

  // run in the next tick,
  // so that forward event buidings could be applied
  process.nextTick(function() {
    self._process();
  });
}

util.inherits(Spawns, EE);

// events for all processes
// this.emit('close');
// this.emit('exit');
// this.emit('error');

// // child process events
// this.emit('child_close');
// this.emit('child_exit');

Spawns.prototype._process = function() {
  var self = this;
  async.series(this._commands.map(function(command) {
    return function(done) {
      self._spawn(command, done);
    };
  }), function(code, status) {
    var last = status.pop();
    self.emit('close', last[0], last[1]);
  });
};

// spawns a child command
// @param {Object} command {
//      name:
//      args:
// }
Spawns.prototype._spawn = function(command, done) {
  var child = spawn(
    command.name,
    command.args,
    mix(command.options || {}, this._options, false)
  );
  var self = this;

  child.on('error', function(err) {
    self.emit('error', err);
  });

  child.on('exit', function(code, signal) {
    self.emit('child_exit', code, signal);
  });

  child.on('close', function(code, signal) {
    self.emit('child_close', code, signal);
    done(code, code, signal);
  });

  return child;
};

// @param {Array.<string>} commands
Spawns.prototype._parse_commands = function(commands) {
  return commands.map(this._parse_command, this);
};

var is_windows = process.platform === 'win32';

// @param {string} command
Spawns.prototype._parse_command = function(command) {
  // // #4,
  // // We should reserve quoted spaces, so never use `/\s+/`
  // var slices = command.split(/\s/).map(function(slice) {
  //   return slice.trim();
  // });

  // var name
  // if (this._is_windows_spawn(slices)) {
  //   name = '/c/cmd';
  // } else {
  //   name = slices.shift();
  // }

  // return {
  //   name: name,
  //   args: this._balance_args(slices),
  //   origin: command
  // };

  return is_windows
    ? {
      name: 'cmd',
      args: ['/c', command],
      origin: command,
      options: {
        windowsVerbatimArguments: true
      }
    }
    : {
      name: 'sh',
      args: ['-c', command],
      origin: command
    };
};

var DOUBLE_QUOTE_START = /^".*[^"]$/;
var DOUBLE_QUOTE_END = /"$/;
var SINGLE_QUOTE_START = /^'.*[^']$/;
var SINGLE_QUOTE_END = /'$/;

// empty argument is allowed
// git commit -a -m "" -> empty value is allow by bash, but git commit will fail
var QUOTE_PAIR = /^(['"])(.*)\1$/;
function trim (str) {
  var match = str.match(QUOTE_PAIR);
  return match
    ? match[2]
    : str;
}

// #4,
// Deal with quotes
Spawns.prototype._balance_args = function(slices) {
  var double_quoted;
  var single_quoted;
  var stack = [];
  var max = slices.length - 1;
  return slices.reduce(function(prev, current, index) {
    if (double_quoted) {
      stack.push(current);
      if (DOUBLE_QUOTE_END.test(current)) {
        double_quoted = false;

        prev.push( trim(stack.join(' ')) );
        stack.length = 0;

      // -a "a b
      // -> ['-a', '"a', 'b']
      // balance quotes teminated
      } else if (index === max) {
        prev = prev.concat(stack);
        stack.length = 0;
      }

    } else if (single_quoted) {
      stack.push(current);
      if (SINGLE_QUOTE_END.test(current)) {
        single_quoted = false;

        prev.push( trim(stack.join(' ')) );
        stack.length = 0;

      } else if (index === max) {
        prev = prev.concat(stack);
        stack.length = 0;
      }

    // if not quoted, and current is empty, just skip
    } else if (current) {
      if (DOUBLE_QUOTE_START.test(current)) {
        stack.push(current);
        double_quoted = true;

      } else if (SINGLE_QUOTE_START.test(current)) {
        stack.push( current );
        single_quoted = true;

      } else {
        prev.push( trim(current) );
      }
    }

    return prev;
  }, []);
};
<|endoftext|>


<commit_before>var request = require('superagent');

function Component () {}

Component.prototype.create = function (model, dom) {
  if (model.get('autofocus')) this.focus();
  if (this.form) dom.addListener('submit', this.form, this.submit.bind(this));
};

Component.prototype.error = function (err) {
  this.model.del('submitting');
  this.model.set('error', err);
  this.redirect();
};

Component.prototype.focus = function () {
  if (this.handle) this.handle.focus();
};

Component.prototype.redirect = function () {
  var model = this.model;
  var error = model.get('error');
  var redirect = model.get('errorRedirect') || model.get('redirect');
  if (error && redirect) return this.app.history.push(redirect);
  redirect = model.get('successRedirect') || model.get('redirect');
  if (redirect) return this.app.history.push(redirect);
};

Component.prototype.reset = function () {
  if (this.form) this.form.reset();
};

Component.prototype.submit = function (e) {
  if (e) e.preventDefault();
  var self = this;
  var model = this.model;
  var basePath = model.get('basePath') || '';
  var data = model.get('data');
  var origin = model.get('origin') || window.location.origin;
  var path = model.get('path') || '/signin';
  var url = model.get('url') || (origin + basePath + path);

  model.del('error');
  model.set('submitting', true);
  this.emit('submitting');
  this._validate(function (err) {
    if (err) return self.error(err);
    request
      .post(url)
      .withCredentials()
      .send(data)
      .end(function (err, res) {
        self._response(err, res, function (err) {
          if (err) return self.error(err);
          self._submitted(res.body, function (err) {
            model.del('submitting');
            if (err) return self.error(err);
            self.emit('submitted');
            self.redirect();
          });
        });
      });
  });
};

Component.prototype._response = function (err, res, done) {
  done(err || res.body.error);
};

Component.prototype._submitted = function (done) {
  done();
};

Component.prototype._validate = function (done) {
  done();
};

module.exports = Component;
<commit_msg>fix error redirect<commit_after>var request = require('superagent');

function Component () {}

Component.prototype.create = function (model, dom) {
  if (model.get('autofocus')) this.focus();
  if (this.form) dom.addListener('submit', this.form, this.submit.bind(this));
};

Component.prototype.error = function (err) {
  this.model.del('submitting');
  this.model.set('error', err);
  this.redirect();
};

Component.prototype.focus = function () {
  if (this.handle) this.handle.focus();
};

Component.prototype.redirect = function () {
  var model = this.model;
  var error = model.get('error');
  var redirect = model.get('errorRedirect') || model.get('redirect');
  if (error && redirect) return this.app.history.push(redirect);
  if (error) return;
  redirect = model.get('successRedirect') || model.get('redirect');
  if (redirect) return this.app.history.push(redirect);
};

Component.prototype.reset = function () {
  if (this.form) this.form.reset();
};

Component.prototype.submit = function (e) {
  if (e) e.preventDefault();
  var self = this;
  var model = this.model;
  var basePath = model.get('basePath') || '';
  var data = model.get('data');
  var origin = model.get('origin') || window.location.origin;
  var path = model.get('path') || '/signin';
  var url = model.get('url') || (origin + basePath + path);

  model.del('error');
  model.set('submitting', true);
  this.emit('submitting');
  this._validate(function (err) {
    if (err) return self.error(err);
    request
      .post(url)
      .withCredentials()
      .send(data)
      .end(function (err, res) {
        self._response(err, res, function (err) {
          if (err) return self.error(err);
          self._submitted(res.body, function (err) {
            model.del('submitting');
            if (err) return self.error(err);
            self.emit('submitted');
            self.redirect();
          });
        });
      });
  });
};

Component.prototype._response = function (err, res, done) {
  done(err || res.body.error);
};

Component.prototype._submitted = function (done) {
  done();
};

Component.prototype._validate = function (done) {
  done();
};

module.exports = Component;
<|endoftext|>


<commit_before>/*
    Inspired by https://github.com/assemble/generator-assemble/
    which is released under an MIT license
*/

'use strict';
var fs = require('fs');
// var util = require('util');
// var path = require('path');
var crypto = require('crypto');
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var shell = require('shelljs');
var updateNotifier = require('update-notifier');
var metrics = require('famous-metrics');

var FamousGenerator = yeoman.generators.Base.extend({
  init: function () {
    var notifier = updateNotifier({
      packagePath: '../package.json',
      updateCheckInterval: 1
    });

    if (notifier.update) {
      notifier.notify();
      process.exit(1);
    }
    if (!shell.which('git')) {
      this.log(chalk.red('(ERROR)') + ' It looks like you do not have git installed, please install it and try again.');
      process.exit(1);
    }
    this.pkg = require('../package.json');
    this.description = this.pkg.description;

    this.option('init', {
      alias: 'i',
      desc: 'Force to prompt question and re-initialize of .yo-rc.json',
      type: String,
      defaults: false,
      required: false
    });

    this.init = this.options['init'] || this.options['i'] || false;

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies({
          skipInstall: this.options['skip-install'] || this.options['s'],
          skipMessage: this.options['skip-welcome-message'] || this.options['w']
        });
      }
    });

    this.config.defaults({
      projectName: 'Famo.us Base',
      projectDesc: 'Seed project to get started with Famo.us',
      authorLogin: '',
      author: {
        name: this.user.git.username || process.env.user || process.env.username,
        email: this.user.git.email
      }
    });
  },

  askFor: function () {
    var done = this.async();

    // have Yeoman greet the user
    if (!this.options['skip-welcome-message']) {
      this.log(this.yeoman);
      // replace it with a short and sweet description of your generator
      this.log(chalk.magenta('You\'re using the fantastic Famo.us generator.'));
    }

    var force = false;

    if (!this.config.existed || this.init) {
      force = true;
    }

    var questions = [];

    if (!this.config.get('projectName') || force)  {
      questions.push({
        type : 'input',
        name : 'projectName',
        message : 'Your project name',
        default : this.appname || this.config.get('projectName')
      });
    }

    if (!this.config.get('projectDesc') || force) {
      questions.push({
        type : 'input',
        name : 'projectDesc',
        message : 'Your project description',
        default : this.config.get('projectDesc')
      });
    }

    if (!this.config.get('authorLogin') || force) {
      questions.push({
        type : 'input',
        name : 'authorLogin',
        message : 'Would you mind telling me your username on Github?',
        default : this.config.get('author').login || this.config.get('authorLogin')
      });
    }

    if (metrics.getTinfoil() === null) {
      questions.push({
        type : 'confirm',
        name : 'noTinfoil',
        message : chalk.green('(optional)') + ' Do you agree to our Terms of Service (https://famo.us/terms) and our Privacy Policy (http://famo.us/privacy)?',
        default : true
      });
    }

    this.prompt(questions, function (answers) {
      this.projectName = answers.projectName || this.config.get('projectName');
      this.projectDesc = answers.projectDesc || this.config.get('projectDesc');
      this.authorLogin = answers.authorLogin || this.config.get('authorLogin');

      this.authorName  = this.config.get('author').name;
      this.authorEmail = this.config.get('author').email;

      if (metrics.getTinfoil() === null) {
        if (answers.noTinfoil) {
          metrics.setTinfoil(this.authorEmail, function(err) {
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
            metrics.track('initialization', {
              packageName: this.pkg.name,
              packageVersion: this.pkg.version
            });
          });
        } else {
          metrics.setTinfoil(false, function(err){
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
          });
        }
      }

      if (!metrics.getTinfoil()) {
        metrics.track('initialization', {
          packageName: this.pkg.name,
          packageVersion: this.pkg.version
        });
      }

      //save config to .yo-rc.json
      this.config.set(answers);

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('app');
    this.mkdir('app/styles');
    this.mkdir('app/content');
    this.mkdir('app/content/images');
    this.mkdir('app/src');

    this.copy('README.md', 'README.md');

    this.template('_index.html', 'app/index.html');

    this.bulkCopy('images/_famous_logo.png', 'app/content/images/famous_logo.png');

    this.copy('styles/app.css', 'app/styles/app.css');

    this.template('src/requireConfig.js', 'app/src/requireConfig.js');
    this.template('src/_main.js', 'app/src/main.js');
  },

  manifests: function () {
    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
    this.copy('Gruntfile.js', 'Gruntfile.js');
  },

  dotfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('bowerrc', '.bowerrc');
    this.copy('eslint.json', '.eslintrc');
    this.copy('jscs.json', '.jscsrc');
    this.copy('gitignore', '.gitignore');
    this.copy('travis.yml', '.travis.yml');
  },

  gruntfiles: function () {
    this.mkdir('grunt');

    this.src.copy('grunt/aliases.js', 'grunt/aliases.js');
    this.src.copy('grunt/eslint.js', 'grunt/eslint.js');
    this.src.copy('grunt/jscs.js', 'grunt/jscs.js');
    this.src.copy('grunt/watch.js', 'grunt/watch.js');
    this.src.copy('grunt/connect.js', 'grunt/connect.js');
    this.src.copy('grunt/clean.js', 'grunt/clean.js');
    this.src.copy('grunt/bower.js', 'grunt/bower.js');
    this.src.copy('grunt/rev.js', 'grunt/rev.js');
    this.src.copy('grunt/processhtml.js', 'grunt/processhtml.js');
    this.src.copy('grunt/useminPrepare.js', 'grunt/useminPrepare.js');
    this.src.copy('grunt/usemin.js', 'grunt/usemin.js');
    this.src.copy('grunt/htmlmin.js', 'grunt/htmlmin.js');
    this.src.copy('grunt/copy.js', 'grunt/copy.js');
    this.src.copy('grunt/requirejs.js', 'grunt/requirejs.js');
  }
});

module.exports = FamousGenerator;
<commit_msg>Fixing styles<commit_after>/*
    Inspired by https://github.com/assemble/generator-assemble/
    which is released under an MIT license
*/

'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var shell = require('shelljs');
var updateNotifier = require('update-notifier');
var metrics = require('famous-metrics');

var FamousGenerator = yeoman.generators.Base.extend({
  init: function () {
    var notifier = updateNotifier({
      packagePath: '../package.json',
      updateCheckInterval: 1
    });

    if (notifier.update) {
      notifier.notify();
      process.exit(1);
    }
    if (!shell.which('git')) {
      this.log(chalk.red('(ERROR)') + ' It looks like you do not have git installed, please install it and try again.');
      process.exit(1);
    }
    this.pkg = require('../package.json');
    this.description = this.pkg.description;

    this.option('init', {
      alias: 'i',
      desc: 'Force to prompt question and re-initialize of .yo-rc.json',
      type: String,
      defaults: false,
      required: false
    });

    this.init = this.options['init'] || this.options['i'] || false;

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies({
          skipInstall: this.options['skip-install'] || this.options['s'],
          skipMessage: this.options['skip-welcome-message'] || this.options['w']
        });
      }
    });

    this.config.defaults({
      projectName: 'Famo.us Base',
      projectDesc: 'Seed project to get started with Famo.us',
      authorLogin: '',
      author: {
        name: this.user.git.username || process.env.user || process.env.username,
        email: this.user.git.email
      }
    });
  },

  askFor: function () {
    var done = this.async();

    // have Yeoman greet the user
    if (!this.options['skip-welcome-message']) {
      this.log(this.yeoman);
      // replace it with a short and sweet description of your generator
      this.log(chalk.magenta('You\'re using the fantastic Famo.us generator.'));
    }

    var force = false;

    if (!this.config.existed || this.init) {
      force = true;
    }

    var questions = [];

    if (!this.config.get('projectName') || force)  {
      questions.push({
        type : 'input',
        name : 'projectName',
        message : 'Your project name',
        default : this.appname || this.config.get('projectName')
      });
    }

    if (!this.config.get('projectDesc') || force) {
      questions.push({
        type : 'input',
        name : 'projectDesc',
        message : 'Your project description',
        default : this.config.get('projectDesc')
      });
    }

    if (!this.config.get('authorLogin') || force) {
      questions.push({
        type : 'input',
        name : 'authorLogin',
        message : 'Would you mind telling me your username on Github?',
        default : this.config.get('author').login || this.config.get('authorLogin')
      });
    }

    if (metrics.getTinfoil() === null) {
      questions.push({
        type : 'confirm',
        name : 'noTinfoil',
        message : chalk.green('(optional)') + ' Do you agree to our Terms of Service (https://famo.us/terms) and our Privacy Policy (http://famo.us/privacy)?',
        default : true
      });
    }

    this.prompt(questions, function (answers) {
      this.projectName = answers.projectName || this.config.get('projectName');
      this.projectDesc = answers.projectDesc || this.config.get('projectDesc');
      this.authorLogin = answers.authorLogin || this.config.get('authorLogin');

      this.authorName  = this.config.get('author').name;
      this.authorEmail = this.config.get('author').email;

      if (metrics.getTinfoil() === null) {
        if (answers.noTinfoil) {
          metrics.setTinfoil(this.authorEmail, function (err) {
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
            metrics.track('initialization', {
              packageName: this.pkg.name,
              packageVersion: this.pkg.version
            });
          });
        }
        else {
          metrics.setTinfoil(false, function (err) {
            if (err) {
              return console.error('Failed to write ~/.famousrc');
            }
          });
        }
      }

      if (!metrics.getTinfoil()) {
        metrics.track('initialization', {
          packageName: this.pkg.name,
          packageVersion: this.pkg.version
        });
      }

      //save config to .yo-rc.json
      this.config.set(answers);

      done();
    }.bind(this));
  },

  app: function () {
    this.mkdir('app');
    this.mkdir('app/styles');
    this.mkdir('app/content');
    this.mkdir('app/content/images');
    this.mkdir('app/src');

    this.copy('README.md', 'README.md');

    this.template('_index.html', 'app/index.html');

    this.bulkCopy('images/_famous_logo.png', 'app/content/images/famous_logo.png');

    this.copy('styles/app.css', 'app/styles/app.css');

    this.template('src/requireConfig.js', 'app/src/requireConfig.js');
    this.template('src/_main.js', 'app/src/main.js');
  },

  manifests: function () {
    this.copy('_package.json', 'package.json');
    this.copy('_bower.json', 'bower.json');
    this.copy('Gruntfile.js', 'Gruntfile.js');
  },

  dotfiles: function () {
    this.copy('editorconfig', '.editorconfig');
    this.copy('bowerrc', '.bowerrc');
    this.copy('eslint.json', '.eslintrc');
    this.copy('jscs.json', '.jscsrc');
    this.copy('gitignore', '.gitignore');
    this.copy('travis.yml', '.travis.yml');
  },

  gruntfiles: function () {
    this.mkdir('grunt');

    this.src.copy('grunt/aliases.js', 'grunt/aliases.js');
    this.src.copy('grunt/eslint.js', 'grunt/eslint.js');
    this.src.copy('grunt/jscs.js', 'grunt/jscs.js');
    this.src.copy('grunt/watch.js', 'grunt/watch.js');
    this.src.copy('grunt/connect.js', 'grunt/connect.js');
    this.src.copy('grunt/clean.js', 'grunt/clean.js');
    this.src.copy('grunt/bower.js', 'grunt/bower.js');
    this.src.copy('grunt/rev.js', 'grunt/rev.js');
    this.src.copy('grunt/processhtml.js', 'grunt/processhtml.js');
    this.src.copy('grunt/useminPrepare.js', 'grunt/useminPrepare.js');
    this.src.copy('grunt/usemin.js', 'grunt/usemin.js');
    this.src.copy('grunt/htmlmin.js', 'grunt/htmlmin.js');
    this.src.copy('grunt/copy.js', 'grunt/copy.js');
    this.src.copy('grunt/requirejs.js', 'grunt/requirejs.js');
  }
});

module.exports = FamousGenerator;
<|endoftext|>


<commit_before>'use strict';

module.exports = function (buf) {
	if (!buf || buf.length < 3) {
		return false;
	}

	return buf[0] === 66 && buf[1] === 90 && buf[2] === 104;
};
<commit_msg>Use hex values<commit_after>'use strict';

module.exports = function (buf) {
	if (!buf || buf.length < 3) {
		return false;
	}

	return buf[0] === 0x42 && buf[1] === 0x5a && buf[2] === 0x68;
};
<|endoftext|>


<commit_before>var React = require('react');
var ReactDOM = require('react-dom');

var App = React.createClass({
  render() {
    return (

Hello world

    );
  }
});

ReactDOM.render(<App />, document.body);
<commit_msg>added bootstrap and some css<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
var App = require('./components/App');

var options = {
  title: 'Choose a Fruit',
  items: ['Apple', 'banana', 'mango', 'pineapple']
};

ReactDOM.render(<App data={options} />, document.getElementById('app'));
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');
var updateNotifier = require('update-notifier');

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
    updateNotifier({pkg: this.pkg}).notify();
  },

  prompting: {

    name: function () {
      var done = this.async();

      // Have Yeoman greet the user.
      this.log(yosay(
        'Let\'s make a visualization!'
      ));

      var prompts = [{
        name: 'name',
        message: 'Module Name',
        default: path.basename(process.cwd())
      }];

      this.prompt(prompts, function (props) {
        this.slugname = _.kebabCase(props.name);
        this.props = props;
        done();
      }.bind(this));
    }
  },

  configuring: function() {

    this.template('_package.json',  './package.json');
    this.template('index.js',  './index.js');
    this.template('README.md',  './README.md');
    this.copy('gitignore', './.gitignore');

  },

  writing: function() {
    this.directory('src', './src');
  },

  install: function () {
    var elementDir = process.cwd();
    process.chdir(elementDir);
    this.npmInstall();
  }
});
<commit_msg>Add data<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');
var updateNotifier = require('update-notifier');

module.exports = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
    updateNotifier({pkg: this.pkg}).notify();
  },

  prompting: {

    name: function () {
      var done = this.async();

      // Have Yeoman greet the user.
      this.log(yosay(
        'Let\'s make a visualization!'
      ));

      var prompts = [{
        name: 'name',
        message: 'Module Name',
        default: path.basename(process.cwd())
      }];

      this.prompt(prompts, function (props) {
        this.slugname = _.kebabCase(props.name);
        this.props = props;
        done();
      }.bind(this));
    }
  },

  configuring: function() {

    this.template('_package.json',  './package.json');
    this.template('index.js',  './index.js');
    this.template('README.md',  './README.md');
    this.copy('gitignore', './.gitignore');

  },

  writing: function() {
    this.directory('src', './src');
    this.directory('data', './data');
  },

  install: function () {
    var elementDir = process.cwd();
    process.chdir(elementDir);
    this.npmInstall();
  }
});
<|endoftext|>


<commit_before>"use strict";

const htmlparser    = require('htmlparser2'),
      fs            = require('fs'),
      path          = require('path');

class LaravelBladeParser
{
    /**
     * @param options
     */
    constructor(options)
    {
        this.html = "";
        this.defaultOptions = {
            folder: './resources/views',
            path: './resources/views/welcome.blade.php',
            regex: {
                include: /@include\(\s*[\'\"]([^\[\]\'\"]*)[\'\"]\s*(?:(?:.*[^\s\)])\s*)*\s*\)/gi,
                extends: /@extends\((?:[\'\"])(.*)(?:[\'\"])\)/gi,
                yield: /@yield\([\'\"]?([^\'\"]*)[\'\"]?\)/gi,
                multiLineSection: /@section\(\s*[\'\"]?([^\'\"]*)[\'\"]?\s*\)((?!\@stop).*\s*)*\@stop/gi,
                oneLineSection: /@section\([\'\"]([^\'\"]*)[\'\"]?\s*\,\s*[\'\"]?([^\"\']*)[\'\"]?\)/gi
            },
            encoding: 'utf8'
        };
        this.options = Object.assign(this.defaultOptions, options ? options : {});

        this._init();
    }

    /**
     * @returns {string|XML|string|void|*|*}
     */
    getHTML()
    {
        return this.html;
    }

    /**
     * @private
     */
    _init()
    {
        this.html = this._parse(this._getFileContent(this.options.path));
    }

    /**
     * @param content
     *
     * @private
     */
    _parse(content)
    {
        var template = content,
            items = {};

        template.replace(this.options.regex.extends, (match, value) => {
            let filePath = path.join(this.options.folder, value.replace(/\./gi, "/") + '.blade.php');

            return this._getFileContent(filePath);
        }).replace(this.options.regex.oneLineSection, (match, key, value) => {
            items[key] = value;

            return "";
        }).replace(this.options.regex.multiLineSection, (match, key, value) => {
            items[key] = value;

            return "";
        }).replace(this.options.regex.yield, (match, key) => {
            return typeof items[key] == "undefined" ? "" : items[key];
        }).replace(this.options.regex.include, (match, value) => {
            let filePath = path.join(this.options.folder, value.replace(/\./gi, "/") + '.blade.php'),
                html = this._getFileContent(filePath);

            return this._parse(html);
        });

        return template;
    }

    /**
     * @param filePath
     *
     * @returns {*}
     * @private
     */
    _getFileContent(filePath)
    {
        return fs.readFileSync(filePath, this.options.encoding);
    }
}

module.exports = options => new LaravelBladeParser(options).getHTML();
<commit_msg>Hotfix<commit_after>"use strict";

const htmlparser    = require('htmlparser2'),
      fs            = require('fs'),
      path          = require('path');

class LaravelBladeParser
{
    /**
     * @param options
     */
    constructor(options)
    {
        this.html = "";
        this.defaultOptions = {
            folder: './resources/views',
            path: './resources/views/welcome.blade.php',
            regex: {
                include: /@include\(\s*[\'\"]([^\[\]\'\"]*)[\'\"]\s*(?:(?:.*[^\s\)])\s*)*\s*\)/gi,
                extends: /@extends\((?:[\'\"])(.*)(?:[\'\"])\)/gi,
                yield: /@yield\([\'\"]?([^\'\"]*)[\'\"]?\)/gi,
                multiLineSection: /@section\(\s*[\'\"]?([^\'\"]*)[\'\"]?\s*\)((?!\@stop).*\s*)*\@stop/gi,
                oneLineSection: /@section\([\'\"]([^\'\"]*)[\'\"]?\s*\,\s*[\'\"]?([^\"\']*)[\'\"]?\)/gi
            },
            encoding: 'utf8'
        };
        this.options = Object.assign(this.defaultOptions, options ? options : {});

        this._init();
    }

    /**
     * @returns {string|XML|string|void|*|*}
     */
    getHTML()
    {
        return this.html;
    }

    /**
     * @private
     */
    _init()
    {
        this.html = this._parse(this._getFileContent(this.options.path));
    }

    /**
     * @param content
     *
     * @private
     */
    _parse(content)
    {
        var items = {};

        return template.replace(this.options.regex.extends, (match, value) => {
            let filePath = path.join(this.options.folder, value.replace(/\./gi, "/") + '.blade.php');

            return this._getFileContent(filePath);
        }).replace(this.options.regex.oneLineSection, (match, key, value) => {
            items[key] = value;

            return "";
        }).replace(this.options.regex.multiLineSection, (match, key, value) => {
            items[key] = value;

            return "";
        }).replace(this.options.regex.yield, (match, key) => {
            return typeof items[key] == "undefined" ? "" : items[key];
        }).replace(this.options.regex.include, (match, value) => {
            let filePath = path.join(this.options.folder, value.replace(/\./gi, "/") + '.blade.php'),
                html = this._getFileContent(filePath);

            return this._parse(html);
        });
    }

    /**
     * @param filePath
     *
     * @returns {*}
     * @private
     */
    _getFileContent(filePath)
    {
        return fs.readFileSync(filePath, this.options.encoding);
    }
}

module.exports = options => new LaravelBladeParser(options).getHTML();
<|endoftext|>