<commit_before>'use strict';

var util = require('util'),
  path = require('path'),
  slug = require('slug'),
  yeoman = require('yeoman-generator');

var BespokeGenerator = module.exports = function BespokeGenerator(args, options, config) {
  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')));
};

util.inherits(BespokeGenerator, yeoman.generators.NamedBase);

BespokeGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
    "\n" +
    "\noooooooooo.                                          oooo                          o8o          ".cyan.bold +
    "\n`888'   `Y8b                                         `888                          `\"'          ".cyan.bold +
    "\n 888     888  .ooooo.   .oooo.o oo.ooooo.   .ooooo.   888  oooo   .ooooo.         oooo  .oooo.o ".cyan.bold +
    "\n 888oooo888' d88' `88b d88(  \"8  888' `88b d88' `88b  888 .8P'   d88' `88b        `888 d88(  \"8 ".cyan.bold +
    "\n 888    `88b 888ooo888 `\"Y88b.   888   888 888   888  888888.    888ooo888         888 `\"Y88b.  ".cyan.bold +
    "\n 888    .88P 888    .o o.  )88b  888   888 888   888  888 `88b.  888    .o .o.     888 o.  )88b ".cyan.bold +
    "\no888bood8P'  `Y8bod8P' 8\"\"888P'  888bod8P' `Y8bod8P' o888o o888o `Y8bod8P' Y8P     888 8\"\"888P' ".cyan.bold +
    "\n                                 888                                               888          ".cyan.bold +
    "\n                                o888o                                          .o. 88P          ".cyan.bold +
    "\n                                                                               `Y888P           ".cyan.bold +
    "\n" +
    "Thanks for choosing Bespoke.js for your presentation! :)   -@markdalgleish".green.bold +
    "\n";

  console.log(welcome);

  var prompts = [
    {
      name: 'title',
      message: 'What is the title of your presentation?',
      'default': 'Hello World'
    },
    {
      name: 'bullets',
      message: 'Would you like bullet list support?',
      'default': 'Y/n'
    },
    {
      name: 'hash',
      message: 'Would you like hash routing support?',
      'default': 'Y/n'
    },
    {
      name: 'state',
      message: 'Would you slide-specific deck styles?',
      'default': 'Y/n'
    }
  ];

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    this.bullets = (/^y/i).test(props.bullets);
    this.hash = (/^y/i).test(props.hash);
    this.state = (/^y/i).test(props.state);
    this.title = props.title;
    this.shortName = slug(props.title).toLowerCase();

    this.bowerComponentPaths = ['bespoke.js/dist/bespoke.min.js'];
    this.bullets && this.bowerComponentPaths.push('bespoke-bullets/dist/bespoke-bullets.min.js');
    this.hash && this.bowerComponentPaths.push('bespoke-hash/dist/bespoke-hash.min.js');
    this.state && this.bowerComponentPaths.push('bespoke-state/dist/bespoke-state.min.js');

    cb();
  }.bind(this));
};

BespokeGenerator.prototype.projectFiles = function projectFiles() {
  this.template('Gruntfile.js', 'Gruntfile.js');

  this.copy('bowerrc', '.bowerrc');
  this.copy('gitignore', '.gitignore');
  this.copy('jshintrc', '.jshintrc');
}

BespokeGenerator.prototype.packageJson = function packageJson() {
  var packageJson = {
    'name': this.shortName + '-bespoke',
    'version': '0.0.0',
    'dependencies': {
      'grunt': '~0.4.1',
      'grunt-contrib-clean': '~0.4.0',
      'grunt-contrib-copy': '~0.4.1',
      'grunt-contrib-watch': '~0.5.1',
      'grunt-contrib-jade': '~0.5.0',
      'grunt-contrib-stylus': '~0.5.0',
      'grunt-contrib-connect': '~0.3.0',
      'grunt-concurrent': '~0.3.0',
      'connect-livereload': '~0.2.0'
    }
  };
  this.write('package.json', JSON.stringify(packageJson, null, 2));
};

BespokeGenerator.prototype.bowerJson = function bowerJson() {
  var bowerJson = {
    'name': this.shortName + '-bespoke',
    'version': '0.0.0',
    'dependencies': {
      'bespoke.js': '~0.2.0'
    }
  };
  if (this.bullets) bowerJson.dependencies['bespoke-bullets'] = '~0.2.0';
  if (this.hash) bowerJson.dependencies['bespoke-hash'] = '~0.1.0';
  if (this.state) bowerJson.dependencies['bespoke-state'] = '~0.2.0';
  this.write('bower.json', JSON.stringify(bowerJson, null, 2));
};

BespokeGenerator.prototype.plugins = function plugins() {
  var plugins = {};
  if (this.bullets) plugins['bullets'] = 'li, .bullet';
  if (this.hash) plugins['hash'] = true;
  if (this.state) plugins['state'] = true;
  this.hasPlugins = this.bullets || this.hash || this.state;
  this.pluginsJson = JSON.stringify(plugins, null, 2).replace(/\"/g,"'");
};

BespokeGenerator.prototype.src = function src() {
  this.mkdir('src');
  this.mkdir('src/js');
  this.mkdir('src/css');

  this.template('src/index.jade', 'src/index.jade');
  this.template('src/js/js.js', 'src/js/js.js');
  this.template('src/css/css.styl', 'src/css/css.styl');
};<commit_msg>Unquote object keys in plugins JSON output<commit_after>'use strict';

var util = require('util'),
  path = require('path'),
  slug = require('slug'),
  yeoman = require('yeoman-generator');

var BespokeGenerator = module.exports = function BespokeGenerator(args, options, config) {
  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')));
};

util.inherits(BespokeGenerator, yeoman.generators.NamedBase);

BespokeGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // welcome message
  var welcome =
    "\n" +
    "\noooooooooo.                                          oooo                          o8o          ".cyan.bold +
    "\n`888'   `Y8b                                         `888                          `\"'          ".cyan.bold +
    "\n 888     888  .ooooo.   .oooo.o oo.ooooo.   .ooooo.   888  oooo   .ooooo.         oooo  .oooo.o ".cyan.bold +
    "\n 888oooo888' d88' `88b d88(  \"8  888' `88b d88' `88b  888 .8P'   d88' `88b        `888 d88(  \"8 ".cyan.bold +
    "\n 888    `88b 888ooo888 `\"Y88b.   888   888 888   888  888888.    888ooo888         888 `\"Y88b.  ".cyan.bold +
    "\n 888    .88P 888    .o o.  )88b  888   888 888   888  888 `88b.  888    .o .o.     888 o.  )88b ".cyan.bold +
    "\no888bood8P'  `Y8bod8P' 8\"\"888P'  888bod8P' `Y8bod8P' o888o o888o `Y8bod8P' Y8P     888 8\"\"888P' ".cyan.bold +
    "\n                                 888                                               888          ".cyan.bold +
    "\n                                o888o                                          .o. 88P          ".cyan.bold +
    "\n                                                                               `Y888P           ".cyan.bold +
    "\n" +
    "Thanks for choosing Bespoke.js for your presentation! :)   -@markdalgleish".green.bold +
    "\n";

  console.log(welcome);

  var prompts = [
    {
      name: 'title',
      message: 'What is the title of your presentation?',
      'default': 'Hello World'
    },
    {
      name: 'bullets',
      message: 'Would you like bullet list support?',
      'default': 'Y/n'
    },
    {
      name: 'hash',
      message: 'Would you like hash routing support?',
      'default': 'Y/n'
    },
    {
      name: 'state',
      message: 'Would you slide-specific deck styles?',
      'default': 'Y/n'
    }
  ];

  this.prompt(prompts, function (err, props) {
    if (err) {
      return this.emit('error', err);
    }

    this.bullets = (/^y/i).test(props.bullets);
    this.hash = (/^y/i).test(props.hash);
    this.state = (/^y/i).test(props.state);
    this.title = props.title;
    this.shortName = slug(props.title).toLowerCase();

    this.bowerComponentPaths = ['bespoke.js/dist/bespoke.min.js'];
    this.bullets && this.bowerComponentPaths.push('bespoke-bullets/dist/bespoke-bullets.min.js');
    this.hash && this.bowerComponentPaths.push('bespoke-hash/dist/bespoke-hash.min.js');
    this.state && this.bowerComponentPaths.push('bespoke-state/dist/bespoke-state.min.js');

    cb();
  }.bind(this));
};

BespokeGenerator.prototype.projectFiles = function projectFiles() {
  this.template('Gruntfile.js', 'Gruntfile.js');

  this.copy('bowerrc', '.bowerrc');
  this.copy('gitignore', '.gitignore');
  this.copy('jshintrc', '.jshintrc');
}

BespokeGenerator.prototype.packageJson = function packageJson() {
  var packageJson = {
    'name': this.shortName + '-bespoke',
    'version': '0.0.0',
    'dependencies': {
      'grunt': '~0.4.1',
      'grunt-contrib-clean': '~0.4.0',
      'grunt-contrib-copy': '~0.4.1',
      'grunt-contrib-watch': '~0.5.1',
      'grunt-contrib-jade': '~0.5.0',
      'grunt-contrib-stylus': '~0.5.0',
      'grunt-contrib-connect': '~0.3.0',
      'grunt-concurrent': '~0.3.0',
      'connect-livereload': '~0.2.0'
    }
  };
  this.write('package.json', JSON.stringify(packageJson, null, 2));
};

BespokeGenerator.prototype.bowerJson = function bowerJson() {
  var bowerJson = {
    'name': this.shortName + '-bespoke',
    'version': '0.0.0',
    'dependencies': {
      'bespoke.js': '~0.2.0'
    }
  };
  if (this.bullets) bowerJson.dependencies['bespoke-bullets'] = '~0.2.0';
  if (this.hash) bowerJson.dependencies['bespoke-hash'] = '~0.1.0';
  if (this.state) bowerJson.dependencies['bespoke-state'] = '~0.2.0';
  this.write('bower.json', JSON.stringify(bowerJson, null, 2));
};

BespokeGenerator.prototype.plugins = function plugins() {
  var plugins = {};
  if (this.bullets) plugins['bullets'] = 'li, .bullet';
  if (this.hash) plugins['hash'] = true;
  if (this.state) plugins['state'] = true;
  this.hasPlugins = this.bullets || this.hash || this.state;
  this.pluginsJson = JSON.stringify(plugins, null, 2)
    .replace(/\"/g,"'") // Switch to single quotes
    .replace(/\'([a-z0-9_$]+)\'(:)/gi, '$1$2') // Unquote object keys
};

BespokeGenerator.prototype.src = function src() {
  this.mkdir('src');
  this.mkdir('src/js');
  this.mkdir('src/css');

  this.template('src/index.jade', 'src/index.jade');
  this.template('src/js/js.js', 'src/js/js.js');
  this.template('src/css/css.styl', 'src/css/css.styl');
};<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var InuitGenerator = module.exports = function InuitGenerator(args, options, config) {
  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')));
};

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

InuitGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);
  console.log('This will install the inuit css framework created by Harry Roberts with a few optional extras. For documentation and demos visit: http://inuitcss.com/');
  console.log('*** NOTE: Inuit.css requires Sass 3.2 ***\n');

  var prompts = [
    {
      type: 'confirm',
      name: 'setupSMACSS',
      message: 'SMACSS helps structure your css into manageable modules. Would you like to include it?',
      default: false
    }
  ];

  this.prompt(prompts, function (answers) {

    this.setupSMACSS = answers.setupSMACSS;

    cb();
  }.bind(this));
};

InuitGenerator.prototype.getInuit = function getInuit() {
  var cb = this.async();
  this.bowerInstall('inuit.css', { save:true });
  cb();
};

InuitGenerator.prototype.setupApp = function setupApp() {
  var cb = this.async();
  this.mkdir('css');
  this.mkdir('css/src');
  this.mkdir('img');
  this.mkdir('js');
  this.mkdir('js/src');
  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
  cb();
};

InuitGenerator.prototype.projectfiles = function projectfiles() {
  var cb = this.async();
  this.template('_vars.scss', 'css/_vars.scss');
  this.template('style.scss', 'css/style.scss');
  this.template('index.html', 'index.html');
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  cb();
};

InuitGenerator.prototype.smacssFiles = function smacssFiles() {
  if(this.setupSMACSS) {
    // add extra directories
    this.mkdir('css/src/modules');
    this.mkdir('css/src/plugins');

    // store smacss files in an array
    var smacssFiles = [
      '1-base',
      '2-layout',
      '3-states',
      '4-theme'
    ];

    var insert = '';

    // loop through smacss files
    for(var i = 0; i < smacssFiles.length; i++) {
      // copy template files over to project
      this.template('smacss/_'+ smacssFiles[i] + '.scss', 'css/src/_' + smacssFiles[i] + '.scss');
      // prepare content before updating style.scss
      if( (i + 1) === smacssFiles.length) {
        insert += '@import "src/' + smacssFiles[i] + '"\n';
      } else {
        insert += '@import "src/' + smacssFiles[i] + '",\n';
      }
    }

    // console.log("SMCASS imports: ", insert);
    // console.log('SMACSS setup complete');
    // import files into main stylesheet
    InuitGenerator.prototype._updateFile('style-hook', 'css/style.scss', insert);
  }
};

InuitGenerator.prototype._updateFile = function _updateFile(hookName, filePath, content) {
  var hook = '/*===== yeoman ' + hookName + ' =====*/',
      file = this.readFileAsString(filePath),
      insert = content;

    // console.log('hookName: ', hookName);
    // console.log('hook: ', hook);

    // console.log('filePath: ', filePath);
    // console.log('file: ', file);

    // console.log('Content: ', content);
    // console.log('insert: ', insert);

    if (file.indexOf(insert) === -1) {
      console.log('ready to add smacss imports to style.scss!!!');
      // this.write(path, file.replace(hook, insert + '\n' + hook));
    }
};

 // var routeText = [
 //        "Flight::route('GET /crudPlural', array('crudSingle_Controller','all') ); ",
 //        "Flight::route('PUT /crudSingle', array('crudSingle_Controller','create') ); ",
 //        "Flight::route('GET /crudSingle/@id', array('crudSingle_Controller','findOne') ); ",
 //        "Flight::route('POST /crudSingle/@id', array('crudSingle_Controller','update') ); ",
 //        "Flight::route('DELETE /crudSingle/@id', array('crudSingle_Controller','delete') ); ",
 //        "//RouteInsertReference"
 //     ];
 //    var indexFile = this.readFileAsString('public/index.php');
 //    indexFile = indexFile.replace('//RouteInsertReference',routeText.join('\n'));
 //    this.write('public/index.php',indexFile);<commit_msg>Worked on updating stylesheet with smacss modules (imports) if smacss option chosen<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var InuitGenerator = module.exports = function InuitGenerator(args, options, config) {
  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')));
};

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

InuitGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);
  console.log('This will install the inuit css framework created by Harry Roberts with a few optional extras. For documentation and demos visit: http://inuitcss.com/');
  console.log('*** NOTE: Inuit.css requires Sass 3.2 ***\n');

  var prompts = [
    {
      type: 'confirm',
      name: 'setupSMACSS',
      message: 'SMACSS helps structure your css into manageable modules. Would you like to include it? (This will prompt you to overwrite the style.scss file - choose yes)',
      default: false
    }
  ];

  this.prompt(prompts, function (answers) {

    this.setupSMACSS = answers.setupSMACSS;

    cb();
  }.bind(this));
};

InuitGenerator.prototype.setupApp = function setupApp() {
  var cb = this.async();
  this.mkdir('css');
  this.mkdir('css/src');
  this.mkdir('img');
  this.mkdir('js');
  this.mkdir('js/src');
  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
  cb();
};

InuitGenerator.prototype.projectfiles = function projectfiles() {
  var cb = this.async();
  this.template('_vars.scss', 'css/_vars.scss');
  this.template('style.scss', 'css/style.scss');
  this.template('index.html', 'index.html');
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  cb();
};

InuitGenerator.prototype.smacssFiles = function smacssFiles() {
  if(this.setupSMACSS) {
    // add extra directories
    this.mkdir('css/src/modules');
    this.mkdir('css/src/plugins');

    // store smacss files in an array
    var smacssFiles = [
      '1-base',
      '2-layout',
      '3-states',
      '4-theme'
    ];

    var content = "";

    // loop through smacss files
    for(var i = 0; i < smacssFiles.length; i++) {
      // copy template files over to project
      this.template('smacss/_'+ smacssFiles[i] + '.scss', 'css/src/_' + smacssFiles[i] + '.scss');
      // prepare content before updating style.scss
      if( (i + 1) === smacssFiles.length) {
        content += '@import "src/' + smacssFiles[i] + '"\n';
      } else {
        content += '@import "src/' + smacssFiles[i] + '"\n,';
      }
    }

    console.log(content);

    // import files into main stylesheet
    // InuitGenerator.prototype._updateFile('style-hook', 'css/style.scss', content);
    var hook = '/*===== yeoman style-hook =====*/',
        file = this.readFileAsString('css/style.scss'),
        newContent = content + '\n' + hook;

    if (file.indexOf(content) === -1) {
      this.write('css/style.scss', file.replace(hook, newContent));
    }
  }
};

InuitGenerator.prototype.getInuit = function getInuit() {
  var cb = this.async();
  this.bowerInstall('inuit.css', { save:true });
  cb();
};

// InuitGenerator.prototype._updateFile = function _updateFile(hookName, filePath, content) {
//   var hook = '/*===== yeoman ' + hookName + ' =====*/',
//       file = this.readFileAsString(filePath),
//       newContent = content + '\n' + hook;

//   // console.log('hookName: ', hookName);
//   console.log('filePath: ', filePath);
//   // console.log('Content: ', content);

//   console.log('hook: ', hook);
//   // console.log('file: ', file);
//   console.log('New Content: ', newContent);

//   if (file.indexOf(content) === -1) {
//     // console.log('ready to add smacss imports to style.scss!!!');
//     // this.write(filePath, file.replace(hook, newContent));
//   }
// };<|endoftext|>


<commit_before>/**
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2012
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2012, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

$('select[id=selected_firm_id]').die('change').live('change', function() {
	var firmId = $('select[id=selected_firm_id]').val();
	$.ajax({
		type: 'post',
		url: '/',
		data: {'selected_firm_id': firmId },
		success: function(data) {
			//console.log(data);
			window.location.href = '/';
		}
	});
});

$(document).ready(function(){
	$('.sprite.showhide').click( function(e){
		e.preventDefault();
		var sprite = $(this).children('span');
		var whiteBox = $(this).parents('.whiteBox');

		if(sprite.hasClass('hide')) {
			whiteBox.children('.data_row').slideUp("fast",'swing');
			sprite.removeClass('hide');
			sprite.addClass('show');
		} else {
			whiteBox.children('.data_row').slideDown("fast",'swing');
			sprite.removeClass('show');
			sprite.addClass('hide');
		}
	});

	$('.sprite.showhide2').click( function(e){
		e.preventDefault();
		var sprite = $(this).children('span');
		var small = $('div.episodeDate');
		var events = $('ul.events');

		if(sprite.hasClass('hide')) {
			events.children('li').slideUp('fast','swing');
			small.slideUp('fast','swing');
			sprite.removeClass('hide');
			sprite.addClass('show');
		} else {
			small.slideDown('fast','swing');
			events.children('li').slideDown('fast','swing',function() {
				events.children('li').map(function() {
					if ($(this).children('div:nth-child(2)').hasClass('viewing')) {
						$(this).children('div:nth-child(2)').removeClass('viewing');
						$(this).children('div:nth-child(2)').addClass('viewing');
					}
				});
			});
			sprite.removeClass('show');
			sprite.addClass('hide');
		}
	});
});
<commit_msg>slidey episodes bugfix - should only slide the current episode.<commit_after>/**
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2012
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2012, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

$('select[id=selected_firm_id]').die('change').live('change', function() {
	var firmId = $('select[id=selected_firm_id]').val();
	$.ajax({
		type: 'post',
		url: '/',
		data: {'selected_firm_id': firmId },
		success: function(data) {
			//console.log(data);
			window.location.href = '/';
		}
	});
});

$(document).ready(function(){
	$('.sprite.showhide').click( function(e){
		e.preventDefault();
		var sprite = $(this).children('span');
		var whiteBox = $(this).parents('.whiteBox');

		if(sprite.hasClass('hide')) {
			whiteBox.children('.data_row').slideUp("fast",'swing');
			sprite.removeClass('hide');
			sprite.addClass('show');
		} else {
			whiteBox.children('.data_row').slideDown("fast",'swing');
			sprite.removeClass('show');
			sprite.addClass('hide');
		}
	});

	$('.sprite.showhide2').click( function(e){
		e.preventDefault();
		var sprite = $(this).children('span');
		var small = $('div.episodeDate');
		var events = $(this).parent().parent().next('div').next('ul.events');

		if(sprite.hasClass('hide')) {
			events.children('li').slideUp('fast','swing');
			small.slideUp('fast','swing');
			sprite.removeClass('hide');
			sprite.addClass('show');
		} else {
			small.slideDown('fast','swing');
			events.children('li').slideDown('fast','swing',function() {
				events.children('li').map(function() {
					if ($(this).children('div:nth-child(2)').hasClass('viewing')) {
						$(this).children('div:nth-child(2)').removeClass('viewing');
						$(this).children('div:nth-child(2)').addClass('viewing');
					}
				});
			});
			sprite.removeClass('show');
			sprite.addClass('hide');
		}
	});
});
<|endoftext|>


<commit_before>const chalk = require('chalk');
const fs = require('fs-extra');
const notifier = require('node-notifier');
const path = require('path');
const process = require('process');
const basePath = __filename.split('/').slice(0, -1).join('/');
const projectPath = process.env.PWD;
const projectSourcePath = `${projectPath}/source`;

module.exports = {
	/**
	 * Prep a string to become file/folder name
	 *
	 * @param  {string} string
	 * @return {string}
	 */
	fileFormat(string) {
		return string.trim().replace(/\s+|_/g, '-').toLowerCase();
	},

	/**
	 * Notify through a natively available notification option
	 *
	 * @param {object} options
	 * @param {string} [type=notice]
	 * @param {boolean} [log=true]
	 */
	notify(options, type, log) {
		options.icon = __dirname + '/images/' + (type || 'notice') + '.png';
		options.group = 1;

		if (type == 'error' || type == 'fail') {
			options.group = 2;
			options.sound = true;
			options.wait = true;
		}

		if (log !== false) {
			console.log(options.message);
		}

		notifier.notify(options);

		if (type == 'fail') {
			process.exit(1);
		}
	},

	/**
	 * Log an error to the console
	 *
	 * @param {string} message
	 * @param {string} [details]
	 */
	logError(message, details) {
		console.log(
			chalk.red.bold('error: ') +
			message + ' ' + (details || '')
		);
	},

	/**
	 * Log a success message to the console
	 *
	 * @param  {string} message
	 */
	logSuccess(message) {
		console.log(chalk.green(message));
	},

	logList(name, desc) {
		console.log(
			`\n${chalk.green.bgBlack.bold(name)} - ${chalk.white.bgBlack(desc)}`
		);
	},

	paths: {
		root: basePath,
		styles: `${basePath}/styles`,
		commands: `${basePath}/commands`,
		project: {
			root: projectPath,
			source: projectSourcePath,
			styles: `${projectSourcePath}/styles`,
			scripts: `${projectSourcePath}/scripts`,
			components: `${projectSourcePath}/components`
		},
		tests: {
			root: `${basePath}/tests`,
			scripts: `${basePath}/tests/scripts`
		}
	},

	trimRight(str) {
		return str.replace(/\s+$/, '');
	},

	stripStars(line) {
	let re = /^(?:\s*[\*]{1,2}\s)/;
		return this.trimRight(line.replace(re, ''));
	}
};<commit_msg>Update fileFormat utility function<commit_after>const chalk = require('chalk');
const fs = require('fs-extra');
const notifier = require('node-notifier');
const path = require('path');
const process = require('process');
const basePath = __filename.split('/').slice(0, -1).join('/');
const projectPath = process.env.PWD;
const projectSourcePath = `${projectPath}/source`;

module.exports = {
	/**
	 * Prep a string to become file/folder name
	 *
	 * @param  {string} string
	 * @return {string}
	 */
	fileFormat(string) {
		return string.trim().replace(/[^A-Za-z0-9]/g, '-').toLowerCase();
	},

	/**
	 * Notify through a natively available notification option
	 *
	 * @param {object} options
	 * @param {string} [type=notice]
	 * @param {boolean} [log=true]
	 */
	notify(options, type, log) {
		options.icon = __dirname + '/images/' + (type || 'notice') + '.png';
		options.group = 1;

		if (type == 'error' || type == 'fail') {
			options.group = 2;
			options.sound = true;
			options.wait = true;
		}

		if (log !== false) {
			console.log(options.message);
		}

		notifier.notify(options);

		if (type == 'fail') {
			process.exit(1);
		}
	},

	/**
	 * Log an error to the console
	 *
	 * @param {string} message
	 * @param {string} [details]
	 */
	logError(message, details) {
		console.log(
			chalk.red.bold('error: ') +
			message + ' ' + (details || '')
		);
	},

	/**
	 * Log a success message to the console
	 *
	 * @param  {string} message
	 */
	logSuccess(message) {
		console.log(chalk.green(message));
	},

	logList(name, desc) {
		console.log(
			`\n${chalk.green.bgBlack.bold(name)} - ${chalk.white.bgBlack(desc)}`
		);
	},

	paths: {
		root: basePath,
		styles: `${basePath}/styles`,
		commands: `${basePath}/commands`,
		project: {
			root: projectPath,
			source: projectSourcePath,
			styles: `${projectSourcePath}/styles`,
			scripts: `${projectSourcePath}/scripts`,
			components: `${projectSourcePath}/components`
		},
		tests: {
			root: `${basePath}/tests`,
			scripts: `${basePath}/tests/scripts`
		}
	},

	trimRight(str) {
		return str.replace(/\s+$/, '');
	},

	stripStars(line) {
	let re = /^(?:\s*[\*]{1,2}\s)/;
		return this.trimRight(line.replace(re, ''));
	}
};<|endoftext|>


<commit_before>const {
  app, screen, ipcMain, BrowserWindow,
} = require('electron');

const { arch, platform, release } = require('os');
const { resolve } = require('path');
const { parseInline } = require('marked');

const Calendar = require('./components/Calendar');
const Clock = require('./components/Clock');
const Locale = require('./components/Locale');
const Logger = require('./components/Logger');
const Preferences = require('./components/Preferences');
const SystemTray = require('./components/SystemTray');
const Updater = require('./components/Updater');
const { PREFERENCES_CHANGED } = require('./views/preferences/ipc');
const { integratedBackgroundsDirectory } = require('./paths');

const {
  APP_QUIT,
  APP_RESIZE_WINDOW,
  APP_RESTART,
  APP_TRANSLATE,
  APP_UPDATE_DOWNLOADED,
} = require('./ipc');

const defaultPreferences = {
  calendarBackground: resolve(integratedBackgroundsDirectory, 'empty.svg'),
  calendarLegendFormat: 'MM / y',
  clockFormat: 'Pp',
  openAtLogin: false,
};

(async () => {
  await app.whenReady();

  app.dock.hide();

  return new class {
    constructor() {
      const currentVersion = app.getVersion();

      this.logger = new Logger();

      this.logger.debug(`Starting Timestamp v${currentVersion} on “${platform()}-${arch()} v${release()}”.`);
      this.logger.debug(`Running in ${app.isPackaged ? 'production' : 'development'} mode.`);

      if (app.isPackaged) {
        this.updater = new Updater({
          currentVersion,
          feedUrl: 'https://mzdr.github.io/timestamp/update.json',
          logger: this.logger,
          onUpdateDownloaded: this.onUpdateDownloaded.bind(this),
        });
      }

      this.locale = new Locale({
        logger: this.logger,
        preferred: app.getLocale(),
      });

      this.tray = new SystemTray({
        logger: this.logger,
        onClick: this.onTrayClicked.bind(this),
      });

      this.clock = new Clock({
        format: defaultPreferences.clockFormat,
        locale: this.locale,
        onTick: this.tray.setLabel.bind(this.tray),
      });

      this.calendar = new Calendar({
        locale: this.locale,
        logger: this.logger,
      });

      this.preferences = new Preferences({
        defaults: defaultPreferences,
        logger: this.logger,
        onChange: this.onPreferencesChanged.bind(this),
      });

      ipcMain.on(APP_QUIT, () => app.exit());
      ipcMain.on(APP_RESTART, this.onRestart.bind(this));
      ipcMain.on(APP_RESIZE_WINDOW, this.onResizeWindow.bind(this));
      ipcMain.handle(APP_TRANSLATE, this.onTranslate.bind(this));
    }

    onRestart() {
      if (this.updater === undefined) {
        return this;
      }

      this.calendar.window.destroy();
      this.preferences.window.destroy();
      this.updater.quitAndInstall();

      return this;
    }

    onResizeWindow({ sender }, { width, height }) {
      const { calendar, preferences } = this;
      const window = BrowserWindow.fromWebContents(sender);

      [calendar, preferences]
        .find((view) => view.window.isSame(window))
        .window
        .setContentSize(width, height);
    }

    onPreferencesChanged(key, value) {
      if (key === 'openAtLogin') {
        app.setLoginItemSettings({ openAtLogin: value });
      } else if (key === 'clockFormat') {
        this.clock.setFormat(value);
      } else if (/^calendar/.test(key)) {
        this.calendar.window.getWebContents().send(PREFERENCES_CHANGED, key, value);
      }

      return this;
    }

    onTranslate(event, key, options = {}) {
      const { markdown = false } = options;
      const translation = this.locale.translate(key);

      if (markdown) {
        return parseInline(translation);
      }

      return translation;
    }

    onTrayClicked() {
      const { calendar, tray } = this;
      const bounds = tray.getBounds();
      const currentMousePosition = screen.getCursorScreenPoint();
      const currentDisplay = screen.getDisplayNearestPoint(currentMousePosition);
      const yOffset = 6;

      // Always center calendar window relative to tray icon
      calendar
        .window
        .setPosition(bounds.x + (bounds.width / 2), currentDisplay.workArea.y + yOffset)
        .toggleVisibility();
    }

    onUpdateDownloaded() {
      this.tray.setPrefix('→ ');
      this.preferences.window.getWebContents().send(APP_UPDATE_DOWNLOADED);
      this.calendar.window.getWebContents().send(APP_UPDATE_DOWNLOADED);
    }
  }();
})();
<commit_msg>chore: use more sensible defaults<commit_after>const {
  app, screen, ipcMain, BrowserWindow,
} = require('electron');

const { arch, platform, release } = require('os');
const { resolve } = require('path');
const { parseInline } = require('marked');

const Calendar = require('./components/Calendar');
const Clock = require('./components/Clock');
const Locale = require('./components/Locale');
const Logger = require('./components/Logger');
const Preferences = require('./components/Preferences');
const SystemTray = require('./components/SystemTray');
const Updater = require('./components/Updater');
const { PREFERENCES_CHANGED } = require('./views/preferences/ipc');
const { integratedBackgroundsDirectory } = require('./paths');

const {
  APP_QUIT,
  APP_RESIZE_WINDOW,
  APP_RESTART,
  APP_TRANSLATE,
  APP_UPDATE_DOWNLOADED,
} = require('./ipc');

const defaultPreferences = {
  calendarBackground: resolve(integratedBackgroundsDirectory, 'empty.svg'),
  calendarLegendFormat: 'MMM y',
  clockFormat: 'PPPP',
  openAtLogin: false,
};

(async () => {
  await app.whenReady();

  app.dock.hide();

  return new class {
    constructor() {
      const currentVersion = app.getVersion();

      this.logger = new Logger();

      this.logger.debug(`Starting Timestamp v${currentVersion} on “${platform()}-${arch()} v${release()}”.`);
      this.logger.debug(`Running in ${app.isPackaged ? 'production' : 'development'} mode.`);

      if (app.isPackaged) {
        this.updater = new Updater({
          currentVersion,
          feedUrl: 'https://mzdr.github.io/timestamp/update.json',
          logger: this.logger,
          onUpdateDownloaded: this.onUpdateDownloaded.bind(this),
        });
      }

      this.locale = new Locale({
        logger: this.logger,
        preferred: app.getLocale(),
      });

      this.tray = new SystemTray({
        logger: this.logger,
        onClick: this.onTrayClicked.bind(this),
      });

      this.clock = new Clock({
        format: defaultPreferences.clockFormat,
        locale: this.locale,
        onTick: this.tray.setLabel.bind(this.tray),
      });

      this.calendar = new Calendar({
        locale: this.locale,
        logger: this.logger,
      });

      this.preferences = new Preferences({
        defaults: defaultPreferences,
        logger: this.logger,
        onChange: this.onPreferencesChanged.bind(this),
      });

      ipcMain.on(APP_QUIT, () => app.exit());
      ipcMain.on(APP_RESTART, this.onRestart.bind(this));
      ipcMain.on(APP_RESIZE_WINDOW, this.onResizeWindow.bind(this));
      ipcMain.handle(APP_TRANSLATE, this.onTranslate.bind(this));
    }

    onRestart() {
      if (this.updater === undefined) {
        return this;
      }

      this.calendar.window.destroy();
      this.preferences.window.destroy();
      this.updater.quitAndInstall();

      return this;
    }

    onResizeWindow({ sender }, { width, height }) {
      const { calendar, preferences } = this;
      const window = BrowserWindow.fromWebContents(sender);

      [calendar, preferences]
        .find((view) => view.window.isSame(window))
        .window
        .setContentSize(width, height);
    }

    onPreferencesChanged(key, value) {
      if (key === 'openAtLogin') {
        app.setLoginItemSettings({ openAtLogin: value });
      } else if (key === 'clockFormat') {
        this.clock.setFormat(value);
      } else if (/^calendar/.test(key)) {
        this.calendar.window.getWebContents().send(PREFERENCES_CHANGED, key, value);
      }

      return this;
    }

    onTranslate(event, key, options = {}) {
      const { markdown = false } = options;
      const translation = this.locale.translate(key);

      if (markdown) {
        return parseInline(translation);
      }

      return translation;
    }

    onTrayClicked() {
      const { calendar, tray } = this;
      const bounds = tray.getBounds();
      const currentMousePosition = screen.getCursorScreenPoint();
      const currentDisplay = screen.getDisplayNearestPoint(currentMousePosition);
      const yOffset = 6;

      // Always center calendar window relative to tray icon
      calendar
        .window
        .setPosition(bounds.x + (bounds.width / 2), currentDisplay.workArea.y + yOffset)
        .toggleVisibility();
    }

    onUpdateDownloaded() {
      this.tray.setPrefix('→ ');
      this.preferences.window.getWebContents().send(APP_UPDATE_DOWNLOADED);
      this.calendar.window.getWebContents().send(APP_UPDATE_DOWNLOADED);
    }
  }();
})();
<|endoftext|>


<commit_before>var express, app, logger, cookieParser, bodyParser, cors,
contact, expressJWT, jwt;

express = require('express');
logger = require('morgan');
cookieParser = require('cookie-parser');
bodyParser = require('body-parser');
cors = require('cors');
expressJWT = require('express-jwt');
jwt = require('jsonwebtoken');

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

app = express();

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressJWT({ secret: 'w3c porra' }).unless({ path: ['/contact'] }));

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

contact = require('../server/routes/contact.js');

app.use('/contact', contact);

// 404
app.use(function(req, res, next) {
  var err;

  err = new Error('Not Found');
  err.status = 404;

  next(err);
});

// error handler
app.use(function(err, req, res, next) {

  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<commit_msg>Comenta o código responsável pela autenticação jwt.<commit_after>var express, app, logger, cookieParser, bodyParser, cors,
contact, expressJWT, jwt;

express = require('express');
logger = require('morgan');
cookieParser = require('cookie-parser');
bodyParser = require('body-parser');
cors = require('cors');
// expressJWT = require('express-jwt');
// jwt = require('jsonwebtoken');

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

app = express();

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// app.use(expressJWT({ secret: 'w3c porra' }).unless({ path: ['/contact'] }));

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

contact = require('../server/routes/contact.js');

app.use('/contact', contact);

// 404
app.use(function(req, res, next) {
  var err;

  err = new Error('Not Found');
  err.status = 404;

  next(err);
});

// error handler
app.use(function(err, req, res, next) {

  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<|endoftext|>


<commit_before>var nameChecker = (function() {
  'use strict';
  // CHECK LENGTH
  var lengthCheck = function(target) {
    return target.length;
  };
  // MAXIMUM lENGTH
  var maxLength = function(target, max) {
    return lengthCheck(target) > max;
  };
  // REPLACE LETTER
  var replaceLetter = function(string, options) {
    var value = string;
    var regex;
    for (var letter in options) {
      if (options.hasOwnProperty(letter)) {
        regex = new RegExp(letter, 'g');
        value = value.replace(regex, options[letter]);
      }
    }
    return value;
  };
  //REPLACE UMLAUTS
  var replaceUmlauts = function(string) {
    return replaceLetter(string, {
      '\u00c4': 'Ae',
      '\u00d6': 'Oe',
      '\u00dc': 'ue',
      '\u00e4': 'ae',
      '\u00f6': 'oe',
      '\u00fc': 'ue',
      '\u00df': 'ss',
    });
  };
  //REPLACE SLASHES
  var replaceSlashes = function(string) {
    return replaceLetter(string, {
      '/': '%2F'
    });
  };
  //GENERATE TRANSLATE LINK
  var translateLink = function(string) {
    return 'https://translate.google.com/#auto/en/' + replaceSlashes(encodeURI(removeBreaks(string)));
  };
  //REMOVE PARENS
  var removeParens = function(string) {
    return replaceLetter(string, {
      '[()]': ''
    });
  };
  //REMOVE LINE BREAKS
  var removeBreaks = function(string) {
    return replaceLetter(string, {
      '\n': ' '
    });
  };
  // ADD CLASSES
  var addShareClasses = function(name, sClasses) {
    var output = [];
    for (var i = 0; i < sClasses.length; i++) {
      if (sClasses[i] !== '') {
        output.push(name + ' ' + sClasses[i]);
      }
    }
    return output;
  };
  var shortenName = function(name, shareClasses, rulesUns, lengths) {
    var rulesTemp = Object.keys(rulesUns).sort(function(a, b) {
      return name.lastIndexOf(a) - name.lastIndexOf(b);
    });
    var rules = {};
    for (var i = 0; i < rulesTemp.length; i++) {
      rules[rulesTemp[i]] = rulesUns[rulesTemp[i]]
    }
    var shortenedNames = [];
    // add share classes for length calculation
    var nameWithShareclasses = addShareClasses(name, shareClasses);
    // find out longest possible name (with sc if any)
    var longest = name;
    if (nameWithShareclasses.length > 0) {
      longest = nameWithShareclasses.reduce(function(a, b) {
        return a.length > b.length ? a : b;
      });
    }
    // max length of share class to add
    var maxShareClassLen = longest.length - name.length;
    // lengths to shorten name to
    var shortenToLen = lengths.map(function(e) {
      return e - maxShareClassLen;
    });
    var x = 0;
    // shortening algorithm
    var algorithm = function(value, options, maxlen) {
      var len = value.length;
      if (len <= maxlen) {
        return value;
      } else {
        var newvalue = value;
        for (var prop in options) {
          if (options.hasOwnProperty(prop) && prop.length > options[prop].length) {
						var regex = new Regex(prop, 'gi')
            var pos = value.lastIndexOf(prop);
            if (pos > -1) {
              var oldstring = newvalue.substring(0, pos);
              var newstring = newvalue.substring(pos);
              newstring = newstring.replace(prop, options[prop]);
              newvalue = oldstring + newstring;
              newvalue = algorithm(newvalue, options, maxlen);
            };
          }
        }
        return newvalue;
      }
    };
    // shortening algorithm END
    // output
    for (var i = 0; i < shortenToLen.length; i++) {
      var short = algorithm(name, rules, shortenToLen[i]);
      shortenedNames.push(short);
    }
    return shortenedNames;
  };
  var shortenProcess = function(name, options, rules, shareClasses, lengths) {
    var shortenedName = name;
    // remove parentheses
    shortenedName = options.removeParens ? removeParens(shortenedName) : shortenedName;
    // replace umlauts
    shortenedName = options.replaceUmlauts ? replaceUmlauts(shortenedName) : shortenedName;
    // shorten name
    shortenedName = options.shortenName ? shortenName(shortenedName, shareClasses, rules, lengths) : [shortenedName, shortenedName, shortenedName];
    return {
      shortenedName: shortenedName[0],
      shortenedNameShort: shortenedName[1],
      shortenedNameInHouse: shortenedName[2],
    };
  };
  //RETURN OBJECT
  return {
    lengthCheck: lengthCheck,
    replaceUmlauts: replaceUmlauts,
    removeParens: removeParens,
    maxLength: maxLength,
    removeBreaks: removeBreaks,
    translateLink: translateLink,
    addShareClasses: addShareClasses,
    shortenProcess: shortenProcess
  };
}());
//-----------------------------------------------------------
(function init(lengths) {
  'use strict';
  // SELECTOR
  var $ = function(el) {
    return document.querySelector(el);
  };
  var displayLength = function(input, output, max) {
    output.innerHTML = nameChecker.lengthCheck(input);
    if (nameChecker.maxLength(input, max)) {
      if (!output.classList.contains('warning')) {
        output.classList.add('warning');
      }
    } else {
      if (output.classList.contains('warning')) {
        output.classList.remove('warning');
      }
    }
  };

  function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  }

  function addShareClasses(name, sClassesIn, output, max) {
    var sClasses = sClassesIn.value.length > 0 ? sClassesIn.value.split('\n') : [];
    while (output.firstChild) {
      output.removeChild(output.firstChild);
    }
    let classesOutput = nameChecker.addShareClasses(name, sClasses);
    for (let i = 0; i < classesOutput.length; i++) {
      let lenId = output.id + '_' + i;
      let newShareClass = document.createElement('li');
      newShareClass.setAttribute('tabIndex', '0');
      newShareClass.setAttribute('contentEditable', 'true');
      let newShareClassText = document.createTextNode(classesOutput[i]);
      newShareClass.appendChild(newShareClassText);
      let newShareClassLen = document.createElement('span');
      newShareClassLen.setAttribute('id', lenId);
      newShareClassLen.setAttribute('data-tooltip', "Copy");
      displayLength(newShareClassText, newShareClassLen, max);
      output.appendChild(newShareClass);
      output.appendChild(newShareClassLen);
      newShareClassLen.addEventListener('click', function() {
        selectElementContents(newShareClass);
        try {
          let success = document.execCommand('copy');
          let msg = success ? 'successful' : 'unsuccessful';
          console.log('Copying text command was ' + msg);
        } catch (e) {
          console.log('Unable to copy!');
        }
      })
    }
  }
  // EVENT LISTENERS
  var inputName = $('#inputName'), // INITIAL NAME INPUT
    outputName = $('#outputName'), // PROCESSED NAME OUTPUT
    outputShortName = $('#outputShortName'), // PROCESSED SHORT NAME OUTPUT
    outputInHouseName = $('#outputInHouseName'), // PROCESSED IN HOUSE NAME OUTPUT
    lenName = $('#lenName'), // NAME LENGTH
    inputObj = $('#inputObj'), // OBJECTIVE INPUT
    lenObj = $('#lenObj'), // OBJECTIVE LENGTH
    showRules = $('#showRules'), // RULES BUTTON
    divRules = $('.rules'), // RULES LIST
    shareClassesOutput = $('#shareClassesOutput'), // NAME WITH SC OUTPUT
    shareClassesShortOutput = $('#shareClassesShortOutput'), // SHORT NAME WITH SC OUTPUT
    shareClassesInHouseOutput = $('#shareClassesInHouseOutput'), // IN HOUSE NAME WITH SC OUTPUT
    shareClassesInput = $('#shareClasses'); // SHARE CLASSES INPUT
  function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'js/rules.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function() {
      if (xobj.readyState == 4 && xobj.status == "200") {
        // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
        callback(xobj.responseText);
      }
    };
    xobj.send(null);
  };
  var rules;
  loadJSON(function(response) {
    // Parse JSON string into object
    rules = JSON.parse(response);
  });
  // var rules = {
  //   'Pioneer': 'Pio',
  //   'Eastern': 'Ea',
  //   'Funds': 'Fd',
  //   'Stock': 'Stk',
  //   'long': 'ln',
  //   'bong': 'bn',
  //   'brain': 'brainananakjshfdkjdszh;',
  //   'Europe': 'Eur',
  //   'Austria': 'Aut',
  //   'a1': 'b',
  //   'a2': 'b',
  //   'a3': 'b',
  //   'a4': 'b',
  //   'a5': 'b',
  //   'a6': 'b',
  //   'a7': 'b',
  //   'a8': 'b',
  // };
  var displayAndAdd = function(output, lenout, lennum, shareClassesOutput) {
    var value = output.value;
    var length = lengths[lennum];
    displayLength(value, lenout, length);
    addShareClasses(value, shareClassesInput, shareClassesOutput, length);
  }
  inputName.addEventListener('input', function(e) {
    displayLength(inputName.value, lenName, lengths[0]);
  });
  outputName.addEventListener('input', function(e) {
    displayAndAdd(outputName, lenOutputName, 0, shareClassesOutput);
  });
  outputShortName.addEventListener('input', function(e) {
    displayAndAdd(outputShortName, lenOutputShortName, 1, shareClassesOutputShort);
  });
  outputInHouseName.addEventListener('input', function(e) {
    displayAndAdd(outputInHouseName, lenOutputInHouseName, 2, shareClassesOutputInHouse);
  });
  $('#buttonShorten').addEventListener('click', function(e) {
    var value = inputName.value;
    var options = {};
    options.replaceUmlauts = $('input[name="removeSpecial"]').checked;
    options.removeParens = $('input[name="removeParens"]').checked;
    options.shortenName = $('input[name="shortenNames"]').checked;
    var sClasses = shareClassesInput.value.length > 0 ? shareClassesInput.value.split('\n') : [];
    var shortened = nameChecker.shortenProcess(value, options, rules, sClasses, lengths);
    outputName.value = shortened.shortenedName;
    outputShortName.value = shortened.shortenedNameShort;
    outputInHouseName.value = shortened.shortenedNameInHouse;
    displayAndAdd(outputName, lenOutputName, 0, shareClassesOutput);
    displayAndAdd(outputShortName, lenOutputShortName, 1, shareClassesOutputShort);
    displayAndAdd(outputInHouseName, lenOutputInHouseName, 2, shareClassesOutputInHouse);
  });
  //OBJECTIVE
  inputObj.addEventListener('input', function(e) {
    displayLength(inputObj.value, lenObj, 2000);
    $('#linkTranslate').href = nameChecker.translateLink(inputObj.value);
  });
  $('#buttonObjUmlauts').addEventListener('click', function(e) {
    inputObj.value = nameChecker.replaceUmlauts(inputObj.value);
    displayLength(inputObj.value, lenObj, 2000);
    inputObj.select();
  });
  $('#buttonObjBreaks').addEventListener('click', function(e) {
    inputObj.value = nameChecker.removeBreaks(inputObj.value);
    displayLength(inputObj.value, lenObj, 2000);
    inputObj.select();
  });
  showRules.addEventListener('click', function(e) {
    if (!divRules.classList.contains('show')) {
      divRules.classList.add('show');
    } else {
      divRules.classList.remove('show');
    }
  });
  var comfyText = (function() {
    shareClassesInput.addEventListener('input', autoExpand);

    function autoExpand(e, el) {
      var el = el || e.target;
      el.style.height = 'inherit';
      el.style.height = (el.scrollHeight + 4) + 'px';
    }
  })();
}([50, 30, 40]));
<commit_msg>case insensitivity<commit_after>var nameChecker = (function() {
  'use strict';
  // CHECK LENGTH
  var lengthCheck = function(target) {
    return target.length;
  };
  // MAXIMUM lENGTH
  var maxLength = function(target, max) {
    return lengthCheck(target) > max;
  };
  // REPLACE LETTER
  var replaceLetter = function(string, options) {
    var value = string;
    var regex;
    for (var letter in options) {
      if (options.hasOwnProperty(letter)) {
        regex = new RegExp(letter, 'g');
        value = value.replace(regex, options[letter]);
      }
    }
    return value;
  };
  //REPLACE UMLAUTS
  var replaceUmlauts = function(string) {
    return replaceLetter(string, {
      '\u00c4': 'Ae',
      '\u00d6': 'Oe',
      '\u00dc': 'ue',
      '\u00e4': 'ae',
      '\u00f6': 'oe',
      '\u00fc': 'ue',
      '\u00df': 'ss',
    });
  };
  //REPLACE SLASHES
  var replaceSlashes = function(string) {
    return replaceLetter(string, {
      '/': '%2F'
    });
  };
  //GENERATE TRANSLATE LINK
  var translateLink = function(string) {
    return 'https://translate.google.com/#auto/en/' + replaceSlashes(encodeURI(removeBreaks(string)));
  };
  //REMOVE PARENS
  var removeParens = function(string) {
    return replaceLetter(string, {
      '[()]': ''
    });
  };
  //REMOVE LINE BREAKS
  var removeBreaks = function(string) {
    return replaceLetter(string, {
      '\n': ' '
    });
  };
  // ADD CLASSES
  var addShareClasses = function(name, sClasses) {
    var output = [];
    for (var i = 0; i < sClasses.length; i++) {
      if (sClasses[i] !== '') {
        output.push(name + ' ' + sClasses[i]);
      }
    }
    return output;
  };
  var shortenName = function(name, shareClasses, rulesUns, lengths) {
    var rulesTemp = Object.keys(rulesUns).sort(function(a, b) {
      return name.lastIndexOf(a) - name.lastIndexOf(b);
    });
    var rules = {};
    for (var i = 0; i < rulesTemp.length; i++) {
      rules[rulesTemp[i]] = rulesUns[rulesTemp[i]]
    }
    var shortenedNames = [];
    // add share classes for length calculation
    var nameWithShareclasses = addShareClasses(name, shareClasses);
    // find out longest possible name (with sc if any)
    var longest = name;
    if (nameWithShareclasses.length > 0) {
      longest = nameWithShareclasses.reduce(function(a, b) {
        return a.length > b.length ? a : b;
      });
    }
    // max length of share class to add
    var maxShareClassLen = longest.length - name.length;
    // lengths to shorten name to
    var shortenToLen = lengths.map(function(e) {
      return e - maxShareClassLen;
    });
    var x = 0;
    // shortening algorithm
    var algorithm = function(value, options, maxlen) {
      var len = value.length;
      if (len <= maxlen) {
        return value;
      } else {
        var newvalue = value;
        for (var prop in options) {
          if (options.hasOwnProperty(prop) && prop.length > options[prop].length) {
						var regex = new Regex(prop, 'gi')
            var pos = value.lastIndexOf(prop);
            if (pos > -1) {
              var oldstring = newvalue.substring(0, pos);
              var newstring = newvalue.substring(pos);
              newstring = newstring.replace(regex, options[prop]);
              newvalue = oldstring + newstring;
              newvalue = algorithm(newvalue, options, maxlen);
            };
          }
        }
        return newvalue;
      }
    };
    // shortening algorithm END
    // output
    for (var i = 0; i < shortenToLen.length; i++) {
      var short = algorithm(name, rules, shortenToLen[i]);
      shortenedNames.push(short);
    }
    return shortenedNames;
  };
  var shortenProcess = function(name, options, rules, shareClasses, lengths) {
    var shortenedName = name;
    // remove parentheses
    shortenedName = options.removeParens ? removeParens(shortenedName) : shortenedName;
    // replace umlauts
    shortenedName = options.replaceUmlauts ? replaceUmlauts(shortenedName) : shortenedName;
    // shorten name
    shortenedName = options.shortenName ? shortenName(shortenedName, shareClasses, rules, lengths) : [shortenedName, shortenedName, shortenedName];
    return {
      shortenedName: shortenedName[0],
      shortenedNameShort: shortenedName[1],
      shortenedNameInHouse: shortenedName[2],
    };
  };
  //RETURN OBJECT
  return {
    lengthCheck: lengthCheck,
    replaceUmlauts: replaceUmlauts,
    removeParens: removeParens,
    maxLength: maxLength,
    removeBreaks: removeBreaks,
    translateLink: translateLink,
    addShareClasses: addShareClasses,
    shortenProcess: shortenProcess
  };
}());
//-----------------------------------------------------------
(function init(lengths) {
  'use strict';
  // SELECTOR
  var $ = function(el) {
    return document.querySelector(el);
  };
  var displayLength = function(input, output, max) {
    output.innerHTML = nameChecker.lengthCheck(input);
    if (nameChecker.maxLength(input, max)) {
      if (!output.classList.contains('warning')) {
        output.classList.add('warning');
      }
    } else {
      if (output.classList.contains('warning')) {
        output.classList.remove('warning');
      }
    }
  };

  function selectElementContents(el) {
    var range = document.createRange();
    range.selectNodeContents(el);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  }

  function addShareClasses(name, sClassesIn, output, max) {
    var sClasses = sClassesIn.value.length > 0 ? sClassesIn.value.split('\n') : [];
    while (output.firstChild) {
      output.removeChild(output.firstChild);
    }
    let classesOutput = nameChecker.addShareClasses(name, sClasses);
    for (let i = 0; i < classesOutput.length; i++) {
      let lenId = output.id + '_' + i;
      let newShareClass = document.createElement('li');
      newShareClass.setAttribute('tabIndex', '0');
      newShareClass.setAttribute('contentEditable', 'true');
      let newShareClassText = document.createTextNode(classesOutput[i]);
      newShareClass.appendChild(newShareClassText);
      let newShareClassLen = document.createElement('span');
      newShareClassLen.setAttribute('id', lenId);
      newShareClassLen.setAttribute('data-tooltip', "Copy");
      displayLength(newShareClassText, newShareClassLen, max);
      output.appendChild(newShareClass);
      output.appendChild(newShareClassLen);
      newShareClassLen.addEventListener('click', function() {
        selectElementContents(newShareClass);
        try {
          let success = document.execCommand('copy');
          let msg = success ? 'successful' : 'unsuccessful';
          console.log('Copying text command was ' + msg);
        } catch (e) {
          console.log('Unable to copy!');
        }
      })
    }
  }
  // EVENT LISTENERS
  var inputName = $('#inputName'), // INITIAL NAME INPUT
    outputName = $('#outputName'), // PROCESSED NAME OUTPUT
    outputShortName = $('#outputShortName'), // PROCESSED SHORT NAME OUTPUT
    outputInHouseName = $('#outputInHouseName'), // PROCESSED IN HOUSE NAME OUTPUT
    lenName = $('#lenName'), // NAME LENGTH
    inputObj = $('#inputObj'), // OBJECTIVE INPUT
    lenObj = $('#lenObj'), // OBJECTIVE LENGTH
    showRules = $('#showRules'), // RULES BUTTON
    divRules = $('.rules'), // RULES LIST
    shareClassesOutput = $('#shareClassesOutput'), // NAME WITH SC OUTPUT
    shareClassesShortOutput = $('#shareClassesShortOutput'), // SHORT NAME WITH SC OUTPUT
    shareClassesInHouseOutput = $('#shareClassesInHouseOutput'), // IN HOUSE NAME WITH SC OUTPUT
    shareClassesInput = $('#shareClasses'); // SHARE CLASSES INPUT
  function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'js/rules.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function() {
      if (xobj.readyState == 4 && xobj.status == "200") {
        // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
        callback(xobj.responseText);
      }
    };
    xobj.send(null);
  };
  var rules;
  loadJSON(function(response) {
    // Parse JSON string into object
    rules = JSON.parse(response);
  });
  // var rules = {
  //   'Pioneer': 'Pio',
  //   'Eastern': 'Ea',
  //   'Funds': 'Fd',
  //   'Stock': 'Stk',
  //   'long': 'ln',
  //   'bong': 'bn',
  //   'brain': 'brainananakjshfdkjdszh;',
  //   'Europe': 'Eur',
  //   'Austria': 'Aut',
  //   'a1': 'b',
  //   'a2': 'b',
  //   'a3': 'b',
  //   'a4': 'b',
  //   'a5': 'b',
  //   'a6': 'b',
  //   'a7': 'b',
  //   'a8': 'b',
  // };
  var displayAndAdd = function(output, lenout, lennum, shareClassesOutput) {
    var value = output.value;
    var length = lengths[lennum];
    displayLength(value, lenout, length);
    addShareClasses(value, shareClassesInput, shareClassesOutput, length);
  }
  inputName.addEventListener('input', function(e) {
    displayLength(inputName.value, lenName, lengths[0]);
  });
  outputName.addEventListener('input', function(e) {
    displayAndAdd(outputName, lenOutputName, 0, shareClassesOutput);
  });
  outputShortName.addEventListener('input', function(e) {
    displayAndAdd(outputShortName, lenOutputShortName, 1, shareClassesOutputShort);
  });
  outputInHouseName.addEventListener('input', function(e) {
    displayAndAdd(outputInHouseName, lenOutputInHouseName, 2, shareClassesOutputInHouse);
  });
  $('#buttonShorten').addEventListener('click', function(e) {
    var value = inputName.value;
    var options = {};
    options.replaceUmlauts = $('input[name="removeSpecial"]').checked;
    options.removeParens = $('input[name="removeParens"]').checked;
    options.shortenName = $('input[name="shortenNames"]').checked;
    var sClasses = shareClassesInput.value.length > 0 ? shareClassesInput.value.split('\n') : [];
    var shortened = nameChecker.shortenProcess(value, options, rules, sClasses, lengths);
    outputName.value = shortened.shortenedName;
    outputShortName.value = shortened.shortenedNameShort;
    outputInHouseName.value = shortened.shortenedNameInHouse;
    displayAndAdd(outputName, lenOutputName, 0, shareClassesOutput);
    displayAndAdd(outputShortName, lenOutputShortName, 1, shareClassesOutputShort);
    displayAndAdd(outputInHouseName, lenOutputInHouseName, 2, shareClassesOutputInHouse);
  });
  //OBJECTIVE
  inputObj.addEventListener('input', function(e) {
    displayLength(inputObj.value, lenObj, 2000);
    $('#linkTranslate').href = nameChecker.translateLink(inputObj.value);
  });
  $('#buttonObjUmlauts').addEventListener('click', function(e) {
    inputObj.value = nameChecker.replaceUmlauts(inputObj.value);
    displayLength(inputObj.value, lenObj, 2000);
    inputObj.select();
  });
  $('#buttonObjBreaks').addEventListener('click', function(e) {
    inputObj.value = nameChecker.removeBreaks(inputObj.value);
    displayLength(inputObj.value, lenObj, 2000);
    inputObj.select();
  });
  showRules.addEventListener('click', function(e) {
    if (!divRules.classList.contains('show')) {
      divRules.classList.add('show');
    } else {
      divRules.classList.remove('show');
    }
  });
  var comfyText = (function() {
    shareClassesInput.addEventListener('input', autoExpand);

    function autoExpand(e, el) {
      var el = el || e.target;
      el.style.height = 'inherit';
      el.style.height = (el.scrollHeight + 4) + 'px';
    }
  })();
}([50, 30, 40]));
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    fs = require('fs'),
    logger = require('./logger'),
    webpack = require('webpack'),
    ExtractTextPlugin = require('extract-text-webpack-plugin'),
    config = require('./config'),
    babel = require('./babel');

class Utils {

    /**
     * load webpack:
     *     @task dev: add dev-server and enable HMR, according to mock config, enable mock
     *     @task release: add uglifyjs
     * @return config
     */
    loadWebpackCfg(target, args) {
        switch (target) {
        case 'dev':
            var isDebug = true;
            var pack_config = this.mergeConfig(args, isDebug);
            pack_config.devtool = '#eval';

            var conf = config.getConfig();
            if (conf.mock === true) {
                var babelQueryStr = babel(isDebug);
                var entryPath = [];
                for (var key in pack_config.entry) {
                    var entry = pack_config.entry[key];
                    var type = Object.prototype.toString.call(entry);
                    if (type === 'object String]') {
                        entryPath.push(path.resolve(process.cwd(), entry + '.js'));
                    } else if (type === '[object Array]') {
                        entryPath.push(path.resolve(process.cwd(), entry[entry.length - 1] + '.js'));
                    }
                }

                var mockPath = path.resolve(process.cwd(), 'mock/mock.js');

                //load mock.js before all
                pack_config.module.loaders.push({
                    test: entryPath,
                    exclude: /(node_modules|bower_components)/,
                    loaders: [`imports?Mock=${mockPath}`, `babel-loader?${babelQueryStr}`]
                });
            }

            // config css and less loader
            pack_config.module.loaders.push({
                test: /\.css$/,
                loaders: ['style', 'css?sourceMap']
            });
            pack_config.module.loaders.push({
                test: /\.less$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['style', 'css?sourceMap!less?sourceMap']
            });

            // add plugin
            pack_config.plugins.push(new webpack.HotModuleReplacementPlugin());
            pack_config.plugins.push(new webpack.DefinePlugin({
                WEBPACK_DEBUG: true,
                'process.env': {
                    NODE_ENV: '"development"'
                }
            }));

            pack_config.output.publicPath = `http://localhost:${config.getPort()}/`;

            logger.debug('dev server start with webpack config: ');
            logger.debug(pack_config);

            return pack_config;
        case 'release':
            if (args.mock) {
                args.sourcemap = "";
            }
            var sourcemap = !!args.sourcemap ? "?source-map" : "";

            var pack_config = this.mergeConfig(args);
            if (sourcemap) {
                pack_config.devtool = '#source-map';
            } else {
                pack_config.devtool = '#eval';
            }

            if (args.mock == true) {
                var babelQueryStr = babel(false);
                var entryPath = [];
                for (var key in pack_config.entry) {
                    var entry = pack_config.entry[key];
                    var type = Object.prototype.toString.call(entry);
                    if (type === 'object String]') {
                        entryPath.push(path.resolve(process.cwd(), entry + '.js'));
                    } else if (type === '[object Array]') {
                        entryPath.push(path.resolve(process.cwd(), entry[entry.length - 1] + '.js'));
                    }
                }

                var mockPath = path.resolve(process.cwd(), 'mock/mock.js');

                //load mock.js before all
                pack_config.module.loaders.push({
                    test: entryPath,
                    exclude: /(node_modules|bower_components)/,
                    loaders: [`imports?Mock=${mockPath}`, `babel-loader?${babelQueryStr}`]
                });
            }

            pack_config.module.loaders.push({
                test: /\.css$/,
                loader: ExtractTextPlugin.extract('style', `css${sourcemap}!postcss`)
            });
            pack_config.module.loaders.push({
                test: /\.less$/,
                exclude: /(node_modules|bower_components)/,
                loader: ExtractTextPlugin.extract('style', `css${sourcemap}!postcss!less${sourcemap}`)
            });

            pack_config.plugins.push(new ExtractTextPlugin(`[name].[hash].css`));
            if (args.uglify) {
                pack_config.plugins.push(new webpack.optimize.UglifyJsPlugin({
                    compress: {
                        warnings: false
                    },
                    sourceMap: !!args.sourcemap
                }));
            }

            pack_config.plugins.push(new webpack.DefinePlugin({
                WEBPACK_DEBUG: false,
                'process.env': {
                    NODE_ENV: '"production"'
                }
            }));

            logger.debug('kil release with webpack config: ');
            logger.debug(pack_config);

            return pack_config;
        default:
            break;
        }

        return null;
    }

    /**
     * parse entry
     * @param  {[string]} dev:
     *     dev: add dev server and HMR entries
     *     release: do nothing with enties expcet convert string to array
     * @return {[type]}
     */
    parseEntry(entry, dev, depth) {
        if (entry) {
            var type = Object.prototype.toString.call(entry);
            if (type === '[object String]') {
                entry = [entry];
                if (dev) {
                    entry.unshift(`webpack-dev-server/client?http://localhost:${config.getPort()}`, 'webpack/hot/dev-server');
                }
            } else if (type === '[object Array]') {
                if (dev) {
                    entry.unshift(`webpack-dev-server/client?http://localhost:${config.getPort()}`, 'webpack/hot/dev-server');
                }
            } else {
                for (var key in entry) {
                    entry[key] = this.parseEntry(entry[key], dev);
                }
            }

            return entry;
        } else {
            logger.error('No entry is found!');
        }
    }

    /**
     * merge webpack default config, user's config, and config from package.json
     * @param  {Boolean} isDebug : is debug mode, add dev-sever entry or not
     * @return {[Object]}
     */
    mergeConfig(args, isDebug) {
        var pack_def = require('./pack');
        var packPath = path.join(process.cwd(), 'pack.js');
        var sysCfg = config.loadPackageConfig(args);
        var pack;

        try {
            pack = fs.statSync(packPath);
            pack = require(packPath);
            try {
                pack = pack(path.resolve(__dirname, 'node_modules'));
            } catch ( e ) {
                logger.error(' Error happens in pack.js ');
                logger.error(e);

                process.exit(1);
            }
        } catch ( e ) {}

        if (!pack) {
            logger.info("can't find pack.js, use webpack config from package.json or default.");
            var conf = sysCfg.webpack;
            pack = {
                entry: conf.entry || 'main',
                plugins: conf.plugins,
                devServer: conf.devServer,
                resolve: conf.resolve,
                output: {
                    publicPath: conf.publicPath
                }
            }
        }

        if (!pack) {
            return pack_def;
        } else {
            var pack_config = pack;
            if (!pack.entry) {
                pack_config.entry = pack_def.entry;
            }
            pack_config.entry = this.parseEntry(pack_config.entry, isDebug);
            // use kil default webpack config, for build use
            var publicPath = pack_config.output && pack_config.output.publicPath;
            pack_config.output = pack_def.output;
            if (publicPath) {
                pack_config.output.publicPath = publicPath;
            }

            // hash control, add hash when release
            let hash = '';
            if (!isDebug) {
                hash = '.[hash]';
            }
            pack_config.output.filename = `[name]${hash}.js`;
            pack_config.output.chunkFilename = `[id]${hash}.js`;

            if (pack_config.module && pack_config.module.loaders) {
                Array.prototype.push.apply(pack_def.module.loaders, pack_config.module.loaders);
            } else {
                pack_config.module = {};
            }
            pack_config.module.loaders = pack_def.module.loaders;
            pack_config.module.loaders.push({
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loaders: [`babel-loader?${babel(isDebug)}`]
            });

            // config loader for vue
            pack_config.module.loaders.push({
                test: /\.vue$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['vue-loader']
            });
            pack_config.vue = {
                loaders: {
                    js: `babel-loader?${babel(isDebug)}`,
                }
            };
            if (pack_config.resolve) {
                pack_config.resolve.root = pack_def.resolve.root;
            } else {
                pack_config.resolve = pack_def.resolve;
            }
            pack_config.resolveLoader = pack.resolveLoader || pack_def.resolveLoader;

            if (pack_config.plugins) {
                Array.prototype.push.apply(pack_def.plugins, pack_config.plugins);
            }
            pack_config.plugins = pack_def.plugins;

            if (pack_config.externals) {
                Array.prototype.push.apply(pack_def.externals, pack_config.externals);
            }

            pack_config.externals = pack_def.externals;
            pack_config.postcss = pack_def.postcss;
            if (pack.devServer) {
                pack_config.devServer = pack.devServer;
            }

            return pack_config;
        }
    }

}

module.exports = new Utils();
<commit_msg>change crlf to lf<commit_after>'use strict';

var path = require('path'),
    fs = require('fs'),
    logger = require('./logger'),
    webpack = require('webpack'),
    ExtractTextPlugin = require('extract-text-webpack-plugin'),
    config = require('./config'),
    babel = require('./babel');

class Utils {

    /**
     * load webpack:
     *     @task dev: add dev-server and enable HMR, according to mock config, enable mock
     *     @task release: add uglifyjs
     * @return config
     */
    loadWebpackCfg(target, args) {
        switch (target) {
            case 'dev':
                var isDebug = true;
                var pack_config = this.mergeConfig(args, isDebug);
                pack_config.devtool = '#eval';

                var conf = config.getConfig();
                if (conf.mock === true) {
                    var babelQueryStr = babel(isDebug);
                    var entryPath = [];
                    for (var key in pack_config.entry) {
                        var entry = pack_config.entry[key];
                        var type = Object.prototype.toString.call(entry);
                        if (type === 'object String]') {
                            entryPath.push(path.resolve(process.cwd(), entry + '.js'));
                        } else if (type === '[object Array]') {
                            entryPath.push(path.resolve(process.cwd(), entry[entry.length - 1] + '.js'));
                        }
                    }

                    var mockPath = path.resolve(process.cwd(), 'mock/mock.js');

                    //load mock.js before all
                    pack_config.module.loaders.push({
                        test: entryPath,
                        exclude: /(node_modules|bower_components)/,
                        loaders: [`imports?Mock=${mockPath}`, `babel-loader?${babelQueryStr}`]
                    });
                }

                // config css and less loader
                pack_config.module.loaders.push({
                    test: /\.css$/,
                    loaders: ['style', 'css?sourceMap']
                });
                pack_config.module.loaders.push({
                    test: /\.less$/,
                    exclude: /(node_modules|bower_components)/,
                    loaders: ['style', 'css?sourceMap!less?sourceMap']
                });

                // add plugin
                pack_config.plugins.push(new webpack.HotModuleReplacementPlugin());
                pack_config.plugins.push(new webpack.DefinePlugin({
                    WEBPACK_DEBUG: true,
                    'process.env': {
                        NODE_ENV: '"development"'
                    }
                }));

                pack_config.output.publicPath = `http://localhost:${config.getPort()}/`;

                logger.debug('dev server start with webpack config: ');
                logger.debug(pack_config);

                return pack_config;
            case 'release':
                if (args.mock) {
                    args.sourcemap = "";
                }
                var sourcemap = !!args.sourcemap ? "?source-map" : "";

                var pack_config = this.mergeConfig(args);
                if (sourcemap) {
                    pack_config.devtool = '#source-map';
                } else {
                    pack_config.devtool = '#eval';
                }

                if (args.mock == true) {
                    var babelQueryStr = babel(false);
                    var entryPath = [];
                    for (var key in pack_config.entry) {
                        var entry = pack_config.entry[key];
                        var type = Object.prototype.toString.call(entry);
                        if (type === 'object String]') {
                            entryPath.push(path.resolve(process.cwd(), entry + '.js'));
                        } else if (type === '[object Array]') {
                            entryPath.push(path.resolve(process.cwd(), entry[entry.length - 1] + '.js'));
                        }
                    }

                    var mockPath = path.resolve(process.cwd(), 'mock/mock.js');

                    //load mock.js before all
                    pack_config.module.loaders.push({
                        test: entryPath,
                        exclude: /(node_modules|bower_components)/,
                        loaders: [`imports?Mock=${mockPath}`, `babel-loader?${babelQueryStr}`]
                    });
                }

                pack_config.module.loaders.push({
                    test: /\.css$/,
                    loader: ExtractTextPlugin.extract('style', `css${sourcemap}!postcss`)
                });
                pack_config.module.loaders.push({
                    test: /\.less$/,
                    exclude: /(node_modules|bower_components)/,
                    loader: ExtractTextPlugin.extract('style', `css${sourcemap}!postcss!less${sourcemap}`)
                });

                pack_config.plugins.push(new ExtractTextPlugin(`[name].[hash].css`));
                if (args.uglify) {
                    pack_config.plugins.push(new webpack.optimize.UglifyJsPlugin({
                        compress: {
                            warnings: false
                        },
                        sourceMap: !!args.sourcemap
                    }));
                }

                pack_config.plugins.push(new webpack.DefinePlugin({
                    WEBPACK_DEBUG: false,
                    'process.env': {
                        NODE_ENV: '"production"'
                    }
                }));

                logger.debug('kil release with webpack config: ');
                logger.debug(pack_config);

                return pack_config;
            default:
                break;
        }

        return null;
    }

    /**
     * parse entry
     * @param  {[string]} dev:
     *     dev: add dev server and HMR entries
     *     release: do nothing with enties expcet convert string to array
     * @return {[type]}
     */
    parseEntry(entry, dev, depth) {
        if (entry) {
            var type = Object.prototype.toString.call(entry);
            if (type === '[object String]') {
                entry = [entry];
                if (dev) {
                    entry.unshift(`webpack-dev-server/client?http://localhost:${config.getPort()}`, 'webpack/hot/dev-server');
                }
            } else if (type === '[object Array]') {
                if (dev) {
                    entry.unshift(`webpack-dev-server/client?http://localhost:${config.getPort()}`, 'webpack/hot/dev-server');
                }
            } else {
                for (var key in entry) {
                    entry[key] = this.parseEntry(entry[key], dev);
                }
            }

            return entry;
        } else {
            logger.error('No entry is found!');
        }
    }

    /**
     * merge webpack default config, user's config, and config from package.json
     * @param  {Boolean} isDebug : is debug mode, add dev-sever entry or not
     * @return {[Object]}
     */
    mergeConfig(args, isDebug) {
        var pack_def = require('./pack');
        var packPath = path.join(process.cwd(), 'pack.js');
        var sysCfg = config.loadPackageConfig(args);
        var pack;

        try {
            pack = fs.statSync(packPath);
            pack = require(packPath);
            try {
                pack = pack(path.resolve(__dirname, 'node_modules'));
            } catch (e) {
                logger.error(' Error happens in pack.js ');
                logger.error(e);

                process.exit(1);
            }
        } catch (e) {}

        if (!pack) {
            logger.info("can't find pack.js, use webpack config from package.json or default.");
            var conf = sysCfg.webpack;
            pack = {
                entry: conf.entry || 'main',
                plugins: conf.plugins,
                devServer: conf.devServer,
                resolve: conf.resolve,
                output: {
                    publicPath: conf.publicPath
                }
            }
        }

        if (!pack) {
            return pack_def;
        } else {
            var pack_config = pack;
            if (!pack.entry) {
                pack_config.entry = pack_def.entry;
            }
            pack_config.entry = this.parseEntry(pack_config.entry, isDebug);
            // use kil default webpack config, for build use
            var publicPath = pack_config.output && pack_config.output.publicPath;
            pack_config.output = pack_def.output;
            if (publicPath) {
                pack_config.output.publicPath = publicPath;
            }

            // hash control, add hash when release
            let hash = '';
            if (!isDebug) {
                hash = '.[hash]';
            }
            pack_config.output.filename = `[name]${hash}.js`;
            pack_config.output.chunkFilename = `[id]${hash}.js`;

            if (pack_config.module && pack_config.module.loaders) {
                Array.prototype.push.apply(pack_def.module.loaders, pack_config.module.loaders);
            } else {
                pack_config.module = {};
            }
            pack_config.module.loaders = pack_def.module.loaders;
            pack_config.module.loaders.push({
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loaders: [`babel-loader?${babel(isDebug)}`]
            });

            // config loader for vue
            pack_config.module.loaders.push({
                test: /\.vue$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['vue-loader']
            });
            pack_config.vue = {
                loaders: {
                    js: `babel-loader?${babel(isDebug)}`,
                }
            };
            if (pack_config.resolve) {
                pack_config.resolve.root = pack_def.resolve.root;
            } else {
                pack_config.resolve = pack_def.resolve;
            }
            pack_config.resolveLoader = pack.resolveLoader || pack_def.resolveLoader;

            if (pack_config.plugins) {
                Array.prototype.push.apply(pack_def.plugins, pack_config.plugins);
            }
            pack_config.plugins = pack_def.plugins;

            if (pack_config.externals) {
                Array.prototype.push.apply(pack_def.externals, pack_config.externals);
            }

            pack_config.externals = pack_def.externals;
            pack_config.postcss = pack_def.postcss;
            if (pack.devServer) {
                pack_config.devServer = pack.devServer;
            }

            return pack_config;
        }
    }

}

module.exports = new Utils();
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var yeoman = require('yeoman-generator');

var ScalatraGenerator = module.exports = function ScalatraGenerator() {
  yeoman.generators.Base.apply(this, arguments);
};

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

ScalatraGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'projectName',
    message: 'What do you want to call your project?'
  }, {
    name: 'organization',
    message: 'Organization name?',
    default: 'com.example'
  }];

  this.prompt(prompts, function (props) {
    this.projectName = props.projectName;
    this.organization = props.organization;

    var promptRest = [{
      name: 'package',
      message: props.organization + '.[Package name]?',
      default: 'app'
    }, {
      name: 'servletName',
      message: 'Servlet name?',
      default: 'MessageController'
    }];

    this.prompt(promptRest, function (properties) {
      this.package = props.organization + '.' + checkPackage(properties.package);
      this.servletName = properties.servletName;
      cb();
    }.bind(this));

    function checkPackage(pkg) {
      return pkg.substring(0, props.organization.length) === props.organization ?
        pkg.slice(props.organization.length + 1) : pkg;
    }

  }.bind(this));
};

ScalatraGenerator.prototype.app = function app() {

  function makePath(path) {
    return path.replace(/\./g, '/');
  }

  this.mkdir('src/main/resources');
  this.mkdir('src/main/scala/' + makePath(this.package));
  this.mkdir('src/main/webapp/WEB-INF');
  this.mkdir('src/test/scala/' + makePath(this.package));
  this.mkdir('project');

  this.template('_build.scala', 'project/build.scala');
  this.copy('build.properties', 'project/build.properties');
  this.copy('plugins.sbt', 'project/plugins.sbt');
  this.copy('sbt', 'sbt');
  this.copy('README.md', 'README.md');
  this.template('_ScalatraBootstrap.scala', 'src/main/scala/ScalatraBootstrap.scala');
  this.template('_ScalatraServlet.scala', 'src/main/scala/' + makePath(this.package) + '/controllers/' + this.servletName + '.scala');
  this.template('_ScalatraServletSpec.scala', 'src/test/scala/' + makePath(this.package) + '/controllers/' + this.servletName + 'Spec.scala');
  this.copy('web.xml', 'src/main/webapp/WEB-INF/web.xml');
};

<commit_msg>folder name as a default value for project name<commit_after>'use strict';
var util = require('util');
var path = require('path')
var yeoman = require('yeoman-generator');

var ScalatraGenerator = module.exports = function ScalatraGenerator() {
  yeoman.generators.Base.apply(this, arguments);
};

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

ScalatraGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'projectName',
    message: 'What do you want to call your project?',
    default: path.basename(process.cwd())
  }, {
    name: 'organization',
    message: 'Organization name?',
    default: 'com.example'
  }];

  this.prompt(prompts, function (props) {
    this.projectName = props.projectName;
    this.organization = props.organization;

    var promptRest = [{
      name: 'package',
      message: props.organization + '.[Package name]?',
      default: 'app'
    }, {
      name: 'servletName',
      message: 'Servlet name?',
      default: 'MessageController'
    }];

    this.prompt(promptRest, function (properties) {
      this.package = props.organization + '.' + checkPackage(properties.package);
      this.servletName = properties.servletName;
      cb();
    }.bind(this));

    function checkPackage(pkg) {
      return pkg.substring(0, props.organization.length) === props.organization ?
        pkg.slice(props.organization.length + 1) : pkg;
    }

  }.bind(this));
};

ScalatraGenerator.prototype.app = function app() {

  function makePath(path) {
    return path.replace(/\./g, '/');
  }

  this.mkdir('src/main/resources');
  this.mkdir('src/main/scala/' + makePath(this.package));
  this.mkdir('src/main/webapp/WEB-INF');
  this.mkdir('src/test/scala/' + makePath(this.package));
  this.mkdir('project');

  this.template('_build.scala', 'project/build.scala');
  this.copy('build.properties', 'project/build.properties');
  this.copy('plugins.sbt', 'project/plugins.sbt');
  this.copy('sbt', 'sbt');
  this.copy('README.md', 'README.md');
  this.template('_ScalatraBootstrap.scala', 'src/main/scala/ScalatraBootstrap.scala');
  this.template('_ScalatraServlet.scala', 'src/main/scala/' + makePath(this.package) + '/controllers/' + this.servletName + '.scala');
  this.template('_ScalatraServletSpec.scala', 'src/test/scala/' + makePath(this.package) + '/controllers/' + this.servletName + 'Spec.scala');
  this.copy('web.xml', 'src/main/webapp/WEB-INF/web.xml');
};

<|endoftext|>


<commit_before>var request = require("request");
var cheerio = require("cheerio");

var Iconv = require('iconv').Iconv;
var iconv = new Iconv('euc-kr', 'utf-8//translit//ignore');

var stockCode = 192820;
var stockDetailPageUrl = "http://finance.naver.com/item/main.nhn?code=" + stockCode;

var requestOptions = {
  url: stockDetailPageUrl,
  encoding: null
};

request(requestOptions, function(error, response, body) {
  if (error) throw error;
  var body = iconv.convert(body).toString();

  var $ = cheerio.load(body);

  // 종목명 크롤링
  var stockName = $(".wrap_company h2").text();

  // 종목 상승/하락 크롤링
  var className = $(".no_today").find("em").attr("class");
  var isUp = className == "no_up" ? true : false;

  // 종목 상승률/하락률 크롤링
  var stockPrice = $("#chart_area .rate_info .no_exday em").eq(0).find(".blind").text();
  stockPrice = Number(stockPrice.replace(/,/gi, ""));

  var stockChangeRate = $("#chart_area .rate_info .no_exday em").eq(1).find(".blind").text();
  stockChangeRate = Number(stockChangeRate);

  console.log(stockName);
  console.log(isUp);
  console.log(stockPrice);
  console.log(stockChangeRate);
});
<commit_msg>update stocks.js: add stock current price<commit_after>var request = require("request");
var cheerio = require("cheerio");

var Iconv = require('iconv').Iconv;
var iconv = new Iconv('euc-kr', 'utf-8//translit//ignore');

var stockCode = 192820;
var stockDetailPageUrl = "http://finance.naver.com/item/main.nhn?code=" + stockCode;

var requestOptions = {
  url: stockDetailPageUrl,
  encoding: null
};

request(requestOptions, function(error, response, body) {
  if (error) throw error;
  var body = iconv.convert(body).toString();

  var $ = cheerio.load(body);

  // 종목명 크롤링
  var stockName = $(".wrap_company h2").text();

  // 종목 상승/하락 크롤링
  var className = $(".no_today").find("em").attr("class");
  var isUp = className == "no_up" ? true : false;

  // 종목 가격 정보
  var stockPrice = $(".no_today em .blind").html();
  stockPrice = Number(stockPrice.replace(/,/gi, ""));

  // 종목 상승률/하락률 크롤링
  var stockChangePrice = $("#chart_area .rate_info .no_exday em").eq(0).find(".blind").text();
  stockChangePrice = Number(stockChangePrice.replace(/,/gi, ""));

  var stockChangeRate = $("#chart_area .rate_info .no_exday em").eq(1).find(".blind").text();
  stockChangeRate = Number(stockChangeRate);

  console.log(stockName);
  console.log(isUp);
  console.log(stockPrice);
  console.log(stockChangePrice);
  console.log(stockChangeRate);
});
<|endoftext|>