<commit_before>;(function ( $, window, undefined ) {

    var pluginName = 'russian_declension',
        document = window.document,
        defaults = {
            one: "",
            several: "",
            many: "",
            zero: ""
        };

    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype.init = function () {
        var title_keys = ['one', 'several', 'many'];
        var titles = [];
        for (i=0; i<=2; i++) {
            if ($(this.element).data(title_keys[i])) {
                titles.push($(this.element).data(title_keys[i]));
            } else {
                titles.push(this.options[title_keys[i]]);
            }
        }

        var number = parseInt($(this.element).html());
        var zero_title = this.options['zero'] || $(this.element).data('zero');

        var title = this.pluralize(number, titles);

        if (number == 0 && zero_title) {
          $(this.element).html(zero_title);
        } else {
          $(this.element).html(number + " " + title);
        }
    };

    Plugin.prototype.pluralize = function(number, titles) {
        var cases = [2, 0, 1, 1, 1, 2];
        return titles[ (number%100 > 4 && number%100 < 20) ? 2 : cases[(number%10 < 5) ? number%10 : 5] ];
    }

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
            }
        });
    };

    $(window).on('load', function() {
        $('[data-rudecle]').russian_declension()
    });

}(jQuery, window));
<commit_msg>Бешбармак<commit_after>;(function ( $, window, undefined ) {

    var pluginName = 'russian_declension',
        document = window.document,
        defaults = {
            one: "",
            several: "",
            many: "",
            zero: ""
        };

    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype.init = function () {
        var title_keys = ['one', 'several', 'many'];
        var titles = [];
        for (i=0; i<=2; i++) {
            if ($(this.element).data(title_keys[i])) {
                titles.push($(this.element).data(title_keys[i]));
            } else {
                titles.push(this.options[title_keys[i]]);
            }
        }

        var number = parseInt($(this.element).html());

        if (!number) {
          number = 0;
        }

        var zero_title = this.options['zero'] || $(this.element).data('zero');
        var title = this.pluralize(number, titles);

        if (number == 0 && zero_title) {
          $(this.element).html(zero_title);
        } else {
          $(this.element).html(number + " " + title);
        }
    };

    Plugin.prototype.pluralize = function(number, titles) {
        var cases = [2, 0, 1, 1, 1, 2];
        return titles[ (number%100 > 4 && number%100 < 20) ? 2 : cases[(number%10 < 5) ? number%10 : 5] ];
    }

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
            }
        });
    };

    $(window).on('load', function() {
        $('[data-rudecle]').russian_declension()
    });

}(jQuery, window));
<|endoftext|>


<commit_before>/**
 * Translates templates in Pattern Lab to templates consumable by the backend.
 *
 * Converts Mustache tags into whatever type of tokens are used by the backend
 * webapp based on mappings in a YAML file named similarly to the Mustache
 * template.
 */
'use strict';

const path = require('path');

const diveSync = require('diveSync');
const Feplet = require('feplet');
const fs = require('fs-extra');
const slash = require('slash');
const yaml = require('js-yaml');

let t;

module.exports = class {
  #ui;

  constructor(options, ui) {
    this.#ui = ui;

    this.options = options;
    this.conf = options.conf;
    this.pref = options.pref;
    this.rootDir = options.rootDir;
    this.utils = options.utils;

    this.srcDir = this.conf.ui.paths.source.templates;

    t = this.utils.t;
  }

  get patternlab() {
    return this.#ui.patternlab;
  }

  mustacheRecurse(code) {
    const partsByTag = code.split('{{');
    const patternExtension = this.conf.ui.patternExtension;
    const patternsDir = this.conf.ui.paths.source.patterns;
    let codeEscaped = '';

    for (let i = 0; i < partsByTag.length; i++) {
      const part = partsByTag[i];

      if (i === 0) {
        codeEscaped += part;
      }
      else {
        if (part[0] === '>') {
          const partsOfPart = part.split('}}');
          const regexStr = patternExtension + '\\s*\\(';
          const regex = new RegExp(regexStr);

          if (
            partsOfPart[0].trim().slice(-patternExtension.length) === patternExtension ||
            regex.test(partsOfPart[0])
          ) {
            codeEscaped += '\u0002\u0002' + part.replace('}}', '\u0003\u0003');
          }
          else {
            codeEscaped += '{{' + part;
          }
        }
        else {
          codeEscaped += '{{' + part;
        }
      }
    }

    const delimiters = '\u0002\u0002 \u0003\u0003';
    const parseArr = Feplet.parse(Feplet.scan(codeEscaped, delimiters), null, {delimiters});
    const partials = {};
    const partialsComp = {};

    for (const part of parseArr) {
      if (part.tag === '>') {
        const parenIndex = part.n.indexOf('(');
        let codeUnescaped;
        let partPath = part.n;

        if (parenIndex > -1) {
          partPath = part.n.slice(0, parenIndex);
        }

        // Reduce file reads by checking if file content has already been saved in the patternlab object.
        for (const pattern of this.patternlab.ingredients.patterns) {
          if (partPath === pattern.relPath) {
            codeUnescaped = pattern.template;

            break;
          }
        }

        if (typeof codeUnescaped === 'undefined') {
          codeUnescaped = fs.readFileSync(`${patternsDir}/${partPath}`, this.conf.enc);
        }

        const recursionResults = this.mustacheRecurse(codeUnescaped);
        partials[part.n] = recursionResults.codeEscaped;
        partialsComp[part.n] = recursionResults;

        Object.assign(partials, recursionResults.partials);
        Object.assign(partialsComp, recursionResults.partialsComp);
      }
    }

    const compilation = Feplet.generate(parseArr, codeEscaped, {delimiters});

    return {
      codeEscaped,
      compilation,
      parseArr,
      partials,
      partialsComp
    };
  }

  templateProcess(file, templatesDirDefault, templatesExtDefault) {
    const patternExtension = this.conf.ui.patternExtension;
    let data = null;
    let mustacheFile;
    let srcDirParam = this.srcDir;
    let stat = null;
    let stat1 = null;
    let templatesDir = '';
    let templatesExt = '';
    let ymlFile = '';

    // Exclude files prefixed by __
    if (path.basename(file).slice(0, 2) === '__') {
      return;
    }

    if (path.extname(file) === patternExtension) {
      const regex = new RegExp(patternExtension + '$');
      mustacheFile = file;
      ymlFile = file.replace(regex, '.yml');
    }

    try {
      stat = fs.statSync(mustacheFile);
    }
    catch /* istanbul ignore next */ {
      // Only process templates that actually exist.
      return;
    }

    try {
      stat1 = fs.statSync(ymlFile);
    }
    catch {} // eslint-disable-line no-empty

    // Return on stat fail. Exclude non-files.
    /* istanbul ignore if */
    if (!stat || !stat.isFile()) {
      return;
    }

    // Try to read YAML file if it exists.
    if (stat1 && stat1.isFile()) {
      // Read YAML file and store keys/values in tokens object.
      try {
        const yml = fs.readFileSync(ymlFile, this.conf.enc);
        data = yaml.safeLoad(yml);

        if (typeof data.templates_dir === 'string') {
          templatesDir = this.utils.backendDirCheck(data.templates_dir);

          // Do not maintain nested directory structure in backend if
          // templates_dir is set in exceptional YAML file.
          if (templatesDir) {
            srcDirParam = path.dirname(mustacheFile);
          }

          // Unset templates_dir in local YAML data.
          delete data.templates_dir;
        }

        if (typeof data.templates_ext === 'string') {
          templatesExt = this.utils.extNormalize(data.templates_ext);

          // Unset templates_dir in local YAML data.
          delete data.templates_ext;
        }
      }
      catch /* istanbul ignore next */ {
        data = null;
      }
    }

    if (templatesDirDefault && !templatesDir) {
      templatesDir = templatesDirDefault;
    }

    if (templatesExtDefault && !templatesExt) {
      templatesExt = templatesExtDefault;
    }

    if (templatesDir && templatesExt) {
      try {
        let code;

        // Reduce file reads by checking if file content has already been saved in the patternlab object.
        for (const pattern of this.patternlab.ingredients.patterns) {
          if (mustacheFile.includes(pattern.relPath)) {
            code = pattern.template;

            break;
          }
        }

        if (typeof code === 'undefined') {
          code = fs.readFileSync(mustacheFile, this.conf.enc);
        }

        // Recurse through Mustache templates (sparingly. See comment above.)
        const {
          compilation,
          partials,
          partialsComp
        } = this.mustacheRecurse(code);
        const codeRecursed = compilation.render({}, partials, null, partialsComp);
        // Iterate through tokens and replace keys for values in the code.
        const codeTranslated = this.tokensReplace(data, codeRecursed);
        // Write translated templates.
        const dest = this.templatesWrite(mustacheFile, srcDirParam, templatesDir, templatesExt, codeTranslated);

        let message = t('Template %s translated');
        message = message.replace('%s', '\x1b[36m' + dest.replace(this.rootDir, '').replace(/^\//, '') + '\x1b[0m');

        this.utils.log(message);
      }
      catch (err) /* istanbul ignore next */ {
        this.utils.error(err);
      }
    }
  }

  templatesGlob() {
    const globbed = [];
    const nosyncStr = '/_nosync';

    diveSync(
      this.srcDir,
      {
        filter: (pathname, dir) => {
          if (
            pathname.indexOf(`${nosyncStr}/`) > -1 ||
            pathname.slice(-nosyncStr.length) === nosyncStr
          ) {
            return false;
          }
          else if (dir) {
            return true;
          }
          else if (path.extname(pathname) === this.conf.ui.patternExtension) {
            return true;
          }
          else {
            return false;
          }
        }
      },
      (err, file) => {
        /* istanbul ignore if */
        if (err) {
          this.utils.error(err);
        }

        globbed.push(slash(file));
      }
    );

    return globbed;
  }

  templatesWrite(file, srcDirParam, templatesDir, templatesExt, code) {
    // Determine destination for token-replaced code.
    let dest = file.replace(srcDirParam, '');

    // Replace underscore prefixes.
    // eslint-disable-next-line no-useless-escape
    dest = dest.replace(/\/_([^\/]+)$/, '/$1');
    dest = templatesDir + dest;
    dest = dest.replace(/\.mustache$/, templatesExt);

    // Write to file system.
    fs.ensureDirSync(path.dirname(dest));
    fs.outputFileSync(dest, code);

    return dest;
  }

  tokensReplace(tokens, codeParam) {
    if (!tokens) {
      return codeParam;
    }

    const tokenKeys = Object.keys(tokens);
    let code = codeParam;

    // Switch delimiters where there is a tokenKey match.
    for (const tokenKey of tokenKeys) {
      const regexStr = '\\{\\{\\{?\\s*' + this.utils.regexReservedCharsEscape(tokenKey) + '\\s*\\}?\\}\\}';
      const regex = new RegExp(regexStr, 'g');
      code = code.replace(regex, '\u0002\u0002' + tokenKey + '\u0003\u0003');
    }

    // Delete remaining Mustache tags if configured to do so.
    if (!this.pref.templater.retain_mustache) {
      // eslint-disable-next-line no-useless-escape
      code = code.replace(/\{\{[^\(]*?(\([\S\s]*?\))?\s*\}?\}\}\s*\n?/g, '');
    }

    // Hydate the newly delimited tokens.
    for (const tokenKey of tokenKeys) {
      const regexStr = '\u0002\u0002' + this.utils.regexReservedCharsEscape(tokenKey) + '\u0003\u0003';
      const regex = new RegExp(regexStr, 'g');
      const token = tokens[tokenKey].replace(/^\n/, '').replace(/\n$/, '');
      code = code.replace(regex, token);
    }

    return code;
  }

  main() {
    const files = this.templatesGlob();
    const templatesDirDefault = this.utils.backendDirCheck(this.pref.backend.synced_dirs.templates_dir);
    const templatesExtDefault = this.utils.extNormalize(this.pref.backend.synced_dirs.templates_ext);

    // Search source directory for Mustache files.
    // Excluding templates in _nosync directory and those prefixed by __.
    // Trying to keep the globbing simple and maintainable.
    for (let i = 0; i < files.length; i++) {
      this.templateProcess(files[i], templatesDirDefault, templatesExtDefault);
    }
  }
};
<commit_msg>backward compatible templater<commit_after>/**
 * Translates templates in Pattern Lab to templates consumable by the backend.
 *
 * Converts Mustache tags into whatever type of tokens are used by the backend
 * webapp based on mappings in a YAML file named similarly to the Mustache
 * template.
 */
'use strict';

const path = require('path');

const diveSync = require('diveSync');
const Feplet = require('feplet');
const fs = require('fs-extra');
const slash = require('slash');
const yaml = require('js-yaml');

let t;

module.exports = class {
  #ui;

  constructor(options, ui) {
    this.#ui = ui;

    this.options = options;
    this.conf = options.conf;
    this.pref = options.pref;
    this.rootDir = options.rootDir;
    this.utils = options.utils;

    this.srcDir = this.conf.ui.paths.source.templates;

    t = this.utils.t;
  }

  get patternlab() {
    return this.#ui.patternlab;
  }

  mustacheRecurse(code) {
    const partsByTag = code.split('{{');
    const patternExtension = this.conf.ui.patternExtension;
    const patternsDir = this.conf.ui.paths.source.patterns;
    let codeEscaped = '';

    for (let i = 0; i < partsByTag.length; i++) {
      const part = partsByTag[i];

      if (i === 0) {
        codeEscaped += part;
      }
      else {
        if (part[0] === '>') {
          const partsOfPart = part.split('}}');
          const regexStr = patternExtension + '\\s*\\(';
          const regex = new RegExp(regexStr);

          if (
            partsOfPart[0].trim().slice(-patternExtension.length) === patternExtension ||
            regex.test(partsOfPart[0])
          ) {
            codeEscaped += '\u0002\u0002' + part.replace('}}', '\u0003\u0003');
          }
          else {
            codeEscaped += '{{' + part;
          }
        }
        else {
          codeEscaped += '{{' + part;
        }
      }
    }

    const delimiters = '\u0002\u0002 \u0003\u0003';
    const parseArr = Feplet.parse(Feplet.scan(codeEscaped, delimiters), null, {delimiters});
    const partials = {};
    const partialsComp = {};

    for (const part of parseArr) {
      if (part.tag === '>') {
        const parenIndex = part.n.indexOf('(');
        let codeUnescaped;
        let partPath = part.n;

        if (parenIndex > -1) {
          partPath = part.n.slice(0, parenIndex);
        }

        // Reduce file reads by checking if file content has already been saved in the patternlab object.
        for (const pattern of this.patternlab.ingredients.patterns) {
          if (partPath === pattern.relPath) {
            codeUnescaped = pattern.template;

            break;
          }
        }

        if (typeof codeUnescaped === 'undefined') {
          codeUnescaped = fs.readFileSync(`${patternsDir}/${partPath}`, this.conf.enc);
        }

        const recursionResults = this.mustacheRecurse(codeUnescaped);
        partials[part.n] = recursionResults.codeEscaped;
        partialsComp[part.n] = recursionResults;

        Object.assign(partials, recursionResults.partials);
        Object.assign(partialsComp, recursionResults.partialsComp);
      }
    }

    const compilation = Feplet.generate(parseArr, codeEscaped, {delimiters});

    return {
      codeEscaped,
      compilation,
      parseArr,
      partials,
      partialsComp
    };
  }

  templateProcess(file, templatesDirDefault, templatesExtDefault) {
    const patternExtension = this.conf.ui.patternExtension;
    let data = null;
    let mustacheFile;
    let srcDirParam = this.srcDir;
    let stat = null;
    let stat1 = null;
    let templatesDir = '';
    let templatesExt = '';
    let ymlFile = '';

    // Exclude files prefixed by __
    if (path.basename(file).slice(0, 2) === '__') {
      return;
    }

    if (path.extname(file) === patternExtension) {
      const regex = new RegExp(patternExtension + '$');
      mustacheFile = file;
      ymlFile = file.replace(regex, '.yml');
    }

    try {
      stat = fs.statSync(mustacheFile);
    }
    catch /* istanbul ignore next */ {
      // Only process templates that actually exist.
      return;
    }

    try {
      stat1 = fs.statSync(ymlFile);
    }
    catch {} // eslint-disable-line no-empty

    // Return on stat fail. Exclude non-files.
    /* istanbul ignore if */
    if (!stat || !stat.isFile()) {
      return;
    }

    // Try to read YAML file if it exists.
    if (stat1 && stat1.isFile()) {
      // Read YAML file and store keys/values in tokens object.
      try {
        const yml = fs.readFileSync(ymlFile, this.conf.enc);
        data = yaml.safeLoad(yml);

        if (typeof data.templates_dir === 'string') {
          templatesDir = this.utils.backendDirCheck(data.templates_dir);

          // Do not maintain nested directory structure in backend if
          // templates_dir is set in exceptional YAML file.
          if (templatesDir) {
            srcDirParam = path.dirname(mustacheFile);
          }

          // Unset templates_dir in local YAML data.
          delete data.templates_dir;
        }

        if (typeof data.templates_ext === 'string') {
          templatesExt = this.utils.extNormalize(data.templates_ext);

          // Unset templates_dir in local YAML data.
          delete data.templates_ext;
        }
      }
      catch /* istanbul ignore next */ {
        data = null;
      }
    }

    if (templatesDirDefault && !templatesDir) {
      templatesDir = templatesDirDefault;
    }

    if (templatesExtDefault && !templatesExt) {
      templatesExt = templatesExtDefault;
    }

    if (templatesDir && templatesExt) {
      try {
        let code;

        // Reduce file reads by checking if file content has already been saved in the patternlab object.
        for (const pattern of this.patternlab.ingredients.patterns) {
          if (mustacheFile.includes(pattern.relPath)) {
            code = pattern.template;

            break;
          }
        }

        if (typeof code === 'undefined') {
          code = fs.readFileSync(mustacheFile, this.conf.enc);
        }

        // Recurse through Mustache templates (sparingly. See comment above.)
        const {
          compilation,
          partials,
          partialsComp
        } = this.mustacheRecurse(code);
        const codeRecursed = compilation.render({}, partials, null, partialsComp);
        // Iterate through tokens and replace keys for values in the code.
        const codeTranslated = this.tokensReplace(data, codeRecursed);
        // Write translated templates.
        const dest = this.templatesWrite(mustacheFile, srcDirParam, templatesDir, templatesExt, codeTranslated);

        let message = t('Template %s translated');
        message = message.replace('%s', '\x1b[36m' + dest.replace(this.rootDir, '').replace(/^\//, '') + '\x1b[0m');

        this.utils.log(message);
      }
      catch (err) /* istanbul ignore next */ {
        this.utils.error(err);
      }
    }
  }

  templatesGlob() {
    const globbed = [];
    const nosyncStr = '/_nosync';

    diveSync(
      this.srcDir,
      {
        filter: (pathname, dir) => {
          if (
            pathname.indexOf(`${nosyncStr}/`) > -1 ||
            pathname.slice(-nosyncStr.length) === nosyncStr
          ) {
            return false;
          }
          else if (dir) {
            return true;
          }
          else if (path.extname(pathname) === this.conf.ui.patternExtension) {
            return true;
          }
          else {
            return false;
          }
        }
      },
      (err, file) => {
        /* istanbul ignore if */
        if (err) {
          this.utils.error(err);
        }

        globbed.push(slash(file));
      }
    );

    return globbed;
  }

  templatesWrite(file, srcDirParam, templatesDir, templatesExt, code) {
    // Determine destination for token-replaced code.
    let dest = file.replace(srcDirParam, '');

    // Replace underscore prefixes.
    // eslint-disable-next-line no-useless-escape
    dest = dest.replace(/\/_([^\/]+)$/, '/$1');
    dest = templatesDir + dest;
    dest = dest.replace(/\.mustache$/, templatesExt);

    // Write to file system.
    fs.ensureDirSync(path.dirname(dest));
    fs.outputFileSync(dest, code);

    return dest;
  }

  tokensReplace(tokens, codeParam) {
    if (!tokens) {
      return codeParam;
    }

    const tokenKeys = Object.keys(tokens);
    let code = codeParam;

    // Switch delimiters where there is a tokenKey match.
    for (const tokenKey of tokenKeys) {
      // DEPRECATED: the next 3 lines are for backward compatibility with fepper-drupal versions < v0.15.0.
      const regexStrDeprecated = '\\{\\{\\{?\\s*' + tokenKey + '\\s*\\}?\\}\\}';
      const regexDeprecated = new RegExp(regexStrDeprecated, 'g');
      code = code.replace(regexDeprecated, '\u0002\u0002' + tokenKey + '\u0003\u0003');

      const regexStr = '\\{\\{\\{?\\s*' + this.utils.regexReservedCharsEscape(tokenKey) + '\\s*\\}?\\}\\}';
      const regex = new RegExp(regexStr, 'g');
      code = code.replace(regex, '\u0002\u0002' + tokenKey + '\u0003\u0003');
    }

    // Delete remaining Mustache tags if configured to do so.
    if (!this.pref.templater.retain_mustache) {
      // eslint-disable-next-line no-useless-escape
      code = code.replace(/\{\{[^\(]*?(\([\S\s]*?\))?\s*\}?\}\}\s*\n?/g, '');
    }

    // Hydate the newly delimited tokens.
    for (const tokenKey of tokenKeys) {
      // DEPRECATED: the next 7 lines are for backward compatibility with fepper-drupal versions < v0.15.0.
      const regexStrDeprecated = '\u0002\u0002' + tokenKey + '\u0003\u0003';
      const regexDeprecated = new RegExp(regexStrDeprecated, 'g');
      const tokenDeprecated = tokens[tokenKey]
        .replace(/\\\{\\\{(.*)\\\}\\\}/g, '{{$1}}')
        .replace(/^\n/, '')
        .replace(/\n$/, '');
      code = code.replace(regexDeprecated, tokenDeprecated);

      const regexStr = '\u0002\u0002' + this.utils.regexReservedCharsEscape(tokenKey) + '\u0003\u0003';
      const regex = new RegExp(regexStr, 'g');
      const token = tokens[tokenKey]
        .replace(/\\\{\\\{(.*)\\\}\\\}/g, '{{$1}}') // DEPRECATED: for backward compatibility - to be removed.
        .replace(/^\n/, '')
        .replace(/\n$/, '');
      code = code.replace(regex, token);
    }

    return code;
  }

  main() {
    const files = this.templatesGlob();
    const templatesDirDefault = this.utils.backendDirCheck(this.pref.backend.synced_dirs.templates_dir);
    const templatesExtDefault = this.utils.extNormalize(this.pref.backend.synced_dirs.templates_ext);

    // Search source directory for Mustache files.
    // Excluding templates in _nosync directory and those prefixed by __.
    // Trying to keep the globbing simple and maintainable.
    for (let i = 0; i < files.length; i++) {
      this.templateProcess(files[i], templatesDirDefault, templatesExtDefault);
    }
  }
};
<|endoftext|>


<commit_before>/*
 *	Rename file to match api/html
 *	this file will be autoloaded
 *	and setUi() autorun
 *
 *	Used for report-specific mods
 */
var splReportUI = {

	setUI: function() {
		console.log('retreiving char sets');
		$.ajax(
			_this.api
		)
		.done(function(obj) {
			//_this.showReport(obj);
			//console.log(obj);
			if (obj.charsets) {
				$('#search-list-chars').append(obj.chars);
				$('#search-list-chars-warning').hide()
				$('#search-list-chars-wrapper').show();
			} else {
				$('#search-list-chars-warning')
				.removeClass('alert-warning')
				.addClass('alert-danger')
				.html('Unable to load character sets.');
			}
		})
		.fail(function() {
		})
		.always(function() {
		});

	}

}.setUI();
<commit_msg>spell<commit_after>/*
 *	Rename file to match api/html
 *	this file will be autoloaded
 *	and setUi() autorun
 *
 *	Used for report-specific mods
 */
var splReportUI = {

	setUI: function() {
		console.log('retreiving char sets');
		$.ajax(
			_this.api
		)
		.done(function(obj) {
			//_this.showReport(obj);
			//console.log(obj);
			if (obj.chars) {
				$('#search-list-chars').append(obj.chars);
				$('#search-list-chars-warning').hide()
				$('#search-list-chars-wrapper').show();
			} else {
				$('#search-list-chars-warning')
				.removeClass('alert-warning')
				.addClass('alert-danger')
				.html('Unable to load character sets.');
			}
		})
		.fail(function() {
		})
		.always(function() {
		});

	}

}.setUI();
<|endoftext|>


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

'use strict';

const assert = require('assert');
const StateTree = require('state-tree');

class Foo {}

const tree = StateTree({
  // Can not pass functions
  //func() {
  //},
  instance: new Foo(),
  money: 1000,
  party: {
    members: [
      {
        name: 'Taro',
        job: 'fighter',
      },
      {
        name: 'Hanako',
        job: 'mage',
      },
    ],
  },
});

assert.strictEqual(tree.get('money'), 1000);
assert.deepStrictEqual(tree.get('party.members.1'), {
  name: 'Hanako',
  job: 'mage',
});

tree.push('party.members', {
  name: 'Jiro',
  job: 'thief',
});
assert.deepStrictEqual(tree.get('party.members.2'), {
  name: 'Jiro',
  job: 'thief',
});

//
// Does it not broken unrelated refs?
//
const taro = tree.get('party.members.0');
assert.deepStrictEqual(taro, {
  name: 'Taro',
  job: 'fighter',
});

tree.unshift('party.members', {
  name: 'Hiroshi',
  job: 'ranger',
});

const taro2 = tree.get('party.members.1');
assert.strictEqual(taro, taro2);

const tree2 = tree.get('');
console.log(tree2);
<commit_msg>Update a sample<commit_after>#!/usr/bin/env node

'use strict';

const assert = require('assert');
const StateTree = require('state-tree');

class Foo {
  func() {
  }
}

const tree = StateTree({
  // Can not pass functions directly
  //func() {
  //},
  foo: new Foo(),
  money: 1000,
  party: {
    members: [
      {
        name: 'Taro',
        job: 'fighter',
      },
      {
        name: 'Hanako',
        job: 'mage',
      },
    ],
  },
});

assert.strictEqual(tree.get('money'), 1000);
assert.deepStrictEqual(tree.get('party.members.1'), {
  name: 'Hanako',
  job: 'mage',
});

tree.push('party.members', {
  name: 'Jiro',
  job: 'thief',
});
assert.deepStrictEqual(tree.get('party.members.2'), {
  name: 'Jiro',
  job: 'thief',
});

//
// Does it not broken unrelated refs?
//
const taro = tree.get('party.members.0');
assert.deepStrictEqual(taro, {
  name: 'Taro',
  job: 'fighter',
});

tree.unshift('party.members', {
  name: 'Hiroshi',
  job: 'ranger',
});

const taro2 = tree.get('party.members.1');
assert.strictEqual(taro, taro2);

const tree2 = tree.get('');
console.log(tree2);
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * Single location of all accessibility strings used in scenery-phet.  These
 * strings are not meant to be translatable yet.  Rosetta needs some work to
 * provide translators with context for these strings, and we want to receive
 * some community feedback before these strings are submitted for translation.
 *
 * @author Jesse Greenberg
 */
define( function( require ) {
  'use strict';

  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );

  var SceneryPhetA11yStrings = {

    //------------------------------------------------------------------------
    // Sim Section strings
    //------------------------------------------------------------------------

    // screen summary intro for a multiscreen sim (not sim specific),
    // extra space at end for string concat with rest of the screen summary
    screenSummaryMultiScreenIntro: {
      value: 'This is an interactive sim. It changes as you play with it. Each screen has a Play Area and Control Panel. '
    },

    // screen summary intro for a single screen sim (not sim specific),
    screenSummarySingleScreenIntroPattern: {
      value: '{{sim}} is an interactive sim. It changes as you play with it.'
    },
    // screen summary intro for a single screen sim (not sim specific),
    screenSummaryKeyboardShortcutsHint: {
      value: 'If needed, check out keyboard shortcuts under Sim Resources.'
    },

    playArea: {
      value: 'Play Area'
    },
    controlArea: {
      value: 'Control Area'
    },

    //------------------------------------------------------------------------

    // button labels
    soundToggleLabelString: {
      value: 'Mute Sound'
    },

    // SoundToggleButton alerts
    simSoundOnString: {
      value: 'Sim sound on.'
    },
    simSoundOffString: {
      value: 'Sim sound off.'
    },

    // alert for sim reset
    resetAllAlertString: {
      value: 'Sim screen restarted. Everything reset.'
    },

    // help descriptions for general navigation
    keyboardHelpDialogTabDescription: {
      value: 'Move to next item with Tab key.'
    },
    keyboardHelpDialogShiftTabDescription: {
      value: 'Move to previous item with Shift plus Tab key.'
    },
    keyboardHelpDialogPressButtonsDescription: {
      value: 'Press buttons with the space bar.'
    },
    keyboardHelpDialogGroupNavigationDescription: {
      value: 'Move between items in a group with Left and Right arrow keys or Up and Down Arrow keys.'
    },
    keyboardHelpDialogExitDialogDescription: {
      value: 'Exit a dialog with Escape key.'
    },

    // help descriptions for sliders
    keyboardHelpDialogAdjustDefaultStepsString: {
      value: 'Adjust slider with Left and Right arrow keys, or Up and Down arrow keys.'
    },
    keyboardHelpDialogAdjustSmallerStepsString: {
      value: 'Adjust in smaller steps with Shift plus Left or Right arrow key, or Shift plus Up or Down arrow key.'
    },
    keyboardHelpDialogAdjustLargerStepsString: {
      value: 'Adjust in larger steps with Page Up or Page Down key.'
    },
    keyboardHelpDialogJumpToHomeString: {
      value: 'Jump to minimum with Home key.'
    },
    keyboardHelpDialogJumpToEndString: {
      value: 'Jump to maximum with End key.'
    },

    // PlayPauseButton
    playString: {
      value: 'Play'
    },
    pauseString: {
      value: 'Pause'
    },
    playDescriptionString: {
      value: 'Resume what is happening in the Play Area'
    },
    pauseDescriptionString: {
      value: 'Pause what is happening in the Play Area'
    },
    // StepButton
    stepString: {
      'value': 'Step'
    },
    stepDescriptionString: {
      'value': 'Pause and resume stream with every press.'
    }
  };

  if ( phet.chipper.queryParameters.stringTest === 'xss' ) {
    for ( var key in SceneryPhetA11yStrings ) {
      SceneryPhetA11yStrings[ key ].value += '';
    }
  }

  // verify that object is immutable, without the runtime penalty in production code
  if ( assert ) { Object.freeze( SceneryPhetA11yStrings ); }

  sceneryPhet.register( 'SceneryPhetA11yStrings', SceneryPhetA11yStrings );

  return SceneryPhetA11yStrings;
} );<commit_msg>update friction keyboard dialog, https://github.com/phetsims/friction/issues/117<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * Single location of all accessibility strings used in scenery-phet.  These
 * strings are not meant to be translatable yet.  Rosetta needs some work to
 * provide translators with context for these strings, and we want to receive
 * some community feedback before these strings are submitted for translation.
 *
 * @author Jesse Greenberg
 */
define( function( require ) {
  'use strict';

  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );

  var SceneryPhetA11yStrings = {

    //------------------------------------------------------------------------
    // Sim Section strings
    //------------------------------------------------------------------------

    // screen summary intro for a multiscreen sim (not sim specific),
    // extra space at end for string concat with rest of the screen summary
    screenSummaryMultiScreenIntro: {
      value: 'This is an interactive sim. It changes as you play with it. Each screen has a Play Area and Control Panel. '
    },

    // screen summary intro for a single screen sim (not sim specific),
    screenSummarySingleScreenIntroPattern: {
      value: '{{sim}} is an interactive sim. It changes as you play with it.'
    },
    // screen summary intro for a single screen sim (not sim specific),
    screenSummaryKeyboardShortcutsHint: {
      value: 'If needed, check out keyboard shortcuts under Sim Resources.'
    },

    playArea: {
      value: 'Play Area'
    },
    controlArea: {
      value: 'Control Area'
    },

    //------------------------------------------------------------------------

    // button labels
    soundToggleLabelString: {
      value: 'Mute Sound'
    },

    // SoundToggleButton alerts
    simSoundOnString: {
      value: 'Sim sound on.'
    },
    simSoundOffString: {
      value: 'Sim sound off.'
    },

    // alert for sim reset
    resetAllAlertString: {
      value: 'Sim screen restarted. Everything reset.'
    },

    // help descriptions for general navigation
    keyboardHelpDialogTabDescription: {
      value: 'Move to next item with Tab key.'
    },
    keyboardHelpDialogShiftTabDescription: {
      value: 'Move to previous item with Shift plus Tab key.'
    },
    keyboardHelpDialogPressButtonsDescription: {
      value: 'Press buttons with Space key.'
    },
    keyboardHelpDialogGroupNavigationDescription: {
      value: 'Move between items in a group with Left and Right arrow keys or Up and Down Arrow keys.'
    },
    keyboardHelpDialogExitDialogDescription: {
      value: 'Exit a dialog with Escape key.'
    },

    // help descriptions for sliders
    keyboardHelpDialogAdjustDefaultStepsString: {
      value: 'Adjust slider with Left and Right arrow keys, or Up and Down arrow keys.'
    },
    keyboardHelpDialogAdjustSmallerStepsString: {
      value: 'Adjust in smaller steps with Shift plus Left or Right arrow key, or Shift plus Up or Down arrow key.'
    },
    keyboardHelpDialogAdjustLargerStepsString: {
      value: 'Adjust in larger steps with Page Up or Page Down key.'
    },
    keyboardHelpDialogJumpToHomeString: {
      value: 'Jump to minimum with Home key.'
    },
    keyboardHelpDialogJumpToEndString: {
      value: 'Jump to maximum with End key.'
    },

    // PlayPauseButton
    playString: {
      value: 'Play'
    },
    pauseString: {
      value: 'Pause'
    },
    playDescriptionString: {
      value: 'Resume what is happening in the Play Area'
    },
    pauseDescriptionString: {
      value: 'Pause what is happening in the Play Area'
    },
    // StepButton
    stepString: {
      'value': 'Step'
    },
    stepDescriptionString: {
      'value': 'Pause and resume stream with every press.'
    }
  };

  if ( phet.chipper.queryParameters.stringTest === 'xss' ) {
    for ( var key in SceneryPhetA11yStrings ) {
      SceneryPhetA11yStrings[ key ].value += '';
    }
  }

  // verify that object is immutable, without the runtime penalty in production code
  if ( assert ) { Object.freeze( SceneryPhetA11yStrings ); }

  sceneryPhet.register( 'SceneryPhetA11yStrings', SceneryPhetA11yStrings );

  return SceneryPhetA11yStrings;
} );<|endoftext|>


<commit_before>var http = require('http'), https = require('https'), url = require('url'), fs = require('fs'),
  db = require('mongoose'),
  connect = require('connect'),
  express = require('express'),
  Log = require('log');
var routes = require('./adnoceserver-routes.js'),
  adnoce = require('./adnoce');

var log = new Log('info');

// creates a new adnoce server based on expres
var app = express();
module.exports = function (options) {
  "use strict";

  this.routes = routes;

  var _name = 'adnoceserver';
  var config = {};

  config.server = {
    port: options.port || 8080,
    host: options.host || 'localhost',
    cookiesecret: options.cookiesecret || 'adnocebe1e2c9d20dd0b0a',
    dumpExceptions: options.dumpExceptions || true,
    showStack: options.showStack || true,
    adnoceport: options.adnoceport || 80,
    adnocehost: options.adnocehost || 'localhost',
    socketnamespace: options.socketnamespace || 'adnoce'
  };

  app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
  });

  app.use(connect.bodyParser())
  .use(connect.query())
  .use(connect.cookieParser(config.server.cookiesecret))
  .use(app.router)
  .use(express.errorHandler({ dumpExceptions: config.server.dumpExceptions, showStack: config.server.showStack }));

  // Routes
  // views
  app.get('/', routes.index);
  // API
  app.get('/api/:collection', routes.genericAPI);
  // external requests (in case, no CDN is defined)
  app.get('/jquery-1.9.1.min.js', function (req, res) {
    res.set('Content-Type', 'application/javascript');
    fs.readFile(__dirname + '/external/jquery-1.9.1.min.js', 'utf8', function(err, data){
      if (err === null) res.send(200, data);
      else res.send(404);
    });
  });

  // create the server
  var server = http.createServer(app);
  server.listen(config.server.port, config.server.host, function(e,s) {
    log.info('adnoce server - "%s" running on port %s', config.server.host, config.server.port);
  });
  // setup websockets
  var io = require('socket.io').listen(server);
  io.configure(function (){
    io.set('log level', 1);
  });
  // setup websockets client (connect to adnoce core)
  var ioc = require('socket.io-client');
  var adnocesocket = ioc.connect(config.server.adnocehost+':'+config.server.adnoceport+'/'+config.server.socketnamespace, {reconnect: true});
  // adnoce events
  adnocesocket.on('connect', function(){
    if (adnocesocket.socket.connected) log.info('adnoce server - socket connection to adnoce core established, host: "%s:%s"', adnocesocket.socket.options.host, adnocesocket.socket.options.port);
  });
  adnocesocket.on('trackingdata', function(data){
    console.log('EMIT TRACKING DATA');
    io.sockets.emit('trackingdata', data);
  });
}<commit_msg>console.log deleted<commit_after>var http = require('http'), https = require('https'), url = require('url'), fs = require('fs'),
  db = require('mongoose'),
  connect = require('connect'),
  express = require('express'),
  Log = require('log');
var routes = require('./adnoceserver-routes.js'),
  adnoce = require('./adnoce');

var log = new Log('info');

// creates a new adnoce server based on expres
var app = express();
module.exports = function (options) {
  "use strict";

  this.routes = routes;

  var _name = 'adnoceserver';
  var config = {};

  config.server = {
    port: options.port || 8080,
    host: options.host || 'localhost',
    cookiesecret: options.cookiesecret || 'adnocebe1e2c9d20dd0b0a',
    dumpExceptions: options.dumpExceptions || true,
    showStack: options.showStack || true,
    adnoceport: options.adnoceport || 80,
    adnocehost: options.adnocehost || 'localhost',
    socketnamespace: options.socketnamespace || 'adnoce'
  };

  app.configure(function(){
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
  });

  app.use(connect.bodyParser())
  .use(connect.query())
  .use(connect.cookieParser(config.server.cookiesecret))
  .use(app.router)
  .use(express.errorHandler({ dumpExceptions: config.server.dumpExceptions, showStack: config.server.showStack }));

  // Routes
  // views
  app.get('/', routes.index);
  // API
  app.get('/api/:collection', routes.genericAPI);
  // external requests (in case, no CDN is defined)
  app.get('/jquery-1.9.1.min.js', function (req, res) {
    res.set('Content-Type', 'application/javascript');
    fs.readFile(__dirname + '/external/jquery-1.9.1.min.js', 'utf8', function(err, data){
      if (err === null) res.send(200, data);
      else res.send(404);
    });
  });

  // create the server
  var server = http.createServer(app);
  server.listen(config.server.port, config.server.host, function(e,s) {
    log.info('adnoce server - "%s" running on port %s', config.server.host, config.server.port);
  });
  // setup websockets
  var io = require('socket.io').listen(server);
  io.configure(function (){
    io.set('log level', 1);
  });
  // setup websockets client (connect to adnoce core)
  var ioc = require('socket.io-client');
  var adnocesocket = ioc.connect(config.server.adnocehost+':'+config.server.adnoceport+'/'+config.server.socketnamespace, {reconnect: true});
  // adnoce events
  adnocesocket.on('connect', function(){
    if (adnocesocket.socket.connected) log.info('adnoce server - socket connection to adnoce core established, host: "%s:%s"', adnocesocket.socket.options.host, adnocesocket.socket.options.port);
  });
  adnocesocket.on('trackingdata', function(data){
    io.sockets.emit('trackingdata', data);
  });
}<|endoftext|>


<commit_before>/**
 * @module paneFactory
 */
define([
	'./paneUtil',
	'./overlayFactory',
	'./tabBarFactory'
], function(paneUtil, overlayFactory, tabBarFactory) {
	'use strict';

	return {

		clNameContentPane: 'contentPane',
		clNamePaneContainer: 'paneContainer',
		clSuffixPaneContainer: 'Container',

		/**
		 * Creates the element, which serves as the parent of a content pane.
		 * The pane container comes in two types. A row container, where the children are aligned in rows, and a col
		 * container, where the children are laid out out as columns.
		 * @param {string} type colContainer or rowContainer
		 * @return {HTMLDivElement}
		 */
		createPaneContainer: function(type) {
			var pc = document.createElement('div');

			pc.classList.add(this.clNamePaneContainer, type + this.clSuffixPaneContainer);

			return pc;
		},

		/**
		 * Creates the DOM of the content pane.
		 * @param {String} overlayType overlay type 'row' or 'col'
		 * @param {Array} [tabs] array of HTMLLIElements
		 * @param {Array} [tabContents] array of HTMLSectionElements
		 * @return {HTMLDivElement}
		 */
		create: function(overlayType, tabs, tabContents) {
			var div = document.createElement('div'),
				header = document.createElement('header'),
				li = tabs || [document.createElement('li')],
				sections = tabContents || [document.createElement('section')],
				tabBar = tabBarFactory.create(li),
				overlay = this.createOverlays(overlayType);

			div.classList.add(this.clNameContentPane);

			div.appendChild(overlay);
			header.appendChild(tabBar);
			div.appendChild(header);
			for (var i = 0; i < sections.length; i++) {
				div.appendChild(sections[i]);
			}

			return div;
		},

		/**
		 * Removes a contentPane and the corresponding divider from the DOM.
		 * If the pane does not have any siblings the parentContainer is also removed.
		 * @param {HTMLDivElement} pane contentPane
		 */
		remove: function(pane) {
			// note: order of removing of children is important
			var z, idx = paneUtil.getIndex(pane),
				siblings = paneUtil.getSiblings(pane),	// does not return a live nodelist
				parent = pane.parentNode;

			parent.removeChild(pane);

			// last pane in a paneContainer?
			if (siblings.length === 1) { // otherwise length would be at least 2, because of the divider
				// handles case only when no siblings in paneContainer
				// now without a divider but in a paneContainer with a divider
				// remove paneContainer and corresponding divider
				this.remove(parent);
			}
			// remove the divider
			else {
				z = idx === siblings.length - 1 ? idx - 1 : idx + 1;
				parent.removeChild(siblings[z]);
			}
		},

		/**
		 * Create the DOM of the overlays.
		 * @param {String} type 'row' or 'col'
		 * @returns {HTMLDivElement}
		 */
		createOverlays: function(type) {
			// depending on the number of siblings and the position (first, last, only) in the container node, we create
			// the dnd overlays correspondingly.
			var containerNode = overlayFactory.createContainer(type);

			containerNode.appendChild(overlayFactory.create('edge'));
			containerNode.appendChild(overlayFactory.create('middle'));
			containerNode.appendChild(overlayFactory.create('edge'));

			return containerNode;
		},

		/**
		 * Returns the overlay container.
		 * @param {HTMLDivElement} pane contentPane
		 */
		getOverlayContainer: function(pane) {
			return pane.getElementsByClassName(overlayFactory.cssClassName)[0];
		},

		/**
		 * Create and insert a new content pane above or left of the target.
		 * Creates the DOM of a pane, inserts it before the passed node and returns the pane.
		 * @param target
		 * @param tab
		 * @param tabContent
		 * @return {Node}
		 */
		insertBefore: function(target, tab, tabContent) {
			var contentPane, overlayType,
				parent = target.parentNode;

			overlayType = parent.classList.contains('rowContainer') ? 'col' : 'row';
			contentPane = this.create(overlayType, tab, tabContent);
			parent.insertBefore(contentPane, target);

			return contentPane;
		}
	};
});<commit_msg>fixes not passing an array<commit_after>/**
 * @module paneFactory
 */
define([
	'./paneUtil',
	'./overlayFactory',
	'./tabBarFactory'
], function(paneUtil, overlayFactory, tabBarFactory) {
	'use strict';

	return {

		clNameContentPane: 'contentPane',
		clNamePaneContainer: 'paneContainer',
		clSuffixPaneContainer: 'Container',

		/**
		 * Creates the element, which serves as the parent of a content pane.
		 * The pane container comes in two types. A row container, where the children are aligned in rows, and a col
		 * container, where the children are laid out out as columns.
		 * @param {string} type colContainer or rowContainer
		 * @return {HTMLDivElement}
		 */
		createPaneContainer: function(type) {
			var pc = document.createElement('div');

			pc.classList.add(this.clNamePaneContainer, type + this.clSuffixPaneContainer);

			return pc;
		},

		/**
		 * Creates the DOM of the content pane.
		 * @param {String} overlayType overlay type 'row' or 'col'
		 * @param {Array} [tabs] array of HTMLLIElements
		 * @param {Array} [tabContents] array of HTMLSectionElements
		 * @return {HTMLDivElement}
		 */
		create: function(overlayType, tabs, tabContents) {
			var div = document.createElement('div'),
				header = document.createElement('header'),
				li = tabs || [document.createElement('li')],
				sections = tabContents || [document.createElement('section')],
				tabBar = tabBarFactory.create(li),
				overlay = this.createOverlays(overlayType);

			div.classList.add(this.clNameContentPane);

			div.appendChild(overlay);
			header.appendChild(tabBar);
			div.appendChild(header);
			for (var i = 0; i < sections.length; i++) {
				div.appendChild(sections[i]);
			}

			return div;
		},

		/**
		 * Removes a contentPane and the corresponding divider from the DOM.
		 * If the pane does not have any siblings the parentContainer is also removed.
		 * @param {HTMLDivElement} pane contentPane
		 */
		remove: function(pane) {
			// note: order of removing of children is important
			var z, idx = paneUtil.getIndex(pane),
				siblings = paneUtil.getSiblings(pane),	// does not return a live nodelist
				parent = pane.parentNode;

			parent.removeChild(pane);

			// last pane in a paneContainer?
			if (siblings.length === 1) { // otherwise length would be at least 2, because of the divider
				// handles case only when no siblings in paneContainer
				// now without a divider but in a paneContainer with a divider
				// remove paneContainer and corresponding divider
				this.remove(parent);
			}
			// remove the divider
			else {
				z = idx === siblings.length - 1 ? idx - 1 : idx + 1;
				parent.removeChild(siblings[z]);
			}
		},

		/**
		 * Create the DOM of the overlays.
		 * @param {String} type 'row' or 'col'
		 * @returns {HTMLDivElement}
		 */
		createOverlays: function(type) {
			// depending on the number of siblings and the position (first, last, only) in the container node, we create
			// the dnd overlays correspondingly.
			var containerNode = overlayFactory.createContainer(type);

			containerNode.appendChild(overlayFactory.create('edge'));
			containerNode.appendChild(overlayFactory.create('middle'));
			containerNode.appendChild(overlayFactory.create('edge'));

			return containerNode;
		},

		/**
		 * Returns the overlay container.
		 * @param {HTMLDivElement} pane contentPane
		 */
		getOverlayContainer: function(pane) {
			return pane.getElementsByClassName(overlayFactory.cssClassName)[0];
		},

		/**
		 * Create and insert a new content pane above or left of the target.
		 * Creates the DOM of a pane, inserts it before the passed node and returns the pane.
		 * @param target
		 * @param tab
		 * @param tabContent
		 * @return {Node}
		 */
		insertBefore: function(target, tab, tabContent) {
			var contentPane, overlayType,
				parent = target.parentNode;

			overlayType = parent.classList.contains('rowContainer') ? 'col' : 'row';
			contentPane = this.create(overlayType, [tab], [tabContent]);
			parent.insertBefore(contentPane, target);

			return contentPane;
		}
	};
});<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    console.log(viewModel.users().length);
                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        console.log(data);
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
        console.log(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

}

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData.length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
    }

    viewModel.tabledata([]);

    console.log(viewModel.tempTableData());

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
            console.log("OK");
        }
    });
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        console.log(viewModel.users().length);
        return viewModel.users().length;
    });
}<commit_msg>search<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    console.log(viewModel.users().length);
                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        console.log(data);
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
        console.log(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

}

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData.length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
        console.log("222222229");
    }

    viewModel.tabledata([]);

    console.log(viewModel.tempTableData());

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
            console.log("OK");
        }
    });
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        console.log(viewModel.users().length);
        return viewModel.users().length;
    });
}<|endoftext|>


<commit_before>"use strict";

/*  ------------------------------------------------------------------------ */

const { isObject, isNumber, isDictionary, isArray } = require ('./type')

/*  ------------------------------------------------------------------------ */

const empty = () => Object.create (null) // empty obj without even a prototype

    , keys = Object.keys

    , values = x => !isArray (x)  // don't copy arrays if they're already arrays!
                        ? Object.values (x)
                        : x

    , index = x => new Set (values (x))

    , extend = (...args) => Object.assign (empty (), ...args) // NB: side-effect free

    , clone = x => isArray (x)
                        ? Array.from (x) // clones arrays
                        : extend (x)     // clones objects

/*  ------------------------------------------------------------------------ */

module.exports = {

      empty
    , keys
    , values
    , extend
    , clone
    , index
    , ordered: x => x // a stub to keep assoc keys in order (in JS it does nothing, it's mostly for Python)
    , unique:  x => Array.from (index (x))

/*  .............................................   */

    , keysort (x, out = empty ()) {

        for (const k of keys (x).sort ())
            out[k] = x[k]

        return out
    }

/*  .............................................   */

    , indexBy (x, k, out = empty ()) {

        for (const v of values (x))
            if (k in v)
                out[v[k]] = v

        return out
    }

/*  .............................................   */

    , groupBy (x, k, out = empty ()) {

        for (const v of values (x)) {
            if (k in v) {
                const p = v[k]
                out[p] = out[p] || []
                out[p].push (v)
            }
        }
        return out
    }

/*  .............................................   */

    , filterBy (x, k, value = undefined, out = []) {

        for (const v of values (x))
            if (v[k] === value)
                out.push (v)

        return out
    }

/*  .............................................   */

    , sortBy: (array, // NB: MUTATES ARRAY!
               key,
               descending = false,
               direction  = descending ? -1 : 1) => array.sort ((a, b) =>
                                                                ((a[key] < b[key]) ? -direction :
                                                                ((a[key] > b[key]) ?  direction : 0)))

/*  .............................................   */

    , flatten: function flatten (x, out = []) {

        for (const v of x) {
            if (isArray (v)) flatten (v, out)
            else out.push (v)
        }

        return out
    }

/*  .............................................   */

    , pluck: (x, k) => values (x)
                        .filter (v => k in v)
                        .map (v => v[k])

/*  .............................................   */

    , omit (x, ...args) {

        const out = clone (x)

        for (const k of args) {

            if (isArray (k)) // omit (x, ['a', 'b'])
                for (const kk of k)
                    delete out[kk]

            else delete out[k] // omit (x, 'a', 'b')
        }

        return out
    }

/*  .............................................   */

    , sum (...xs) {

        const ns = xs.filter (isNumber) // leave only numbers

        return (ns.length > 0)
                    ? ns.reduce ((a, b) => a + b, 0)
                    : undefined
    }

/*  .............................................   */

    , deepExtend: function deepExtend (...xs) {

        let out = undefined

        for (const x of xs) {

            if (isDictionary (x)) {

                if (!isObject (out))
                    out = empty ()

                for (const k in x)
                    out[k] = deepExtend (out[k], x[k])

            } else out = x
        }

        return out
    }

/*  ------------------------------------------------------------------------ */

}
<commit_msg>removed empty() as it caused problems with networking code<commit_after>"use strict";

/*  ------------------------------------------------------------------------ */

const { isObject, isNumber, isDictionary, isArray } = require ('./type')

/*  ------------------------------------------------------------------------ */

const keys = Object.keys

    , values = x => !isArray (x)  // don't copy arrays if they're already arrays!
                        ? Object.values (x)
                        : x

    , index = x => new Set (values (x))

    , extend = (...args) => Object.assign ({}, ...args) // NB: side-effect free

    , clone = x => isArray (x)
                        ? Array.from (x) // clones arrays
                        : extend (x)     // clones objects

/*  ------------------------------------------------------------------------ */

module.exports =

    { keys
    , values
    , extend
    , clone
    , index
    , ordered: x => x // a stub to keep assoc keys in order (in JS it does nothing, it's mostly for Python)
    , unique:  x => Array.from (index (x))

/*  .............................................   */

    , keysort (x, out = {}) {

        for (const k of keys (x).sort ())
            out[k] = x[k]

        return out
    }

/*  .............................................   */

    , indexBy (x, k, out = {}) {

        for (const v of values (x))
            if (k in v)
                out[v[k]] = v

        return out
    }

/*  .............................................   */

    , groupBy (x, k, out = {}) {

        for (const v of values (x)) {
            if (k in v) {
                const p = v[k]
                out[p] = out[p] || []
                out[p].push (v)
            }
        }
        return out
    }

/*  .............................................   */

    , filterBy (x, k, value = undefined, out = []) {

        for (const v of values (x))
            if (v[k] === value)
                out.push (v)

        return out
    }

/*  .............................................   */

    , sortBy: (array, // NB: MUTATES ARRAY!
               key,
               descending = false,
               direction  = descending ? -1 : 1) => array.sort ((a, b) =>
                                                                ((a[key] < b[key]) ? -direction :
                                                                ((a[key] > b[key]) ?  direction : 0)))

/*  .............................................   */

    , flatten: function flatten (x, out = []) {

        for (const v of x) {
            if (isArray (v)) flatten (v, out)
            else out.push (v)
        }

        return out
    }

/*  .............................................   */

    , pluck: (x, k) => values (x)
                        .filter (v => k in v)
                        .map (v => v[k])

/*  .............................................   */

    , omit (x, ...args) {

        const out = clone (x)

        for (const k of args) {

            if (isArray (k)) // omit (x, ['a', 'b'])
                for (const kk of k)
                    delete out[kk]

            else delete out[k] // omit (x, 'a', 'b')
        }

        return out
    }

/*  .............................................   */

    , sum (...xs) {

        const ns = xs.filter (isNumber) // leave only numbers

        return (ns.length > 0)
                    ? ns.reduce ((a, b) => a + b, 0)
                    : undefined
    }

/*  .............................................   */

    , deepExtend: function deepExtend (...xs) {

        let out = undefined

        for (const x of xs) {

            if (isDictionary (x)) {

                if (!isObject (out))
                    out = {}

                for (const k in x)
                    out[k] = deepExtend (out[k], x[k])

            } else out = x
        }

        return out
    }

/*  ------------------------------------------------------------------------ */

}
<|endoftext|>


<commit_before>"use strict";

define(['logManager',
    'clientUtil',
    'js/DiagramDesigner/DecoratorBase',
    'text!js/ModelEditor3/Decorators/DefaultDecorator/DefaultDecoratorTemplate.html',
    'js/DiagramDesigner/NodePropertyNames',
    'css!ModelEditor3CSS/Decorators/DefaultDecorator/DefaultDecorator'], function (logManager,
                                                       util,
                                                       DecoratorBase,
                                                       defaultDecoratorTemplate,
                                                       nodePropertyNames) {

    var DefaultDecorator,
        __parent__ = DecoratorBase,
        __parent_proto__ = DecoratorBase.prototype,
        DECORATOR_ID = "DefaultDecorator";

    DefaultDecorator = function (options) {
        var opts = _.extend( {}, options);

        __parent__.apply(this, [opts]);

        this.name = "";

        this.logger.debug("DefaultDecorator ctor");
    };

    _.extend(DefaultDecorator.prototype, __parent_proto__);
    DefaultDecorator.prototype.DECORATORID = DECORATOR_ID;

    /*********************** OVERRIDE DECORATORBASE MEMBERS **************************/

    DefaultDecorator.prototype.$DOMBase = $(defaultDecoratorTemplate);

    DefaultDecorator.prototype.on_addTo = function () {
        var client = this._control._client,
            nodeObj = client.getNode(this._metaInfo.GMEID);

        //render GME-ID in the DOM, for debugging
        this.$el.attr({"data-id": this._metaInfo.GMEID});

        if (nodeObj) {
            this.name = nodeObj.getAttribute(nodePropertyNames.Attributes.name) || "";
        }

        //find name placeholder
        this.skinParts.$name = this.$el.find(".name");
        this.skinParts.$name.text(this.name);

        //let the parent decorator class do its job first
        return __parent_proto__.on_addTo.apply(this, arguments);
    };

    DefaultDecorator.prototype.calculateDimension = function () {
        this.hostDesignerItem.width = this.$el.outerWidth(true);
        this.hostDesignerItem.height = this.$el.outerHeight(true);
    };

    DefaultDecorator.prototype.update = function () {
        var client = this._control._client,
            nodeObj = client.getNode(this._metaInfo.GMEID),
            newName = "";

        if (nodeObj) {
            newName = nodeObj.getAttribute(nodePropertyNames.Attributes.name) || "";

            if (this.name !== newName) {
                this.name = newName;
                this.skinParts.$name.text(this.name);
            }
        }
    };

    DefaultDecorator.prototype.getConnectionAreas = function (id) {
        var result = [];

        //by default return the bounding box edge's midpoints

        if (id === undefined) {
            //top left
            result.push( {"id": "0",
                "x": this.hostDesignerItem.width / 2,
                "y": 0,
                "w": 0,
                "h": 0,
                "orientation": "N",
                "len": 10} );

            result.push( {"id": "1",
                "x": this.hostDesignerItem.width / 2,
                "y": this.hostDesignerItem.height,
                "w": 0,
                "h": 0,
                "orientation": "S",
                "len": 10} );

            result.push( {"id": "2",
                "x": 0,
                "y": this.hostDesignerItem.height / 2,
                "w": 0,
                "h": 0,
                "orientation": "W",
                "len": 10} );

            result.push( {"id": "3",
                "x": this.hostDesignerItem.width,
                "y": this.hostDesignerItem.height / 2,
                "w": 0,
                "h": 0,
                "orientation": "E",
                "len": 10} );
        }

        return result;
    };

    return DefaultDecorator;
});<commit_msg>addnig node name inplace edit<commit_after>"use strict";

define(['logManager',
    'clientUtil',
    'js/DiagramDesigner/DecoratorBase',
    'text!js/ModelEditor3/Decorators/DefaultDecorator/DefaultDecoratorTemplate.html',
    'js/DiagramDesigner/NodePropertyNames',
    'css!ModelEditor3CSS/Decorators/DefaultDecorator/DefaultDecorator'], function (logManager,
                                                       util,
                                                       DecoratorBase,
                                                       defaultDecoratorTemplate,
                                                       nodePropertyNames) {

    var DefaultDecorator,
        __parent__ = DecoratorBase,
        __parent_proto__ = DecoratorBase.prototype,
        DECORATOR_ID = "DefaultDecorator";

    DefaultDecorator = function (options) {
        var opts = _.extend( {}, options);

        __parent__.apply(this, [opts]);

        this.name = "";

        this.logger.debug("DefaultDecorator ctor");
    };

    _.extend(DefaultDecorator.prototype, __parent_proto__);
    DefaultDecorator.prototype.DECORATORID = DECORATOR_ID;

    /*********************** OVERRIDE DECORATORBASE MEMBERS **************************/

    DefaultDecorator.prototype.$DOMBase = $(defaultDecoratorTemplate);

    DefaultDecorator.prototype.on_addTo = function () {
        var client = this._control._client,
            nodeObj = client.getNode(this._metaInfo.GMEID),
            gmeID = this._metaInfo.GMEID;

        //render GME-ID in the DOM, for debugging
        this.$el.attr({"data-id": this._metaInfo.GMEID});

        if (nodeObj) {
            this.name = nodeObj.getAttribute(nodePropertyNames.Attributes.name) || "";
        }

        //find name placeholder
        this.skinParts.$name = this.$el.find(".name");
        this.skinParts.$name.text(this.name);

        // set title editable on double-click
        this.skinParts.$name.editOnDblClick({"class": "",
            "onChange": function (oldValue, newValue) {
                client.setAttributes(gmeID, nodePropertyNames.Attributes.name, newValue);
            }});

        //let the parent decorator class do its job first
        return __parent_proto__.on_addTo.apply(this, arguments);
    };

    DefaultDecorator.prototype.calculateDimension = function () {
        this.hostDesignerItem.width = this.$el.outerWidth(true);
        this.hostDesignerItem.height = this.$el.outerHeight(true);
    };

    DefaultDecorator.prototype.update = function () {
        var client = this._control._client,
            nodeObj = client.getNode(this._metaInfo.GMEID),
            newName = "";

        if (nodeObj) {
            newName = nodeObj.getAttribute(nodePropertyNames.Attributes.name) || "";

            if (this.name !== newName) {
                this.name = newName;
                this.skinParts.$name.text(this.name);
            }
        }
    };

    DefaultDecorator.prototype.getConnectionAreas = function (id) {
        var result = [];

        //by default return the bounding box edge's midpoints

        if (id === undefined) {
            //top left
            result.push( {"id": "0",
                "x": this.hostDesignerItem.width / 2,
                "y": 0,
                "w": 0,
                "h": 0,
                "orientation": "N",
                "len": 10} );

            result.push( {"id": "1",
                "x": this.hostDesignerItem.width / 2,
                "y": this.hostDesignerItem.height,
                "w": 0,
                "h": 0,
                "orientation": "S",
                "len": 10} );

            result.push( {"id": "2",
                "x": 0,
                "y": this.hostDesignerItem.height / 2,
                "w": 0,
                "h": 0,
                "orientation": "W",
                "len": 10} );

            result.push( {"id": "3",
                "x": this.hostDesignerItem.width,
                "y": this.hostDesignerItem.height / 2,
                "w": 0,
                "h": 0,
                "orientation": "E",
                "len": 10} );
        }

        return result;
    };

    return DefaultDecorator;
});<|endoftext|>


<commit_before>'use strict';

/**
 * AutoComplete constructor.
 */
function AutoComplete (shellcraft) {
  this.minLength = 0;
  this.cmdList   = [];
  this.sc        = shellcraft;

  this.reload ();
}

AutoComplete.prototype.reload = function () {
  var self = this;

  self.cmdList = [];

  /* Extract only the commands (ignore private and options). */
  Object.keys (Object.getPrototypeOf (self.sc.arguments)).forEach (function (fct) {
    if (self.sc.arguments.hasOwnProperty (fct) ||
        /^_/.test (fct) ||
        self.sc.arguments[fct].type () !== 'command') {
      return;
    }

    if (fct.length > self.minLength) {
      self.minLength = fct.length;
    }
    self.cmdList.push (fct);
  });
};

AutoComplete.prototype.begin = function () {
  var self = this;

  var cmd = [];
  if (self.sc.uiPrompt.rl.line.length) {
    self.cmdList.forEach (function (fct) {
      var res = new RegExp ('^' + self.sc.uiPrompt.rl.line).test (fct);
      if (res) {
        cmd.push (fct);
      }
    });
  }

  if (cmd.length === 1) {
    /* Simple auto-complete (one command). */
    self.sc.uiPrompt.rl.write (null, {ctrl: true, name: 'u'});
    self.sc.uiPrompt.rl.write (cmd[0] + ' ');
    return;
  }

  /* Show all commands if empty. */
  if (!cmd.length) {
    cmd = self.cmdList;
  }

  var line = self.sc.uiPrompt.rl.line;
  self.sc.uiPrompt.rl.write (null, {ctrl: true, name: 'u'});

  var cmdDump = [];

  cmd.forEach (function (fct, index) {
    /* Append spaces for vert-align in the dump. */
    cmdDump[index] = fct + new Array (self.minLength - fct.length + 4).join (' ');

    /* Detect the smaller common string between all commands. */
    while (index < cmd.length - 1 && !new RegExp ('^' + fct).test (cmd[index + 1])) {
      fct = fct.slice (0, -1);
      line = fct;
    }
  });

  console.log ('\n' + cmdDump.join ('') + '\n');
  self.sc.uiPrompt.rl.prompt ();
  self.sc.uiPrompt.rl.write (line);
};

exports = module.exports = AutoComplete;
<commit_msg>Vert-align the commands when it needs more than one line.<commit_after>'use strict';

/**
 * AutoComplete constructor.
 */
function AutoComplete (shellcraft) {
  this.minLength = 0;
  this.cmdList   = [];
  this.sc        = shellcraft;
  this.extraLength = 4;

  this.reload ();
}

/**
 * @api private
 */
AutoComplete.prototype.ttyWidth = function () {
  if (process.stdout.getWindowSize) {
    return process.stdout.getWindowSize ()[0];
  }

  var tty = require ('tty');
  return tty.getWindowSize ? tty.getWindowSize ()[1] : 0;
};

AutoComplete.prototype.reload = function () {
  var self = this;

  self.cmdList = [];

  /* Extract only the commands (ignore private and options). */
  Object.keys (Object.getPrototypeOf (self.sc.arguments)).forEach (function (fct) {
    if (self.sc.arguments.hasOwnProperty (fct) ||
        /^_/.test (fct) ||
        self.sc.arguments[fct].type () !== 'command') {
      return;
    }

    if (fct.length > self.minLength) {
      self.minLength = fct.length;
    }
    self.cmdList.push (fct);
  });
};

AutoComplete.prototype.begin = function () {
  var self = this;

  var cmd = [];
  if (self.sc.uiPrompt.rl.line.length) {
    self.cmdList.forEach (function (fct) {
      var res = new RegExp ('^' + self.sc.uiPrompt.rl.line).test (fct);
      if (res) {
        cmd.push (fct);
      }
    });
  }

  if (cmd.length === 1) {
    /* Simple auto-complete (one command). */
    self.sc.uiPrompt.rl.write (null, {ctrl: true, name: 'u'});
    self.sc.uiPrompt.rl.write (cmd[0] + ' ');
    return;
  }

  /* Show all commands if empty. */
  if (!cmd.length) {
    cmd = self.cmdList;
  }

  var line = self.sc.uiPrompt.rl.line;
  self.sc.uiPrompt.rl.write (null, {ctrl: true, name: 'u'});

  var cmdDump = [];

  cmd.forEach (function (fct, index) {
    /* Append spaces for vert-align in the dump. */
    cmdDump[index] = fct + new Array (self.minLength - fct.length + self.extraLength).join (' ');

    /* Detect the smaller common string between all commands. */
    while (index < cmd.length - 1 && !new RegExp ('^' + fct).test (cmd[index + 1])) {
      fct = fct.slice (0, -1);
      line = fct;
    }
  });

  /* Vert-align correctly the commands line-by-line. */
  var w  = self.ttyWidth () || cmdDump.length * (self.minLength + self.extraLength);
  var nb = parseInt (w / (self.minLength + self.extraLength));

  process.stdout.write ('\n');
  var i = 0;
  cmdDump.forEach (function (fct) {
    if (i && (i % nb) === 0) {
      process.stdout.write ('\n');
    }
    process.stdout.write (fct);
    ++i;
  });
  process.stdout.write ('\n\n');

  /* Then prompt with the completion. */
  self.sc.uiPrompt.rl.prompt ();
  self.sc.uiPrompt.rl.write (line);
};

exports = module.exports = AutoComplete;
<|endoftext|>


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

  var dom = app.dom || require('../dom.js');
  var Component = app.Component || require('./component.js');

  var ModulePort = Component.inherits(function(props) {
    this.label = this.prop(props.label);
    this.name = this.prop(props.name);
    this.type = this.prop(props.type);
    this.plugDisabled = this.prop(props.plugDisabled);
    this.socketDisabled = this.prop(props.socketDisabled);
    this.visible = this.prop(false);
    this.top = this.prop(0);
    this.height = this.prop(44);
    this.socketConnected = this.prop(false);
    this.labelHighlighted = this.prop(false);
    this.plugHighlighted = this.prop(false);
    this.socketHighlighted = this.prop(false);
    this.isMoving = this.prop(false);
    this.listItemElement = this.prop(this.renderListItem());
    this.parentListElement = this.prop(props.parentListElement);
    this.optionElement = this.prop(this.renderOption());
    this.parentOptGroupElement = this.prop(props.parentOptGroupElement);

    // update list-item in redrawToggleClass() method
    this.element = this.listItemElement;
  });

  ModulePort.prototype.plugElement = function() {
    return dom.child(this.listItemElement(), 0);
  };

  ModulePort.prototype.socketElement = function() {
    return dom.child(this.listItemElement(), 1);
  };

  ModulePort.prototype.socketHandleElement = function() {
    return dom.child(this.listItemElement(), 1, 0);
  };

  ModulePort.prototype.labelElement = function() {
    return dom.child(this.listItemElement(), 2);
  };

  ModulePort.prototype.hideButtonElement = function() {
    return dom.child(this.listItemElement(), 3);
  };

  ModulePort.prototype.hideDisabled = function() {
    // don't hide label-highlighted port
    return this.labelHighlighted();
  };

  ModulePort.prototype.middle = function() {
    return this.top() + this.height() / 2;
  };

  ModulePort.prototype.bottom = function() {
    return this.top() + this.height();
  };

  ModulePort.prototype.renderListItem = function() {
    var element = dom.el('
');
    dom.addClass(element, 'module-port');
    dom.data(element, 'type', this.type());
    dom.html(element,
      '

' +
      '

' +
      '

' +
      ''
    );
    dom.text(dom.child(element, 2), this.label());
    return element;
  };

  ModulePort.prototype.renderOption = function() {
    var element = dom.el('<option>');
    dom.text(element, this.label());
    dom.value(element, this.name());
    return element;
  };

  ModulePort.prototype.redraw = function() {
    this.redrawVisibility();
    this.redrawPosition();
    this.redrawPlug();
    this.redrawSocket();
    this.redrawHideButton();
    this.redrawToggleClasses();
  };

  ModulePort.prototype.redrawVisibility = function() {
    this.redrawProp('visible', function(visible) {
      if (visible) {
        dom.remove(this.optionElement());
        dom.append(this.parentListElement(), this.listItemElement());
      } else {
        dom.remove(this.listItemElement());
        dom.append(this.parentOptGroupElement(), this.optionElement());
      }
    });
  };

  ModulePort.prototype.redrawPosition = function() {
    this.redrawProp('top', function(top) {
      dom.translateY(this.listItemElement(), top);
    });
  };

  ModulePort.prototype.redrawPlug = function() {
    this.redrawProp('plugDisabled', function(plugDisabled) {
      dom.toggleClass(this.plugElement(), 'hide', plugDisabled);
    });

    this.redrawProp('plugHighlighted', function(plugHighlighted) {
      dom.toggleClass(this.plugElement(), 'highlighted', plugHighlighted);
    });
  };

  ModulePort.prototype.redrawSocket = function() {
    this.redrawProp('socketDisabled', function(socketDisabled) {
      dom.toggleClass(this.socketElement(), 'hide', socketDisabled);
    });

    this.redrawProp('socketHighlighted', function(socketHighlighted) {
      dom.toggleClass(this.socketElement(), 'highlighted', socketHighlighted);
      dom.toggleClass(this.socketHandleElement(), 'highlighted', socketHighlighted);
    });

    this.redrawProp('socketConnected', function(socketConnected) {
      dom.toggleClass(this.socketHandleElement(), 'hide', !socketConnected);
    });
  };

  ModulePort.prototype.redrawHideButton = function() {
    this.redrawProp('hideDisabled', function(hideDisabled) {
      dom.toggleClass(this.hideButtonElement(), 'disabled', hideDisabled);
    });
  };

  ModulePort.prototype.redrawToggleClasses = function() {
    this.redrawToggleClass('labelHighlighted', 'label-highlighted');
    this.redrawToggleClass('isMoving', 'moving');
  };

  ModulePort.TYPE_PROP = 'prop';
  ModulePort.TYPE_EVENT = 'event';

  ModulePort.PLUG_OFFSET_X = 261;
  ModulePort.PLUG_WIDTH = 50;

  ModulePort.SOCKET_OFFSET_X = -25;
  ModulePort.SOCKET_WIDTH = 50;

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = ModulePort;
  } else {
    app.ModulePort = ModulePort;
  }
})(this.app || (this.app = {}));
<commit_msg>Make method to update list-item of module-port<commit_after>(function(app) {
  'use strict';

  var dom = app.dom || require('../dom.js');
  var Component = app.Component || require('./component.js');

  var ModulePort = Component.inherits(function(props) {
    this.label = this.prop(props.label);
    this.name = this.prop(props.name);
    this.type = this.prop(props.type);
    this.plugDisabled = this.prop(props.plugDisabled);
    this.socketDisabled = this.prop(props.socketDisabled);
    this.visible = this.prop(false);
    this.top = this.prop(0);
    this.height = this.prop(44);
    this.socketConnected = this.prop(false);
    this.labelHighlighted = this.prop(false);
    this.plugHighlighted = this.prop(false);
    this.socketHighlighted = this.prop(false);
    this.isMoving = this.prop(false);
    this.listItemElement = this.prop(this.renderListItem());
    this.parentListElement = this.prop(props.parentListElement);
    this.optionElement = this.prop(this.renderOption());
    this.parentOptGroupElement = this.prop(props.parentOptGroupElement);
  });

  ModulePort.prototype.plugElement = function() {
    return dom.child(this.listItemElement(), 0);
  };

  ModulePort.prototype.socketElement = function() {
    return dom.child(this.listItemElement(), 1);
  };

  ModulePort.prototype.socketHandleElement = function() {
    return dom.child(this.listItemElement(), 1, 0);
  };

  ModulePort.prototype.labelElement = function() {
    return dom.child(this.listItemElement(), 2);
  };

  ModulePort.prototype.hideButtonElement = function() {
    return dom.child(this.listItemElement(), 3);
  };

  ModulePort.prototype.hideDisabled = function() {
    // don't hide label-highlighted port
    return this.labelHighlighted();
  };

  ModulePort.prototype.middle = function() {
    return this.top() + this.height() / 2;
  };

  ModulePort.prototype.bottom = function() {
    return this.top() + this.height();
  };

  ModulePort.prototype.renderListItem = function() {
    var element = dom.el('
');
    dom.addClass(element, 'module-port');
    dom.data(element, 'type', this.type());
    dom.html(element,
      '

' +
      '

' +
      '

' +
      ''
    );
    dom.text(dom.child(element, 2), this.label());
    return element;
  };

  ModulePort.prototype.renderOption = function() {
    var element = dom.el('<option>');
    dom.text(element, this.label());
    dom.value(element, this.name());
    return element;
  };

  ModulePort.prototype.redraw = function() {
    this.redrawVisibility();
    this.redrawListItem();
    this.redrawPlug();
    this.redrawSocket();
    this.redrawHideButton();
  };

  ModulePort.prototype.redrawVisibility = function() {
    this.redrawProp('visible', function(visible) {
      if (visible) {
        dom.remove(this.optionElement());
        dom.append(this.parentListElement(), this.listItemElement());
      } else {
        dom.remove(this.listItemElement());
        dom.append(this.parentOptGroupElement(), this.optionElement());
      }
    });
  };

  ModulePort.prototype.redrawListItem = function() {
    this.redrawProp('top', function(top) {
      dom.translateY(this.listItemElement(), top);
    });

    this.redrawProp('labelHighlighted', function(labelHighlighted) {
      dom.toggleClass(this.listItemElement(), 'label-highlighted', labelHighlighted);
    });

    this.redrawProp('isMoving', function(isMoving) {
      dom.toggleClass(this.listItemElement(), 'moving', isMoving);
    });
  };

  ModulePort.prototype.redrawPlug = function() {
    this.redrawProp('plugDisabled', function(plugDisabled) {
      dom.toggleClass(this.plugElement(), 'hide', plugDisabled);
    });

    this.redrawProp('plugHighlighted', function(plugHighlighted) {
      dom.toggleClass(this.plugElement(), 'highlighted', plugHighlighted);
    });
  };

  ModulePort.prototype.redrawSocket = function() {
    this.redrawProp('socketDisabled', function(socketDisabled) {
      dom.toggleClass(this.socketElement(), 'hide', socketDisabled);
    });

    this.redrawProp('socketHighlighted', function(socketHighlighted) {
      dom.toggleClass(this.socketElement(), 'highlighted', socketHighlighted);
      dom.toggleClass(this.socketHandleElement(), 'highlighted', socketHighlighted);
    });

    this.redrawProp('socketConnected', function(socketConnected) {
      dom.toggleClass(this.socketHandleElement(), 'hide', !socketConnected);
    });
  };

  ModulePort.prototype.redrawHideButton = function() {
    this.redrawProp('hideDisabled', function(hideDisabled) {
      dom.toggleClass(this.hideButtonElement(), 'disabled', hideDisabled);
    });
  };

  ModulePort.TYPE_PROP = 'prop';
  ModulePort.TYPE_EVENT = 'event';

  ModulePort.PLUG_OFFSET_X = 261;
  ModulePort.PLUG_WIDTH = 50;

  ModulePort.SOCKET_OFFSET_X = -25;
  ModulePort.SOCKET_WIDTH = 50;

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