<commit_before>/* global chrome */
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { optionMap } from './optionMap';

class Options extends Component {
  constructor(props) {
    super(props);
    let version = '1.2.0';
    if (typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined' && typeof chrome.runtime.getManifest !== 'undefined') {
      version = chrome.runtime.getManifest().version;
    }
    this.state = {
      version
    };
  }

  optionUpdater = (type, name) => {
    return (e) => {
      if (type === 'checkbox') {
        this.props.setOption(name, e.target.checked);
      } else if (type === 'input') {
        console.log(e);
        this.props.setOption(name, e.target.value);
      }
    }
  }

  render() {
    const versionHistory = [
      {
        version: '1.2',
        changes: [
        'three-column view for GTM & Launch',
        'improvements to dark mode',
        ]
      },
      {
        version: '1.1',
        changes: [
        'initial support for Adobe Launch',
        'toggle friendly param names',
        'toggle param URL decoding',
        ]
      },
      {
        version: '1.0',
        changes: [
        'rewritten UI',
        'import/export functionality',
        'auto collapse gtm.*',
        'fix displayed GTM IDs',
        'misc. bug fixes'
        ]
      }
    ];

    return (
      <div id={`sub${this.props.index}`} className={`pure-menu pure-menu-open`}>

            dataslayer Options

              {this.state.version}

                {
                  Object.keys(optionMap).map((section) =>
                    (<form className="pure-form pure-form-stacked" key={section}>

                              {section}

                      {
                        optionMap[section].map((option) =>
                        (

                                {
                                  option.type === 'checkbox' &&
                                  (

                                      <input
                                        id={option.name}
                                        disabled={option.dependsOn && this.props.options[option.dependsOn] !== option.dependsOnValue}
                                        type="checkbox"
                                        checked={this.props.options[option.name]}
                                        onChange={this.optionUpdater('checkbox', option.name)}
                                      />
                                      {option.description}

                                  	)
                                }
                                {
                                  option.type === 'input' &&
                                  (

                                    {option.description}

                                    <input
                                      disabled={option.dependsOn && this.props.options[option.dependsOn] !== option.dependsOnValue}
                                      placeholder={option.placeholder}
                                      defaultValue={(this.props.options[option.name] || []).join(';')}
                                      onChange={this.optionUpdater('input', option.name)}
                                    />

                                  	)
                                }
                                {
                                  option.type === 'number' &&
                                  (

                                    {option.description}

                                    <input
                                      disabled={option.dependsOn && this.props.options[option.dependsOn] !== option.dependsOnValue}
                                      placeholder={option.placeholder}
                                      type="number"
                                      defaultValue={this.props.options[option.name]}
                                      onChange={this.optionUpdater('input', option.name)}
                                      max={option.max}
                                      min={option.min}
                                    />

                                  	)
                                }

)
                        )
                      }
                    </form>)
                  )
                }

                        About

                        by
                        Sean Adams

                        contributors

                        documentation
                        dataslayer.org/documentation

                        open source
                        GitHub

                        report bug / request feature
                        GitHub issues (preferred)

                        email

                        leave a review

                            Chrome Web Store

                        links
                        dataslayer.org

                            Chrome Web Store

                            release notes

                        made with
                        React

                        Pure

                        jQuery

                        data-layer-helper

                            Open Sans

                            (license)

                            Madebyoliver icons
                            from www.flaticon.com

What's New

                            x.x.* are bug fix releases

                        {
                          versionHistory.map(({ version, changes }) =>
                            (

                              {version}

                                {changes.map((note, i) => (<span key={`${note}i`}>{note}
))}

)
                          )
                        }

    );
  }
}

Options.propTypes = {
  options: PropTypes.object,
  setOption: PropTypes.func,
};

export default Options;
<commit_msg>additional changes<commit_after>/* global chrome */
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { optionMap } from './optionMap';

class Options extends Component {
  constructor(props) {
    super(props);
    let version = '1.2.0';
    if (typeof chrome !== 'undefined' && typeof chrome.runtime !== 'undefined' && typeof chrome.runtime.getManifest !== 'undefined') {
      version = chrome.runtime.getManifest().version;
    }
    this.state = {
      version
    };
  }

  optionUpdater = (type, name) => {
    return (e) => {
      if (type === 'checkbox') {
        this.props.setOption(name, e.target.checked);
      } else if (type === 'input') {
        console.log(e);
        this.props.setOption(name, e.target.value);
      }
    }
  }

  render() {
    const versionHistory = [
      {
        version: '1.2',
        changes: [
        'three-column view for GTM & Launch',
        'improvements to dark mode',
        'fixes for object watching',
        ]
      },
      {
        version: '1.1',
        changes: [
        'initial support for Adobe Launch',
        'toggle friendly param names',
        'toggle param URL decoding',
        ]
      },
      {
        version: '1.0',
        changes: [
        'rewritten UI',
        'import/export functionality',
        'auto collapse gtm.*',
        'fix displayed GTM IDs',
        'misc. bug fixes'
        ]
      }
    ];

    return (
      <div id={`sub${this.props.index}`} className={`pure-menu pure-menu-open`}>

            dataslayer Options

              {this.state.version}

                {
                  Object.keys(optionMap).map((section) =>
                    (<form className="pure-form pure-form-stacked" key={section}>

                              {section}

                      {
                        optionMap[section].map((option) =>
                        (

                                {
                                  option.type === 'checkbox' &&
                                  (

                                      <input
                                        id={option.name}
                                        disabled={option.dependsOn && this.props.options[option.dependsOn] !== option.dependsOnValue}
                                        type="checkbox"
                                        checked={this.props.options[option.name]}
                                        onChange={this.optionUpdater('checkbox', option.name)}
                                      />
                                      {option.description}

                                  	)
                                }
                                {
                                  option.type === 'input' &&
                                  (

                                    {option.description}

                                    <input
                                      disabled={option.dependsOn && this.props.options[option.dependsOn] !== option.dependsOnValue}
                                      placeholder={option.placeholder}
                                      defaultValue={(this.props.options[option.name] || []).join(';')}
                                      onChange={this.optionUpdater('input', option.name)}
                                    />

                                  	)
                                }
                                {
                                  option.type === 'number' &&
                                  (

                                    {option.description}

                                    <input
                                      disabled={option.dependsOn && this.props.options[option.dependsOn] !== option.dependsOnValue}
                                      placeholder={option.placeholder}
                                      type="number"
                                      defaultValue={this.props.options[option.name]}
                                      onChange={this.optionUpdater('input', option.name)}
                                      max={option.max}
                                      min={option.min}
                                    />

                                  	)
                                }

)
                        )
                      }
                    </form>)
                  )
                }

                        About

                        by
                        Sean Adams

                        contributors

                        documentation
                        dataslayer.org/documentation

                        open source
                        GitHub

                        report bug / request feature
                        GitHub issues (preferred)

                        email

                        leave a review

                            Chrome Web Store

                        links
                        dataslayer.org

                            Chrome Web Store

                            release notes

                        made with
                        React

                        Pure

                        jQuery

                        data-layer-helper

                            Open Sans

                            (license)

                            Madebyoliver icons
                            from www.flaticon.com

What's New

                            x.x.* are bug fix releases

                        {
                          versionHistory.map(({ version, changes }) =>
                            (

                              {version}

                                {changes.map((note, i) => (<span key={`${note}i`}>{note}
))}

)
                          )
                        }

    );
  }
}

Options.propTypes = {
  options: PropTypes.object,
  setOption: PropTypes.func,
};

export default Options;
<|endoftext|>


<commit_before>/**
 * @file
 * @author zdying
 */

'use strict';

var fs = require('fs');
var path = require('path');

var logger = log.namespace('Server');
var Compiler = require('../../compiler');
var Master = require('../../compiler');

var imagePath = path.resolve(__dirname, '..', 'source', 'image');
var docSVG = fs.readFileSync(path.resolve(imagePath, 'Document.svg'));
var fileSVG = fs.readFileSync(path.resolve(imagePath, 'File.svg'));
var folderSVG = fs.readFileSync(path.resolve(imagePath, 'Folder.svg'));

module.exports = function(req, res, next){
    var url = req.url;
    // var filePath = path.resolve('.' + url);
    var filePath = __hii__.cwd + url;
    var projInfo = this.getProjectInfoFromURL(url);

    logger.debug('projInfo:' + JSON.stringify(projInfo));

    if(projInfo){
        var projectName = projInfo.projectName;
        var fileExt = projInfo.fileExt;
        var env = projInfo.env;
        var compiler = this.compilers[projectName];
        var configPath = path.join(__hii__.cwd, projectName, 'hii.config.js');
        var root = path.join(__hii__.cwd, projectName);

        // 第一次请求这个项目，新建一个compiler
        // if(!compiler){
        //     compiler = this.compilers[projectName] = new Compiler(projectName, '', 'loc');
        // }

        if(fileExt === 'scss'){
            // 编译sass文件
            return compiler.compileSASS(filePath, function(err, css, time, result){
                if(err){
                    res.statusCode = 500;
                    res.end(err.stack || err.message)
                }else{
                    res.setHeader('Content-Type', 'text/css');
                    res.end(css);
                    logger.debug('*.sass', '-', filePath.bold, 'compiled', (time + 'ms').magenta);
                }
                logger.access(req);
            });
        }else if(fileExt === 'js'){
            if(env === 'prd' || req.url.indexOf('hot-update.js') !== -1){
                // method: 1
                // return compiler.compile(function(){
                //     this.sendCompiledFile(req, projInfo)
                // }.bind(this))

                // method: 2
                Master.compile(projectName, root, 'loc', { watch: true }, function(){
                    this.sendCompiledFile(req, projInfo)
                }.bind(this));
            }else if(env === 'dev'){
                filePath = filePath.replace(/@(\w+)\.(\w+)/, '@dev.$2');

                logger.debug(req.url, '==>', filePath);

                if(fs.statSync(filePath).isFile()){
                    this.sendFile(req, filePath)
                }
            }else if(env === 'src' || env === 'loc'){
                //TODO 这里需要处理一下'loc'
                this.sendFile(req)
            }
        }else if(fileExt === 'css'){
            if(env === 'src' && fs.existsSync(filePath)){
                this.sendFile(req, filePath);
            }else{
                return Master.compile(projectName, root, 'loc', { watch: true }, function(){
                    var userConfig = require(configPath);
                    var entry = userConfig.entry;
                    var entries = Object.keys(entry);
                    var fileName = ((projInfo.folder || '') + '/' + projInfo.fileName).replace('/', '');
                    var compiledFilePath = path.join(
                        __hii__.codeTmpdir,
                        req.url.replace(/@(\w+)\.(\w+)/, '.$2').replace(/[\\\/](prd|dev|src)[\\\/]/, '/loc/')
                    );

                    if(entries.indexOf(fileName) !== -1){
                        // 是入口CSS文件
                        if(fs.existsSync(compiledFilePath)){
                            this.sendFile(req, compiledFilePath)
                        }else{
                            // 处理css文件
                            res.setHeader('Content-Type', 'text/css');
                            logger.debug('css -', filePath.bold, 'replaced');
                            res.end('/* The `css` code in development environment has been moved to the `js` file */');
                            logger.access(req);
                        }
                    }else{
                        // will return 404
                        this.sendFile(req, filePath);
                    }
                }.bind(this));
            }
        }else{
            // 其它文件
            filePath = filePath.replace(/[\\\/]prd[\\\/]/, '/src/');

            logger.debug(req.url, '==>', filePath);
            try{
                if(fs.statSync(filePath).isFile()){
                    this.sendFile(req, filePath)
                }
            }catch(e){
                res.statusCode = 404;
                res.end('404 Not Found');
                logger.error(e);
                logger.access(req);
            }
        }
    }else{
        try{
            var stat = fs.statSync(filePath);
            if(stat.isDirectory()){
                fs.readdir(filePath, function(err, files){
                    if(err){
                        logger.error(err);
                    }else{
                        res.setHeader('Content-Type', 'text/html');

                        var html = [
                            '',
                            '<meta charset="utf-8">',
                            '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">',
                            '',
                            '',
                            '
'
                        ];
                        html.push('
');
                        html.push(      '', folderSVG, '../');
                        html.push('
');
                        var filesItem = files.map(function(fileName){
                            if(fileName.slice(0, 1) === '.'){
                                logger.debug('hide system file/directory', fileName.bold);
                                // 不显示系统隐藏文件
                                return
                            }

                            var isFile = fs.statSync(filePath + '/' + fileName).isFile();

                            return [
                                '
',
                                '',
                                isFile ? (fileName.indexOf('.') === -1 ? fileSVG : docSVG) : folderSVG,
                                fileName,
                                '',
                                '
'
                            ].join('')
                        });

                        html.push.apply(html, filesItem);
                        html.push('
');
                    }

                    res.end(html.join(''));

                    logger.access(req);
                });
            }else{
                this.sendFile(req)
            }
        }catch(e){
            res.statusCode = 404;
            res.end('404 Not Found');

            logger.error(e);
            logger.access(req);
        }
    }
};<commit_msg>格式化代码<commit_after>/**
 * @file
 * @author zdying
 */

'use strict';

var fs = require('fs');
var path = require('path');

var logger = log.namespace('Server');
var Compiler = require('../../compiler');
var Master = require('../../compiler');

var imagePath = path.resolve(__dirname, '..', 'source', 'image');
var docSVG = fs.readFileSync(path.resolve(imagePath, 'Document.svg'));
var fileSVG = fs.readFileSync(path.resolve(imagePath, 'File.svg'));
var folderSVG = fs.readFileSync(path.resolve(imagePath, 'Folder.svg'));

module.exports = function(req, res, next){
    var url = req.url;
    // var filePath = path.resolve('.' + url);
    var filePath = __hii__.cwd + url;
    var projInfo = this.getProjectInfoFromURL(url);

    logger.debug('projInfo:' + JSON.stringify(projInfo));

    if(projInfo){
        var projectName = projInfo.projectName;
        var fileExt = projInfo.fileExt;
        var env = projInfo.env;
        var compiler = this.compilers[projectName];
        var configPath = path.join(__hii__.cwd, projectName, 'hii.config.js');
        var root = path.join(__hii__.cwd, projectName);

        // 第一次请求这个项目，新建一个compiler
        // if(!compiler){
        //     compiler = this.compilers[projectName] = new Compiler(projectName, '', 'loc');
        // }

        if(fileExt === 'scss'){
            // 编译sass文件
            return compiler.compileSASS(filePath, function(err, css, time, result){
                if(err){
                    res.statusCode = 500;
                    res.end(err.stack || err.message)
                }else{
                    res.setHeader('Content-Type', 'text/css');
                    res.end(css);
                    logger.debug('*.sass', '-', filePath.bold, 'compiled', (time + 'ms').magenta);
                }
                logger.access(req);
            });
        }else if(fileExt === 'js'){
            if(env === 'prd' || req.url.indexOf('hot-update.js') !== -1){
                // method: 1
                // return compiler.compile(function(){
                //     this.sendCompiledFile(req, projInfo)
                // }.bind(this))

                // method: 2
                Master.compile(projectName, root, 'loc', { watch: true }, function(){
                    this.sendCompiledFile(req, projInfo)
                }.bind(this));
            }else if(env === 'dev'){
                filePath = filePath.replace(/@(\w+)\.(\w+)/, '@dev.$2');

                logger.debug(req.url, '==>', filePath);

                if(fs.statSync(filePath).isFile()){
                    this.sendFile(req, filePath)
                }
            }else if(env === 'src' || env === 'loc'){
                //TODO 这里需要处理一下'loc'
                this.sendFile(req)
            }
        }else if(fileExt === 'css'){
            if(env === 'src' && fs.existsSync(filePath)){
                this.sendFile(req, filePath);
            }else{
                return Master.compile(projectName, root, 'loc', { watch: true }, function(){
                    var userConfig = require(configPath);
                    var entry = userConfig.entry;
                    var entries = Object.keys(entry);
                    var fileName = ((projInfo.folder || '') + '/' + projInfo.fileName).replace('/', '');
                    var compiledFilePath = path.join(
                        __hii__.codeTmpdir,
                        req.url.replace(/@(\w+)\.(\w+)/, '.$2').replace(/[\\\/](prd|dev|src)[\\\/]/, '/loc/')
                    );

                    if(entries.indexOf(fileName) !== -1){
                        // 是入口CSS文件
                        if(fs.existsSync(compiledFilePath)){
                            this.sendFile(req, compiledFilePath)
                        }else{
                            // 处理css文件
                            res.setHeader('Content-Type', 'text/css');
                            logger.debug('css -', filePath.bold, 'replaced');
                            res.end('/* The `css` code in development environment has been moved to the `js` file */');
                            logger.access(req);
                        }
                    }else{
                        // will return 404
                        this.sendFile(req, filePath);
                    }
                }.bind(this));
            }
        }else{
            // 其它文件
            filePath = filePath.replace(/[\\\/]prd[\\\/]/, '/src/');

            logger.debug(req.url, '==>', filePath);
            try{
                if(fs.statSync(filePath).isFile()){
                    this.sendFile(req, filePath)
                }
            }catch(e){
                res.statusCode = 404;
                res.end('404 Not Found');
                logger.error(e);
                logger.access(req);
            }
        }
    }else{
        try{
            var stat = fs.statSync(filePath);
            if(stat.isDirectory()){
                fs.readdir(filePath, function(err, files){
                    if(err){
                        logger.error(err);
                    }else{
                        res.setHeader('Content-Type', 'text/html');

                        var html = [
                            '',
                                '<meta charset="utf-8">',
                                '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">',
                            '',
                            '',
                            '
'
                        ];
                        html.push('
');
                        html.push(      '', folderSVG, '../');
                        html.push('
');
                        var filesItem = files.map(function(fileName){
                            if(fileName.slice(0, 1) === '.'){
                                logger.debug('hide system file/directory', fileName.bold);
                                // 不显示系统隐藏文件
                                return
                            }

                            var isFile = fs.statSync(filePath + '/' + fileName).isFile();

                            return [
                                '
',
                                    '',
                                    isFile ? (fileName.indexOf('.') === -1 ? fileSVG : docSVG) : folderSVG,
                                    fileName,
                                    '',
                                '
'
                            ].join('')
                        });

                        html.push.apply(html, filesItem);
                        html.push('
');
                    }

                    res.end(html.join(''));

                    logger.access(req);
                });
            }else{
                this.sendFile(req)
            }
        }catch(e){
            res.statusCode = 404;
            res.end('404 Not Found');

            logger.error(e);
            logger.access(req);
        }
    }
};<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be di<commit_msg>Nearly got it<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be dif<|endoftext|>


<commit_before>/* global Y, Element */
'use strict'

var diff = require('fast-diff')

function extend (Y) {
  Y.requestModules(['Array']).then(function () {
    class YText extends Y.Array.typeDefinition['class'] {
      constructor (os, _model, _content) {
        super(os, _model, _content)
        this.textfields = []
        this.aceInstances = []
      }
      _destroy () {
        this.unbindAll()
        this.textfields = null
        this.aceInstances = null
        super._destroy()
      }
      toString () {
        return this._content.map(function (c) {
          return c.val
        }).join('')
      }
      insert (pos, content) {
        super.insert(pos, content.split(''))
      }
      unbindAll () {
        for (let i = this.textfields.length - 1; i >= 0; i--) {
          this.unbindTextarea(this.textfields[i].editor)
        }
        for (let i = this.aceInstances.length - 1; i >= 0; i--) {
          this.unbindAce(this.aceInstances[i].editor)
        }
      }
      unbindAce (ace) {
        var i = this.aceInstances.findIndex(function (binding) {
          return binding.editor === ace
        })
        if (i >= 0) {
          var binding = this.aceInstances[i]
          this.unobserve(binding.yCallback)
          binding.editor.off('change', binding.aceCallback)
          this.aceInstances.splice(i, 1)
        }
      }
      bindAce (ace, options) {
        var self = this

        // this function makes sure that either the
        // ace event is executed, or the yjs observer is executed
        var token = true
        function mutualExcluse (f) {
          if (token) {
            token = false
            try {
              f()
            } catch (e) {
              token = true
              throw new Error(e)
            }
            token = true
          }
        }
        ace.markers = []
        var disableMarkers = false

        if (typeof options === 'object') {
          if (typeof options.disableMarkers !== 'undefined') {
            disableMarkers = options.disableMarkers
          }
        }

        ace.setValue(this.toString())

        function aceCallback (delta) {
          mutualExcluse(function () {
            var start = 0
            var length = 0

            var aceDocument = ace.getSession().getDocument()
            if (delta.action === 'insert') {
              start = aceDocument.positionToIndex(delta.start, 0)
              self.insert(start, delta.lines.join('\n'))
            } else if (delta.action === 'remove') {
              start = aceDocument.positionToIndex(delta.start, 0)
              length = delta.lines.join('\n').length
              self.delete(start, length)
            }
          })
        }
        ace.on('change', aceCallback)

        if (!disableMarkers) {
          if (this.inteval) {
            clearInterval(this.inteval)
          }
          this.inteval = setInterval(function () {
            var i = 0
            var now = Date.now()
            var timeVisible = 800

            while (i < ace.markers.length) {
              var marker = ace.markers[i]

              if (marker.timestamp + timeVisible < now) {
                ace.getSession().removeMarker(marker.id)
                ace.markers.splice(i, 1)
                i--
              }
              i++
            }
          }, 1000)
        }
        var Range = window.ace.require('ace/range').Range
        function setMarker (start, end, klazz) {
          if (disableMarkers) {
            return
          }
          var offset = 0
          if (start.row === end.row && start.column === end.column) {
            offset = 1
          }
          var range = new Range(start.row, start.column, end.row, end.column + offset)
          var marker = ace.session.addMarker(range, klazz, 'text')
          ace.markers.push({id: marker, timestamp: Date.now()})
        }

        function yCallback (event) {
          var aceDocument = ace.getSession().getDocument()
          mutualExcluse(function () {
            if (event.type === 'insert') {
              let start = aceDocument.indexToPosition(event.index, 0)
              let end = aceDocument.indexToPosition(event.index + event.length, 0)
              aceDocument.insert(start, event.values.join(''))

              setMarker(start, end, 'inserted')
            } else if (event.type === 'delete') {
              let start = aceDocument.indexToPosition(event.index, 0)
              let end = aceDocument.indexToPosition(event.index + event.length, 0)
              var range = new Range(start.row, start.column, end.row, end.column)
              aceDocument.remove(range)

              setMarker(start, end, 'deleted')
            }
          })
        }
        this.observe(yCallback)
        this.aceInstances.push({
          editor: ace,
          yCallback: yCallback,
          aceCallback: aceCallback
        })
      }
      bind () {
        var e = arguments[0]
        if (e instanceof Element) {
          this.bindTextarea.apply(this, arguments)
        } else if (e != null && e.session != null && e.getSession != null && e.setValue != null) {
          this.bindAce.apply(this, arguments)
        } else {
          console.error('Cannot bind, unsupported editor!')
        }
      }
      unbindTextarea (textarea) {
        var i = this.textfields.findIndex(function (binding) {
          return binding.editor === textarea
        })
        if (i >= 0) {
          var binding = this.textfields[i]
          this.unobserve(binding.yCallback)
          var e = binding.editor
          e.oninput = null
          this.textfields.splice(i, 1)
        }
      }
      bindTextarea (textfield, domRoot) {
        domRoot = domRoot || window; // eslint-disable-line
        if (domRoot.getSelection == null) {
          domRoot = window; // eslint-disable-line
        }

        // don't duplicate!
        for (var t = 0; t < this.textfields.length; t++) {
          if (this.textfields[t].editor === textfield) {
            return
          }
        }
        // this function makes sure that either the
        // textfieldt event is executed, or the yjs observer is executed
        var token = true
        function mutualExcluse (f) {
          if (token) {
            token = false
            try {
              f()
            } catch (e) {
              token = true
              throw new Error(e)
            }
            token = true
          }
        }

        var self = this
        textfield.value = this.toString()

        var createRange, writeRange, writeContent, getContent
        if (textfield.selectionStart != null && textfield.setSelectionRange != null) {
          createRange = function (fix) {
            var left = textfield.selectionStart
            var right = textfield.selectionEnd
            if (fix != null) {
              left = fix(left)
              right = fix(right)
            }
            return {
              left: left,
              right: right
            }
          }
          writeRange = function (range) {
            writeContent(self.toString())
            textfield.setSelectionRange(range.left, range.right)
          }
          writeContent = function (content) {
            textfield.value = content
          }
          getContent = function () {
            return textfield.value
          }
        } else {
          createRange = function (fix) {
            var range = {}
            var s = domRoot.getSelection()
            var clength = textfield.textContent.length
            range.left = Math.min(s.anchorOffset, clength)
            range.right = Math.min(s.focusOffset, clength)
            if (fix != null) {
              range.left = fix(range.left)
              range.right = fix(range.right)
            }
            var editedElement = s.focusNode
            if (editedElement === textfield || editedElement === textfield.childNodes[0]) {
              range.isReal = true
            } else {
              range.isReal = false
            }
            return range
          }

          writeRange = function (range) {
            writeContent(self.toString())
            var textnode = textfield.childNodes[0]
            if (range.isReal && textnode != null) {
              if (range.left < 0) {
                range.left = 0
              }
              range.right = Math.max(range.left, range.right)
              if (range.right > textnode.length) {
                range.right = textnode.length
              }
              range.left = Math.min(range.left, range.right)
              var r = document.createRange(); // eslint-disable-line
              r.setStart(textnode, range.left)
              r.setEnd(textnode, range.right)
              var s = domRoot.getSelection(); // eslint-disable-line
              s.removeAllRanges()
              s.addRange(r)
            }
          }
          writeContent = function (content) {
            textfield.innerText = content
            /*
            var contentArray = content.replace(new RegExp('\n', 'g'), ' ').split(' '); // eslint-disable-line
            textfield.innerText = ''
            for (var i = 0; i < contentArray.length; i++) {
              var c = contentArray[i]
              textfield.innerText += c
              if (i !== contentArray.length - 1) {
                textfield.innerHTML += ' '
              }
            }
            */
          }
          getContent = function () {
            return textfield.innerText
          }
        }
        writeContent(this.toString())

        function yCallback (event) {
          mutualExcluse(() => {
            var oPos, fix
            if (event.type === 'insert') {
              oPos = event.index
              fix = function (cursor) { // eslint-disable-line
                if (cursor <= oPos) {
                  return cursor
                } else {
                  cursor += 1
                  return cursor
                }
              }
              var r = createRange(fix)
              writeRange(r)
            } else if (event.type === 'delete') {
              oPos = event.index
              fix = function (cursor) { // eslint-disable-line
                if (cursor < oPos) {
                  return cursor
                } else {
                  cursor -= 1
                  return cursor
                }
              }
              r = createRange(fix)
              writeRange(r)
            }
          })
        }
        this.observe(yCallback)

        var textfieldObserver = function textfieldObserver () {
          mutualExcluse(function () {
            var r = createRange(function (x) { return x })
            var oldContent = self.toString()
            var content = getContent()
            var diffs = diff(oldContent, content, r.left)
            var pos = 0
            for (var i = 0; i < diffs.length; i++) {
              var d = diffs[i]
              if (d[0] === 0) { // EQUAL
                pos += d[1].length
              } else if (d[0] === -1) { // DELETE
                self.delete(pos, d[1].length)
              } else { // INSERT
                self.insert(pos, d[1])
                pos += d[1].length
              }
            }
          })
        }
        textfield.oninput = textfieldObserver
        this.textfields.push({
          editor: textfield,
          yCallback: yCallback
        })
      }
      _destroy () {
        this.unbindQuillAll()
        super._destroy()
      }
    }
    Y.extend('Text', new Y.utils.CustomTypeDefinition({
      name: 'Text',
      class: YText,
      struct: 'List',
      initType: function * YTextInitializer (os, model) {
        var _content = []
        yield* Y.Struct.List.map.call(this, model, function (op) {
          if (op.hasOwnProperty('opContent')) {
            throw new Error('Text must not contain types!')
          } else {
            op.content.forEach(function (c, i) {
              _content.push({
                id: [op.id[0], op.id[1] + i],
                val: op.content[i]
              })
            })
          }
        })
        return new YText(os, model.id, _content)
      },
      createType: function YTextCreator (os, model) {
        return new YText(os, model.id, [])
      }
    }))
  })
}

module.exports = extend
if (typeof Y !== 'undefined') {
  extend(Y)
}
<commit_msg>use addEventListener instead of oninput property<commit_after>/* global Y, Element */
'use strict'

var diff = require('fast-diff')

function extend (Y) {
  Y.requestModules(['Array']).then(function () {
    class YText extends Y.Array.typeDefinition['class'] {
      constructor (os, _model, _content) {
        super(os, _model, _content)
        this.textfields = []
        this.aceInstances = []
      }
      toString () {
        return this._content.map(function (c) {
          return c.val
        }).join('')
      }
      insert (pos, content) {
        super.insert(pos, content.split(''))
      }
      unbindAll () {
        for (let i = this.textfields.length - 1; i >= 0; i--) {
          this.unbindTextarea(this.textfields[i].editor)
        }
        for (let i = this.aceInstances.length - 1; i >= 0; i--) {
          this.unbindAce(this.aceInstances[i].editor)
        }
      }
      unbindAce (ace) {
        var i = this.aceInstances.findIndex(function (binding) {
          return binding.editor === ace
        })
        if (i >= 0) {
          var binding = this.aceInstances[i]
          this.unobserve(binding.yCallback)
          binding.editor.off('change', binding.aceCallback)
          this.aceInstances.splice(i, 1)
        }
      }
      bindAce (ace, options) {
        var self = this

        // this function makes sure that either the
        // ace event is executed, or the yjs observer is executed
        var token = true
        function mutualExcluse (f) {
          if (token) {
            token = false
            try {
              f()
            } catch (e) {
              token = true
              throw new Error(e)
            }
            token = true
          }
        }
        ace.markers = []
        var disableMarkers = false

        if (typeof options === 'object') {
          if (typeof options.disableMarkers !== 'undefined') {
            disableMarkers = options.disableMarkers
          }
        }

        ace.setValue(this.toString())

        function aceCallback (delta) {
          mutualExcluse(function () {
            var start = 0
            var length = 0

            var aceDocument = ace.getSession().getDocument()
            if (delta.action === 'insert') {
              start = aceDocument.positionToIndex(delta.start, 0)
              self.insert(start, delta.lines.join('\n'))
            } else if (delta.action === 'remove') {
              start = aceDocument.positionToIndex(delta.start, 0)
              length = delta.lines.join('\n').length
              self.delete(start, length)
            }
          })
        }
        ace.on('change', aceCallback)

        if (!disableMarkers) {
          if (this.inteval) {
            clearInterval(this.inteval)
          }
          this.inteval = setInterval(function () {
            var i = 0
            var now = Date.now()
            var timeVisible = 800

            while (i < ace.markers.length) {
              var marker = ace.markers[i]

              if (marker.timestamp + timeVisible < now) {
                ace.getSession().removeMarker(marker.id)
                ace.markers.splice(i, 1)
                i--
              }
              i++
            }
          }, 1000)
        }
        var Range = window.ace.require('ace/range').Range
        function setMarker (start, end, klazz) {
          if (disableMarkers) {
            return
          }
          var offset = 0
          if (start.row === end.row && start.column === end.column) {
            offset = 1
          }
          var range = new Range(start.row, start.column, end.row, end.column + offset)
          var marker = ace.session.addMarker(range, klazz, 'text')
          ace.markers.push({id: marker, timestamp: Date.now()})
        }

        function yCallback (event) {
          var aceDocument = ace.getSession().getDocument()
          mutualExcluse(function () {
            if (event.type === 'insert') {
              let start = aceDocument.indexToPosition(event.index, 0)
              let end = aceDocument.indexToPosition(event.index + event.length, 0)
              aceDocument.insert(start, event.values.join(''))

              setMarker(start, end, 'inserted')
            } else if (event.type === 'delete') {
              let start = aceDocument.indexToPosition(event.index, 0)
              let end = aceDocument.indexToPosition(event.index + event.length, 0)
              var range = new Range(start.row, start.column, end.row, end.column)
              aceDocument.remove(range)

              setMarker(start, end, 'deleted')
            }
          })
        }
        this.observe(yCallback)
        this.aceInstances.push({
          editor: ace,
          yCallback: yCallback,
          aceCallback: aceCallback
        })
      }
      bind () {
        var e = arguments[0]
        if (e instanceof Element) {
          this.bindTextarea.apply(this, arguments)
        } else if (e != null && e.session != null && e.getSession != null && e.setValue != null) {
          this.bindAce.apply(this, arguments)
        } else {
          console.error('Cannot bind, unsupported editor!')
        }
      }
      unbindTextarea (textarea) {
        var i = this.textfields.findIndex(function (binding) {
          return binding.editor === textarea
        })
        if (i >= 0) {
          var binding = this.textfields[i]
          this.unobserve(binding.yCallback)
          var e = binding.editor
          e.removeEventListener('input', binding.eventListener)
          this.textfields.splice(i, 1)
        }
      }
      bindTextarea (textfield, domRoot) {
        domRoot = domRoot || window; // eslint-disable-line
        if (domRoot.getSelection == null) {
          domRoot = window; // eslint-disable-line
        }

        // don't duplicate!
        for (var t = 0; t < this.textfields.length; t++) {
          if (this.textfields[t].editor === textfield) {
            return
          }
        }
        // this function makes sure that either the
        // textfieldt event is executed, or the yjs observer is executed
        var token = true
        function mutualExcluse (f) {
          if (token) {
            token = false
            try {
              f()
            } catch (e) {
              token = true
              throw new Error(e)
            }
            token = true
          }
        }

        var self = this
        textfield.value = this.toString()

        var createRange, writeRange, writeContent, getContent
        if (textfield.selectionStart != null && textfield.setSelectionRange != null) {
          createRange = function (fix) {
            var left = textfield.selectionStart
            var right = textfield.selectionEnd
            if (fix != null) {
              left = fix(left)
              right = fix(right)
            }
            return {
              left: left,
              right: right
            }
          }
          writeRange = function (range) {
            writeContent(self.toString())
            textfield.setSelectionRange(range.left, range.right)
          }
          writeContent = function (content) {
            textfield.value = content
          }
          getContent = function () {
            return textfield.value
          }
        } else {
          createRange = function (fix) {
            var range = {}
            var s = domRoot.getSelection()
            var clength = textfield.textContent.length
            range.left = Math.min(s.anchorOffset, clength)
            range.right = Math.min(s.focusOffset, clength)
            if (fix != null) {
              range.left = fix(range.left)
              range.right = fix(range.right)
            }
            var editedElement = s.focusNode
            if (editedElement === textfield || editedElement === textfield.childNodes[0]) {
              range.isReal = true
            } else {
              range.isReal = false
            }
            return range
          }

          writeRange = function (range) {
            writeContent(self.toString())
            var textnode = textfield.childNodes[0]
            if (range.isReal && textnode != null) {
              if (range.left < 0) {
                range.left = 0
              }
              range.right = Math.max(range.left, range.right)
              if (range.right > textnode.length) {
                range.right = textnode.length
              }
              range.left = Math.min(range.left, range.right)
              var r = document.createRange(); // eslint-disable-line
              r.setStart(textnode, range.left)
              r.setEnd(textnode, range.right)
              var s = domRoot.getSelection(); // eslint-disable-line
              s.removeAllRanges()
              s.addRange(r)
            }
          }
          writeContent = function (content) {
            textfield.innerText = content
            /*
            var contentArray = content.replace(new RegExp('\n', 'g'), ' ').split(' '); // eslint-disable-line
            textfield.innerText = ''
            for (var i = 0; i < contentArray.length; i++) {
              var c = contentArray[i]
              textfield.innerText += c
              if (i !== contentArray.length - 1) {
                textfield.innerHTML += ' '
              }
            }
            */
          }
          getContent = function () {
            return textfield.innerText
          }
        }
        writeContent(this.toString())

        function yCallback (event) {
          mutualExcluse(() => {
            var oPos, fix
            if (event.type === 'insert') {
              oPos = event.index
              fix = function (cursor) { // eslint-disable-line
                if (cursor <= oPos) {
                  return cursor
                } else {
                  cursor += 1
                  return cursor
                }
              }
              var r = createRange(fix)
              writeRange(r)
            } else if (event.type === 'delete') {
              oPos = event.index
              fix = function (cursor) { // eslint-disable-line
                if (cursor < oPos) {
                  return cursor
                } else {
                  cursor -= 1
                  return cursor
                }
              }
              r = createRange(fix)
              writeRange(r)
            }
          })
        }
        this.observe(yCallback)

        var textfieldObserver = function textfieldObserver () {
          mutualExcluse(function () {
            var r = createRange(function (x) { return x })
            var oldContent = self.toString()
            var content = getContent()
            var diffs = diff(oldContent, content, r.left)
            var pos = 0
            for (var i = 0; i < diffs.length; i++) {
              var d = diffs[i]
              if (d[0] === 0) { // EQUAL
                pos += d[1].length
              } else if (d[0] === -1) { // DELETE
                self.delete(pos, d[1].length)
              } else { // INSERT
                self.insert(pos, d[1])
                pos += d[1].length
              }
            }
          })
        }
        textfield.addEventListener('input', textfieldObserver)
        this.textfields.push({
          editor: textfield,
          yCallback: yCallback,
          eventListener: textfieldObserver
        })
      }
      _destroy () {
        this.unbindAll()
        this.textfields = null
        this.aceInstances = null
        super._destroy()
      }
    }
    Y.extend('Text', new Y.utils.CustomTypeDefinition({
      name: 'Text',
      class: YText,
      struct: 'List',
      initType: function * YTextInitializer (os, model) {
        var _content = []
        yield* Y.Struct.List.map.call(this, model, function (op) {
          if (op.hasOwnProperty('opContent')) {
            throw new Error('Text must not contain types!')
          } else {
            op.content.forEach(function (c, i) {
              _content.push({
                id: [op.id[0], op.id[1] + i],
                val: op.content[i]
              })
            })
          }
        })
        return new YText(os, model.id, _content)
      },
      createType: function YTextCreator (os, model) {
        return new YText(os, model.id, [])
      }
    }))
  })
}

module.exports = extend
if (typeof Y !== 'undefined') {
  extend(Y)
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/g<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commi<commit_msg>Reverting changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(<commit_msg>Grammar fix<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter + "/" + length + " bytes: " + message + "\r");
    fs.writeSync(o<|endoftext|>


<commit_before>'use strict';

// src/services/game/hooks/check-winner.js
//
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html

const defaults = {};

module.exports = function(options) {
  options = Object.assign({}, defaults, options);

  return function(hook) {
    const turn = hook.data.turn;
    const boxes = hook.data.boxes;
    const edges = hook.data.edges;
    const takenEdgesIds = hook.data.takenEdgesIds;
    const players = hook.data.players;
    const winner = hook.data.winner;

    // check winner part
    if(takenEdgesIds.length > 0){

      const takenEdgesIds = hook.data.takenEdgesIds;
      const clickedEdgeId = takenEdgesIds[(takenEdgesIds.length)-1];

      // filter out the boxes that have pickedEdge in them
      // this will give can array of one or two objects!
      const matchingBoxes = boxes.filter(box => box.boxEdges.indexOf(clickedEdgeId) !== -1);
      const BoxOneEdges = matchingBoxes[0].boxEdges;
      //
      //

      if (BoxOneEdges.filter(id => takenEdgesIds.indexOf(id) !== -1).length === 4){
        console.log("Hallelujah!! A box is won!!!");
        matchingBoxes[0].boxOwner = turn
        players[turn].boxes.push(matchingBoxes[0].boxId)

        if(matchingBoxes.length === 2){
          const BoxTwoEdges = matchingBoxes[1].boxEdges;
          if(BoxTwoEdges.filter(id => takenEdgesIds.indexOf(id) !== -1).length === 4){
            console.log("Way to go!! Another box is won!!!");
            matchingBoxes[1].boxOwner = turn
            players[turn].boxes.push(matchingBoxes[1].boxId)
          }
        }
      }
      else if(matchingBoxes.length === 2){
        const BoxTwoEdges = matchingBoxes[1].boxEdges;
        if(BoxTwoEdges.filter(id => takenEdgesIds.indexOf(id) !== -1).length === 4){
          console.log("Hallelujah!! A box is won!!!");
          matchingBoxes[1].boxOwner = turn
          players[turn].boxes.push(matchingBoxes[1].boxId)
        }

        else{
          console.log("No box is won...");
          let nextTurn = turn + 1
          if (nextTurn > 1){
            nextTurn = 0
          }
          hook.data.turn = nextTurn
        }
      }
      else{
        console.log("No box is won...");
        let nextTurn = turn + 1
        if (nextTurn > 1){
          nextTurn = 0
        }
        hook.data.turn = nextTurn

      }

      // Decide final winner:
      // if all edges are taken
      if (edges.filter(edge => edge.taken === true).length === 24){
        console.log("Decide final winner function is triggered...");
        // determin the hightest score.
        const highestScore = players.reduce((prevBoxes, nextPlayer) => {
        const nextBoxes = nextPlayer.boxes.length
        return prevPairs > nextBoxes ? prevBoxes : nextBoxes
        }, 0)
        console.log(highestScore);
        // push player with highest score into winner
        const gameWinner = players.filter((player) => {player.boxes === hightsthighestScore})

        hook.data.winner = gameWinner.name
      }

    } // end check winner part
  } // end function(hook)
} // end module.exports
<commit_msg>switch branch<commit_after>'use strict';

// src/services/game/hooks/check-winner.js
//
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html

const defaults = {};

module.exports = function(options) {
  options = Object.assign({}, defaults, options);

  return function(hook) {
    const turn = hook.data.turn;
    const boxes = hook.data.boxes;
    const edges = hook.data.edges;
    const takenEdgesIds = hook.data.takenEdgesIds;
    const players = hook.data.players;
    const winner = hook.data.winner;

    // check winner part
    if(takenEdgesIds.length > 0){

      const takenEdgesIds = hook.data.takenEdgesIds;
      const clickedEdgeId = takenEdgesIds[(takenEdgesIds.length)-1];

      // filter out the boxes that have pickedEdge in them
      // this will give can array of one or two objects!
      const matchingBoxes = boxes.filter(box => box.boxEdges.indexOf(clickedEdgeId) !== -1);
      const BoxOneEdges = matchingBoxes[0].boxEdges;

      if (BoxOneEdges.filter(id => takenEdgesIds.indexOf(id) !== -1).length === 4){
        console.log("Hallelujah!! A box is won!!!");
        matchingBoxes[0].boxOwner = turn
        players[turn].boxes.push(matchingBoxes[0].boxId)

        if(matchingBoxes.length === 2){
          const BoxTwoEdges = matchingBoxes[1].boxEdges;
          if(BoxTwoEdges.filter(id => takenEdgesIds.indexOf(id) !== -1).length === 4){
            console.log("Way to go!! Another box is won!!!");
            matchingBoxes[1].boxOwner = turn
            players[turn].boxes.push(matchingBoxes[1].boxId)
          }
        }
      }
      else if(matchingBoxes.length === 2){
        const BoxTwoEdges = matchingBoxes[1].boxEdges;
        if(BoxTwoEdges.filter(id => takenEdgesIds.indexOf(id) !== -1).length === 4){
          console.log("Hallelujah!! A box is won!!!");
          matchingBoxes[1].boxOwner = turn
          players[turn].boxes.push(matchingBoxes[1].boxId)
        }

        else{
          console.log("No box is won...");
          let nextTurn = turn + 1
          if (nextTurn > 1){
            nextTurn = 0
          }
          hook.data.turn = nextTurn
        }
      }
      else{
        console.log("No box is won...");
        let nextTurn = turn + 1
        if (nextTurn > 1){
          nextTurn = 0
        }
        hook.data.turn = nextTurn
      }

    } // end check winner part

    // Decide final winner:
    if (edges.filter(edge => edge.taken === true).length === 24){
      console.log("Decide final winner function is triggered...");
      // determin the hightest score.
      debugger
      const highestScore = players.reduce((prevBoxes, nextPlayer) => {
      const nextBoxes = nextPlayer.boxes.length
      return prevPairs > nextBoxes ? prevBoxes : nextBoxes
      }, 0)
      console.log(highestScore);
      // push player with highest score into winner
      const gameWinner = players.filter((player) => {player.boxes === hightsthighestScore})

      hook.data.winner = gameWinner.name
    } // end final winner

  } // end function(hook)
} // end module.exports
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console<commit_msg>GET A HAIRCUT!<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var count<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counte<|endoftext|>


<commit_before>import L from 'leaflet';
import 'mapbox-gl';
import 'mapbox-gl-leaflet';
import { request } from 'esri-leaflet';

export function fetchMetadata (url, context) {
  request(url, {}, function (error, style) {
    if (!error) {
      request(style.sources.esri.url, {}, function (error, tileMetadata) {
        if (!error) {
          formatStyle(style, tileMetadata, url);

          context._mapboxGL = L.mapboxGL({
            accessToken: 'ezree',
            style: style
          });

          context._ready = true;
          context.fire('ready', {}, true);
        }
      }, context);
    } else {
      throw new Error('Unable to fetch vector tile style metadata');
    }
  }, context);
}

export function formatStyle (style, metadata, styleUrl) {

  // if a relative path is referenced, the default style can be found in a standard location
  if (style.sources.esri.url && style.sources.esri.url.indexOf('http') === -1) {
    style.sources.esri.url = styleUrl.replace('/resources/styles/root.json', '');
  }

  // right now ArcGIS Pro published vector services have a slightly different signature
  if (metadata.tiles && metadata.tiles[0].charAt(0) != '/') {
    metadata.tiles[0] = '/' + metadata.tiles[0];
  }

  style.sources.esri = {
    type: 'vector',
    scheme: 'xyz',
    tilejson: metadata.tilejson || '2.0.0',
    format: (metadata.tileInfo && metadata.tileInfo.format) || 'pbf',
    index: metadata.tileMap ? style.sources.esri.url + metadata.tileMap : null,
    tiles: [
      style.sources.esri.url + metadata.tiles[0]
    ],
    description: metadata.description,
    name: metadata.name
  };

  if (style.glyphs.indexOf('http') === -1) {
    // set paths to sprite and glyphs
    style.glyphs = styleUrl.replace('styles/root.json', style.glyphs.replace('../', ''));
    style.sprite = styleUrl.replace('styles/root.json', style.sprite.replace('../', ''));
  }
}

export var Util = {
  fetchMetadata: fetchMetadata
};

export default Util;
<commit_msg>missed the export<commit_after>import L from 'leaflet';
import 'mapbox-gl';
import 'mapbox-gl-leaflet';
import { request } from 'esri-leaflet';

export function fetchMetadata (url, context) {
  request(url, {}, function (error, style) {
    if (!error) {
      request(style.sources.esri.url, {}, function (error, tileMetadata) {
        if (!error) {
          formatStyle(style, tileMetadata, url);

          context._mapboxGL = L.mapboxGL({
            accessToken: 'ezree',
            style: style
          });

          context._ready = true;
          context.fire('ready', {}, true);
        }
      }, context);
    } else {
      throw new Error('Unable to fetch vector tile style metadata');
    }
  }, context);
}

export function formatStyle (style, metadata, styleUrl) {

  // if a relative path is referenced, the default style can be found in a standard location
  if (style.sources.esri.url && style.sources.esri.url.indexOf('http') === -1) {
    style.sources.esri.url = styleUrl.replace('/resources/styles/root.json', '');
  }

  // right now ArcGIS Pro published vector services have a slightly different signature
  if (metadata.tiles && metadata.tiles[0].charAt(0) != '/') {
    metadata.tiles[0] = '/' + metadata.tiles[0];
  }

  style.sources.esri = {
    type: 'vector',
    scheme: 'xyz',
    tilejson: metadata.tilejson || '2.0.0',
    format: (metadata.tileInfo && metadata.tileInfo.format) || 'pbf',
    index: metadata.tileMap ? style.sources.esri.url + metadata.tileMap : null,
    tiles: [
      style.sources.esri.url + metadata.tiles[0]
    ],
    description: metadata.description,
    name: metadata.name
  };

  if (style.glyphs.indexOf('http') === -1) {
    // set paths to sprite and glyphs
    style.glyphs = styleUrl.replace('styles/root.json', style.glyphs.replace('../', ''));
    style.sprite = styleUrl.replace('styles/root.json', style.sprite.replace('../', ''));
  }
}

export var Util = {
  fetchMetadata: fetchMetadata,
  formatStyle: formatStyle
};

export default Util;
<|endoftext|>