<commit_before>"use strict";

import path from 'path';
import fs from 'fs';
import cjson from 'cjson';

export const buildXML = function({ compress }) {
    let compression = '';

    if (compress) {
        compression = `
            then
            fs
            minify
                -yui
                -from=ext.js
                -to=ext.js
        `;
    }

    return `
        <project name="simple-build" basedir=".">
            <!--  internally, watch calls the init target, so need to have one here -->
            <target name="init"/>
            <target name="init-cmd">
                <taskdef resource="com/sencha/ant/antlib.xml"
                                classpath="\${cmd.dir}/sencha.jar"
                                loaderref="senchaloader"/>
                <x-extend-classpath>
                    <jar path="\${cmd.dir}/sencha.jar"/>
                </x-extend-classpath>
                <x-sencha-init prefix=""/>
                <x-compile refid="theCompiler"
                                 dir="\${basedir}"
                                 initOnly="true"
                                 inheritAll="true">
                          <![CDATA[
                          -classpath=\${basedir}/manifest.js
                          load-app
                              -temp=\${basedir}/temp
                              -tag=App
                    ]]>
                  </x-compile>
            </target>
            <target name="rebuild">
               <x-compile refid="theCompiler"
                          dir="\${basedir}"
                          inheritAll="true">
                  <![CDATA[
                  --debug
                  exclude
                  -all
                  and
                  include
                  -f=Boot.js
                  and
                  concatenate
                      ext.js
                  and
                  exclude
                  -all
                  and
                  # include theme overrides
                  include
                    -r
                    -tag=overrides
                  and
                  # include all js files needed for manifest.js
                  include
                      -r
                      -f=manifest.js
                  and
                  # exclude the generated manifest file itself,
                  # since we don't want the generated bundle file to create any components
                  exclude
                  -f=manifest.js
                  and
                  concatenate
                  +append
                      ext.js
                  and
                  scss
                      -appName=App
                      -imageSearchPath=resources
                      -themeName=triton
                      -resourceMapBase=.
                      -output=ext.scss
                  and
                  resources
                      -excludes=-all*.css
                      -out=resources
                  and
                  resources
                      -model=true
                      -out=resources
                  ]]>
               </x-compile>
            </target>
            <target name="build" depends="init-cmd,rebuild">
               <x-sencha-command dir="\${basedir}">
                   <![CDATA[
                   fashion
                       -pwd=.
                       -split=4095
                       ${compress ? '-compress' : ''}
                           ext.scss
                       ext.css
                   ${compression}
                   ]]>
               </x-sencha-command>
            </target>
            <target name="watch" depends="init-cmd,build">
                <x-fashion-watch
                        refName="fashion-watch"
                        inputFile="ext.scss"
                        outputFile="ext.css"
                        split="4095"
                        compress="${compress ? 'true' : 'false'}"
                        configFile="app.json"
                        fork="true"/>
                <x-watch compilerRef="theCompiler"
                         targets="rebuild"/>
            </target>
        </project>
    `.trim();
};

/**
 * Creates the app.json file
 * @param {String} theme The name of the theme to use.
 * @param {String[]} packages The names of packages to include in the build
 */
export function createAppJson({ theme, packages, toolkit, overrides=[], packageDirs=[] }) {
    const config = {
        framework: "ext",
        toolkit,
        requires: packages,
        overrides: overrides.map(dir => path.resolve(dir)),
        packages: {
            dir: packageDirs.map(dir => path.resolve(dir))
        },
        output: {
            base: '.',
            resources: {
                path: './resources',
                shared: "./resources"
            }
        }
    };

    // if .ext-reactrc file exists, consume it and apply to app.json
    if(fs.existsSync('./.ext-reactrc')) {
        const senchaRc = JSON.parse(fs.readFileSync('./.ext-reactrc', 'utf-8'));
        Object.assign(config, senchaRc);
        theme = senchaRc.theme || theme;
    }

    // if theme is local add it as an additional package dir
    if (fs.existsSync(theme)) {
        const packageInfo = cjson.load(path.join(theme, 'package.json'));
        config.theme = packageInfo.name;
        config.packages.dir.push(path.resolve(theme));
    } else {
        config.theme = theme;
    }

    return JSON.stringify(config, null, 4);
}

/**
 * Creates the workspace.json file
 * @param {String} sdk The path to the sdk
 */
export function createWorkspaceJson(sdk, packages, output) {
    return JSON.stringify({
        "frameworks": {
            "ext": path.resolve(sdk)
        },
        "packages": {
            "dir": ['${workspace.dir}/packages/local', '${workspace.dir}/packages'].concat(packages).join(','),
            "extract": "${workspace.dir}/packages/remote"
        }
    }, null, 4);
}
<commit_msg>REAC-137<commit_after>"use strict";

import path from 'path';
import fs from 'fs';
import cjson from 'cjson';

export const buildXML = function({ compress }) {
    let compression = '';

    if (compress) {
        compression = `
            then
            fs
            minify
                -yui
                -from=ext.js
                -to=ext.js
        `;
    }

    return `
        <project name="simple-build" basedir=".">
            <!--  internally, watch calls the init target, so need to have one here -->
            <target name="init"/>
            <target name="init-cmd">
                <taskdef resource="com/sencha/ant/antlib.xml"
                                classpath="\${cmd.dir}/sencha.jar"
                                loaderref="senchaloader"/>
                <x-extend-classpath>
                    <jar path="\${cmd.dir}/sencha.jar"/>
                </x-extend-classpath>
                <x-sencha-init prefix=""/>
                <x-compile refid="theCompiler"
                                 dir="\${basedir}"
                                 initOnly="true"
                                 inheritAll="true">
                          <![CDATA[
                          -classpath=\${basedir}/manifest.js
                          load-app
                              -temp=\${basedir}/temp
                              -tag=App
                    ]]>
                  </x-compile>
            </target>
            <target name="rebuild">
               <x-compile refid="theCompiler"
                          dir="\${basedir}"
                          inheritAll="true">
                  <![CDATA[
                  --debug
                  exclude
                  -all
                  and
                  include
                  -f=Boot.js
                  and
                  concatenate
                      ext.js
                  and
                  exclude
                  -all
                  and
                  # include theme overrides
                  include
                    -r
                    -tag=overrides
                  and
                  # include all js files needed for manifest.js
                  include
                      -r
                      -f=manifest.js
                  and
                  # exclude the generated manifest file itself,
                  # since we don't want the generated bundle file to create any components
                  exclude
                  -f=manifest.js
                  and
                  concatenate
                  +append
                      ext.js
                  and
                  scss
                      -appName=App
                      -imageSearchPath=resources
                      -themeName=triton
                      -resourceMapBase=.
                      -output=ext.scss
                  and
                  resources
                      -excludes=-all*.css
                      -out=resources
                  and
                  resources
                      -model=true
                      -out=resources
                  ]]>
               </x-compile>
            </target>
            <target name="build" depends="init-cmd,rebuild">
               <x-sencha-command dir="\${basedir}">
                   <![CDATA[
                   fashion
                       -pwd=.
                       -split=4095
                       ${compress ? '-compress' : ''}
                           ext.scss
                       ext.css
                   ${compression}
                   ]]>
               </x-sencha-command>
            </target>
            <target name="watch" depends="init-cmd,build">
                <x-fashion-watch
                        refName="fashion-watch"
                        inputFile="ext.scss"
                        outputFile="ext.css"
                        split="4095"
                        compress="${compress ? 'true' : 'false'}"
                        configFile="app.json"
                        fork="true"/>
                <x-watch compilerRef="theCompiler"
                         targets="rebuild"/>
            </target>
        </project>
    `.trim();
};

/**
 * Creates the app.json file
 * @param {String} theme The name of the theme to use.
 * @param {String[]} packages The names of packages to include in the build
 */
export function createAppJson({ theme, packages, toolkit, overrides=[], packageDirs=[] }) {
    const config = {
        framework: "ext",
        toolkit,
        requires: packages,
        overrides: overrides.map(dir => path.resolve(dir)),
        packages: {
            dir: packageDirs.map(dir => path.resolve(dir))
        },
        output: {
            base: '.',
            resources: {
                path: './resources',
                shared: "./resources"
            }
        }
    };

    // if .ext-reactrc file exists, consume it and apply to app.json
    if(fs.existsSync('./.ext-reactrc')) {
        const senchaRc = JSON.parse(fs.readFileSync('./.ext-reactrc', 'utf-8'));
        Object.assign(config, senchaRc);
        theme = senchaRc.theme || theme;
    }

    // if theme is local add it as an additional package dir
    if (fs.existsSync(theme)) {
        const packageInfo = cjson.load(path.join(theme, 'package.json'));
        config.theme = packageInfo.name;
        config.packages.dir.push(path.resolve(theme));
    } else {
        config.theme = theme;
    }

    return JSON.stringify(config, null, 4);
}

/**
 * Creates the workspace.json file
 * @param {String} sdk The path to the sdk
 */
export function createWorkspaceJson(sdk, packages, output) {
    return JSON.stringify({
        "frameworks": {
            "ext": path.relative(output, sdk)
        },
        "packages": {
            "dir": ['${workspace.dir}/packages/local', '${workspace.dir}/packages'].concat(packages).join(','),
            "extract": "${workspace.dir}/packages/remote"
        }
    }, null, 4);
}
<|endoftext|>


<commit_before>/**
 * @module ember-flexberry
 */

import FlexberryBaseComponent from './flexberry-base-component';

/**
 * Component for create, edit and delete detail objects.
 *
 * @class FlexberryGroupedit
 * @extends FlexberryBaseComponent
 */
export default FlexberryBaseComponent.extend({
  /**
   * Projection for detail object's model.
   *
   * @property modelProjection
   * @type Object
   * @default null
   */
  modelProjection: null,

  /**
   * Array of models for detail objects.
   *
   * @property content
   * @type ManyArray
   * @default null
   */
  content: null,

  /**
   * Function to get names of components to use for display
   * attributes of detail object's model.
   *
   * @property cellComponent
   * @type Function
   * @default null
   */
  cellComponent: null,

  /**
   * Setting to true enables row ordering by clicking on column headers.
   *
   * @property orderable
   * @type Boolean
   * @default false
   */
  orderable: false,
  _showCheckBoxInRow: true,
  _showDeleteButtonInRow: true,
  _rowClickable: false,

  actions: {
    /**
     * Handles action from object-list-view when no handler for this component is defined.
     *
     * @method sortByColumn
     * @param {Object} column Column to sort by.
     */
    sortByColumn: function(column) {
      throw new Error('No handler for sortByColumn action set for flexberry-groupedit. Set handler like {{flexberry-groupedit ... sortByColumn=(action "sortByColumn")}}.');
    },

	/**
     * Handles action from object-list-view when no handler for this component is defined.
     *
     * @method addColumnToSorting
     * @param {Object} column Column to add sorting by.
     */
    addColumnToSorting: function(column) {
      throw new Error('No handler for addColumnToSorting action set for flexberry-groupedit. Set handler like {{flexberry-groupedit ... addColumnToSorting=(action "addColumnToSorting")}}.');
    }
  }
});
<commit_msg>Fix indentation<commit_after>/**
 * @module ember-flexberry
 */

import FlexberryBaseComponent from './flexberry-base-component';

/**
 * Component for create, edit and delete detail objects.
 *
 * @class FlexberryGroupedit
 * @extends FlexberryBaseComponent
 */
export default FlexberryBaseComponent.extend({
  /**
   * Projection for detail object's model.
   *
   * @property modelProjection
   * @type Object
   * @default null
   */
  modelProjection: null,

  /**
   * Array of models for detail objects.
   *
   * @property content
   * @type ManyArray
   * @default null
   */
  content: null,

  /**
   * Function to get names of components to use for display
   * attributes of detail object's model.
   *
   * @property cellComponent
   * @type Function
   * @default null
   */
  cellComponent: null,

  /**
   * Setting to true enables row ordering by clicking on column headers.
   *
   * @property orderable
   * @type Boolean
   * @default false
   */
  orderable: false,
  _showCheckBoxInRow: true,
  _showDeleteButtonInRow: true,
  _rowClickable: false,

  actions: {
    /**
     * Handles action from object-list-view when no handler for this component is defined.
     *
     * @method sortByColumn
     * @param {Object} column Column to sort by.
     */
    sortByColumn: function(column) {
      throw new Error('No handler for sortByColumn action set for flexberry-groupedit. Set handler like {{flexberry-groupedit ... sortByColumn=(action "sortByColumn")}}.');
    },

    /**
     * Handles action from object-list-view when no handler for this component is defined.
     *
     * @method addColumnToSorting
     * @param {Object} column Column to add sorting by.
     */
    addColumnToSorting: function(column) {
      throw new Error('No handler for addColumnToSorting action set for flexberry-groupedit. Set handler like {{flexberry-groupedit ... addColumnToSorting=(action "addColumnToSorting")}}.');
    }
  }
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path'),
  fs = require('fs'),
  mixIn = require('mout/object/mixIn'),
  stampit = require('stampit'),

  filterPath = function filterPath(p) {
    return p.replace(/^\./, '');
  },

  getBuild = function getBuild(options) {
    var buildPath, data;

    if (options.build) {
      return options.build;
    }

    buildPath = path.resolve( process.cwd() +
    filterPath(options.buildPath) );

    try {
      data = fs.readFileSync(buildPath, 'utf8');
      options.data = data.trim();
      return options.data;
    } catch(err) {
      return undefined;
    }
  },

  readPkg = function readPkg() {
    return require(process.cwd() + '/package.json');
  },

  version,

  configure = function configure(options) {
    var instance = version();
    instance.options = mixIn({}, options);
    return instance;
  };

version = stampit().enclose(function () {
  var handler = function (req, res) {
    var options = handler.options,
      pkg = options.pkg || readPkg(),
      build = getBuild(options),

      responseObj = {
        name: pkg.name,
        version: pkg.version,
        build: build
      },

      body;

    if (options.callback) {
      options.callback.call(this, req, res);
    }

    body = JSON.stringify(responseObj);

    res.end(body);
  };

  return mixIn(handler, {
    getBuild: getBuild,
    configure: configure,
    options: {
      buildPath: '/config/BUILD'
    }
  });
});

module.exports = version();
<commit_msg>Set Content-Type header.<commit_after>'use strict';
var path = require('path'),
  fs = require('fs'),
  mixIn = require('mout/object/mixIn'),
  stampit = require('stampit'),

  filterPath = function filterPath(p) {
    return p.replace(/^\./, '');
  },

  getBuild = function getBuild(options) {
    var buildPath, data;

    if (options.build) {
      return options.build;
    }

    buildPath = path.resolve( process.cwd() +
    filterPath(options.buildPath) );

    try {
      data = fs.readFileSync(buildPath, 'utf8');
      options.data = data.trim();
      return options.data;
    } catch(err) {
      return undefined;
    }
  },

  readPkg = function readPkg() {
    return require(process.cwd() + '/package.json');
  },

  version,

  configure = function configure(options) {
    var instance = version();
    instance.options = mixIn({}, options);
    return instance;
  };

version = stampit().enclose(function () {
  var handler = function (req, res) {
    var options = handler.options,
      pkg = options.pkg || readPkg(),
      build = getBuild(options),

      responseObj = {
        name: pkg.name,
        version: pkg.version,
        build: build
      },

      body;

    if (options.callback) {
      options.callback.call(this, req, res);
    }

    body = JSON.stringify(responseObj);
    res.setHeader('Content-Type', 'application/json');
    res.end(body);
  };

  return mixIn(handler, {
    getBuild: getBuild,
    configure: configure,
    options: {
      buildPath: '/config/BUILD'
    }
  });
});

module.exports = version();
<|endoftext|>


<commit_before><commit_msg>remove new section command (#7)<commit_after><|endoftext|>


<commit_before>var
    clientID, clientData = {}, clientArray, chatInitialized = false,
    messageArray = [],
    iosocket = io.connect('http://localhost:9999'),
    mainSection = document.querySelector("#mainSection"),
    startScreen = document.querySelector("#startScreen"),
    chatNameField = document.querySelector("#chatNameField"),
    chatNameInput = document.querySelector("#chatNameInput"),
    joinButton = document.querySelector("#joinButton"),
    loadingScreen = document.querySelector("#loadingScreen"),
    loadingMessage = document.querySelector("#loadingMessage"),
    chatSection, chatList, alertSection;

//////////////////////////
////INIT
//////////////////////////
function initSocketChat() {

    attachEventListener(joinButton, 'click', onJoinClick);
    attachEventListener(chatNameInput, 'focus', onInputFocus);
    log("initSocketChat");
}

//////////////////////////
////START SCREEN
//////////////////////////
function onJoinClick (evt) {
    var chatName = chatNameInput.value;
    if (chatName === '') {
        //Must enter a name
        chatNameField.setAttribute('class', 'field nine columns danger');
        chatNameInput.setAttribute('class', 'input inputError');
    } else {
        //Submit name
        chatNameField.setAttribute('class', 'field nine columns');
        chatNameInput.setAttribute('class', 'input');
        submitUserName(chatName);
    }
   log("chatName: " + chatName);
}

function onInputFocus(evt) {
    chatNameField.setAttribute('class', 'field nine columns');
    chatNameInput.setAttribute('class', 'input');
}

function submitUserName(name) {
    removeElement(startScreen);
    showLoadingScreen('Joining room, one moment...');
    clientData['name'] = name;
    iosocket.emit('join', { data: clientData } );
}

//////////////////////////
////LOADING SCREEN
//////////////////////////
function showLoadingScreen(msg) {
    msg = msg || 'Loading, please wait...';
    loadingScreen.setAttribute('class', 'centered four columns');
    loadingMessage.innerHTML = msg;
    log('showLoadingScreen');
}

function hideLoadingScreen() {
    loadingScreen.setAttribute('class', 'centered four columns hide');
    log('hideLoadingScreen');
}

//////////////////////////
////INIT CHAT
//////////////////////////
function initChat() {
    log('initChatScreen');
    initUserSection();
    initChatSection();
    initMessageSection();
}

//////////////////////////
////USER SECTION
//////////////////////////
function initUserSection() {
    var
        userSection = addElement(mainSection, 'section', { id: 'userSection', className: 'three columns'}),
        userList = addElement(userSection, 'ul', { id: 'userList'});

    refreshUserList();
}

function refreshUserList() {
    var i, userItem, icon, uList = document.querySelector('#userList');

    //clear user list
    uList.innerHTML = '';

    console.log('clientArray: ' + clientArray);

    for (i = 0; i < clientArray.length; i += 1) {
        userItem = addElement(uList, 'li');
        icon = addElement(userItem, 'i', { className: 'icon-user' });
        userItem.innerHTML += clientArray[i].name;
    }
}

//////////////////////////
////INIT CHAT SECTION
//////////////////////////
function initChatSection() {
    var i;
    chatSection = addElement(mainSection, 'section', { id: 'chatSection'});
    chatList = addElement(chatSection, 'ul', { id: 'chatList'});

    if (messageArray.length > 0) {
        //There are already messages, add them to the board
        for (i = 0; i < messageArray.length; i += 1) {
            addToChatList(messageArray[i].client, messageArray[i].message);
        }
    }
}

function addToChatList(client, msg) {
    var item = addElement(chatList, 'li', { className: 'chatItem' });

    addElement(item, 'div', { className: 'chatName', innerHTML: client });
    addElement(item, 'div', { className: 'chatMessage', innerHTML: msg });
    addElement(item, 'div', { className: 'chatTime', innerHTML: '8:00pm' });

    chatSection.scrollTop = chatSection.scrollHeight;
}

//////////////////////////
////INIT MESSAGE SECTION
//////////////////////////
function initMessageSection() {
    var
        messageSection = addElement(mainSection, 'section', { id: 'messageSection', className: 'twelve columns'}),
        messageContainer = addElement(messageSection, 'div', { className: 'field' }),
        messageField =  addElement(messageContainer, 'textarea', { id: 'messageField', className: 'input textarea', placeholder: 'Say something'}),
        sendButton = addElement(messageSection, 'button', { id: 'sendButton', type: 'button', className: 'pretty medium primary btn send', innerHTML: 'Send'});

    attachEventListener(sendButton, 'click', function(){
        addToChatList(clientData.name, messageField.value);
        iosocket.emit('message', { client: clientData.name, message: messageField.value });
    });
}

//////////////////////////
////INIT ALERT SECTION
//////////////////////////
function initAlertSection() {
    alertSection = addElement(mainSection, 'section', { id: 'alertSection', className: 'row' });
}

function addAlert(msg) {
    addElement(alertSection, 'p', { id: 'alertField', className: 'primary alert', innerHTML: msg });
}

//////////////////////////
////IOSOCKET
//////////////////////////
iosocket.on('connected', function (data) {
    clientID = data.clientID;
    clientData['id'] = data.clientID;

    socketLog('your ID is: ' + clientID);
    socketLog('connected');
});

iosocket.on('onmessage', function (data) {
    socketLog("Message received: " + data.message);
    addToChatList(data.client, data.message);
});

iosocket.on('joined', function (data) {
    socketLog('New client has joined: ' + data.newClient);

    hideLoadingScreen();
    clientArray = data.clientList;
    messageArray = data.messages;

    if (chatInitialized === false) {
        socketLog('initChat');
        initChat();
        chatInitialized = true;
    } else {
        socketLog('refreshUserList');
        refreshUserList();
    }
    socketLog("users joined: " + clientArray.length);
});

iosocket.on('userleft', function (data) {
    clientArray = data.clientList;
    refreshUserList();
    socketLog('User left the room: ' + clientArray);
});

//Constructor
initSocketChat();<commit_msg>Working on adding pencil icon next to users name when user is typing.<commit_after>var
    clientID, clientData = {}, clientArray, chatInitialized = false,
    messageArray = [],
    iosocket = io.connect('http://localhost:9999'),
    mainSection = document.querySelector("#mainSection"),
    startScreen = document.querySelector("#startScreen"),
    chatNameField = document.querySelector("#chatNameField"),
    chatNameInput = document.querySelector("#chatNameInput"),
    joinButton = document.querySelector("#joinButton"),
    loadingScreen = document.querySelector("#loadingScreen"),
    loadingMessage = document.querySelector("#loadingMessage"),
    chatSection, chatList, alertSection;

//////////////////////////
////INIT
//////////////////////////
function initSocketChat() {

    attachEventListener(joinButton, 'click', onJoinClick);
    attachEventListener(chatNameInput, 'focus', onInputFocus);
    log("initSocketChat");
}

//////////////////////////
////START SCREEN
//////////////////////////
function onJoinClick (evt) {
    var chatName = chatNameInput.value;
    if (chatName === '') {
        //Must enter a name
        chatNameField.setAttribute('class', 'field nine columns danger');
        chatNameInput.setAttribute('class', 'input inputError');
    } else {
        //Submit name
        chatNameField.setAttribute('class', 'field nine columns');
        chatNameInput.setAttribute('class', 'input');
        submitUserName(chatName);
    }
}

function onInputFocus(evt) {
    chatNameField.setAttribute('class', 'field nine columns');
    chatNameInput.setAttribute('class', 'input');
}

function submitUserName(name) {
    removeElement(startScreen);
    showLoadingScreen('Joining room, one moment...');
    clientData['name'] = name;
    iosocket.emit('join', { data: clientData } );
}

//////////////////////////
////LOADING SCREEN
//////////////////////////
function showLoadingScreen(msg) {
    msg = msg || 'Loading, please wait...';
    loadingScreen.setAttribute('class', 'centered four columns');
    loadingMessage.innerHTML = msg;
    log('showLoadingScreen');
}

function hideLoadingScreen() {
    loadingScreen.setAttribute('class', 'centered four columns hide');
    log('hideLoadingScreen');
}

//////////////////////////
////INIT CHAT
//////////////////////////
function initChat() {
    log('initChatScreen');
    initUserSection();
    initChatSection();
    initMessageSection();
}

//////////////////////////
////USER SECTION
//////////////////////////
function initUserSection() {
    var
        userSection = addElement(mainSection, 'section', { id: 'userSection', className: 'three columns'}),
        userList = addElement(userSection, 'ul', { id: 'userList'});

    refreshUserList();
}

function refreshUserList() {
    var i, userItem, icon, uList = document.querySelector('#userList');

    //clear user list
    uList.innerHTML = '';

    console.log('clientArray: ' + clientArray);

    for (i = 0; i < clientArray.length; i += 1) {
        userItem = addElement(uList, 'li', { id: "user-" + clientArray[i].id });
        userItem.setAttribute('data-username', clientArray[i].name );
        icon = addElement(userItem, 'i', { className: 'icon-user' });
        userItem.innerHTML += clientArray[i].name;
    }
}

//////////////////////////
////INIT CHAT SECTION
//////////////////////////
function initChatSection() {
    var i;
    chatSection = addElement(mainSection, 'section', { id: 'chatSection'});
    chatList = addElement(chatSection, 'ul', { id: 'chatList'});

    if (messageArray.length > 0) {
        //There are already messages, add them to the board
        for (i = 0; i < messageArray.length; i += 1) {
            addToChatList(messageArray[i].client, messageArray[i].message);
        }
    }
}

function addToChatList(client, msg) {
    var item = addElement(chatList, 'li', { className: 'chatItem' });

    addElement(item, 'div', { className: 'chatName', innerHTML: client });
    addElement(item, 'div', { className: 'chatMessage', innerHTML: msg });
    addElement(item, 'div', { className: 'chatTime', innerHTML: '8:00pm' });

    chatSection.scrollTop = chatSection.scrollHeight;
}

//////////////////////////
////INIT MESSAGE SECTION
//////////////////////////
function initMessageSection() {
    var
        messageSection = addElement(mainSection, 'section', { id: 'messageSection', className: 'twelve columns'}),
        messageContainer = addElement(messageSection, 'div', { className: 'field' }),
        messageField =  addElement(messageContainer, 'textarea', { id: 'messageField', className: 'input textarea', placeholder: 'Say something'}),
        sendButton = addElement(messageSection, 'button', { id: 'sendButton', type: 'button', className: 'pretty medium primary btn send', innerHTML: 'Send'}),
        userListItem = document.querySelector('#user-' + clientData.id), typingIcon = false, typingTimeout;

    attachEventListener(sendButton, 'click', function(evt) {
        addToChatList(clientData.name, messageField.value);
        iosocket.emit('message', { client: clientData.name, message: messageField.value });
    });

    attachEventListener(messageField, 'keydown', function(evt) {
        //If key down, clear typingTimeout
        if (typingIcon === false) {
            typingIcon = addElement(userListItem, 'i', { className: 'icon-pencil' });
        }
    });

    attachEventListener(messageField, 'keyup', function(evt) {
        typingTimeout = setTimeout(function () {
            //remove icon
        }, 2000);
    });
}

//////////////////////////
////INIT ALERT SECTION
//////////////////////////
function initAlertSection() {
    alertSection = addElement(mainSection, 'section', { id: 'alertSection', className: 'row' });
}

function addAlert(msg) {
    addElement(alertSection, 'p', { id: 'alertField', className: 'primary alert', innerHTML: msg });
}

//////////////////////////
////IOSOCKET
//////////////////////////
iosocket.on('connected', function (data) {
    clientID = data.clientID;
    clientData['id'] = data.clientID;

    socketLog('your ID is: ' + clientID);
    socketLog('connected');
});

iosocket.on('onmessage', function (data) {
    socketLog("Message received: " + data.message);
    addToChatList(data.client, data.message);
});

iosocket.on('joined', function (data) {
    socketLog('New client has joined: ' + data.newClient);

    hideLoadingScreen();
    clientArray = data.clientList;
    messageArray = data.messages;

    if (chatInitialized === false) {
        socketLog('initChat');
        initChat();
        chatInitialized = true;
    } else {
        socketLog('refreshUserList');
        refreshUserList();
    }
    socketLog("users joined: " + clientArray.length);
});

iosocket.on('userleft', function (data) {
    clientArray = data.clientList;
    refreshUserList();
    socketLog('User left the room: ' + clientArray);
});

//Constructor
initSocketChat();<|endoftext|>


<commit_before>"use strict";

exports.osmbc_version = "0.7.3b";
<commit_msg>Version to close #312<commit_after>"use strict";

exports.osmbc_version = "0.7.3c";
<|endoftext|>


<commit_before>
var semver = require('semver')
  , async = require('async')
  , fs = require('fs')
  , path = require('path')
  , exec = require("child_process").exec
  ;

exports._loadFiles = function (callback) {
  async.parallel({
    'pkg': function (done) {
      fs.readFile(path.join(process.cwd(), "package.json"), function (err, data) {
        done(null, data);
      });
    }

    , 'cpt': function (done) {
      fs.readFile(path.join(process.cwd(), "component.json"), function (err, data) {
        done(null, data);
      });
    }
  }, function (err, result) {
    var ret = {};

    if (!result.pkg && !result.cpt) {
      callback(new Error("Need one of package.json or component.json"));
      return void 0;
    }

    try {
      ret.pkg = JSON.parse(result.pkg)
    } catch (er) {
      ret.pkg = null;
    }

    try {
      ret.cpt = JSON.parse(result.cpt)
    } catch (er) {
      ret.cpt = null;
    }

    callback(null, ret);
  });
};

exports._saveFiles = function (pkg, cpt, callback) {
  // Save package/component file.
  async.parallel({
    'pkg': function (done) {
      if (!pkg) {
        return done(null, null);
      }

      fs.writeFile( path.join(process.cwd(), "package.json"),
          new Buffer(JSON.stringify(pkg, null, 2) + "\n"), function (err) {
            if (err) {
              return done(err);
            }
            done(null, "Updated package.json");
      });
    }

    , 'cpt': function (done) {
      if (!cpt) {
        return done(null, null);
      }
      fs.writeFile( path.join(process.cwd(), "component.json"),
          new Buffer(JSON.stringify(cpt, null, 2) + "\n"), function (err) {
            if (err) {
              return done(err);
            }
            done(null, "Updated component.json");
      });
    }
  }, callback);
};

var makeCommit = function (files, message, newVer, callback) {
    var git = 'git'
      , extra = {env: process.env}
      ;

    message = message.replace('%s', newVer);

    exec(git + " " + [ "status", "--porcelain" ].join(' '), extra, function (er, stdout, stderr) {

      var lines = stdout.trim().split("\n").filter(function (line) {
        return line.trim() && !line.match(/^\?\? /)
                  && line.indexOf('package.json') === -1
                  && line.indexOf('component.json') === -1
      }).map(function (line) {
        return line.trim()
      });

      if (lines.length) {
        return callback(new Error("Git working directory not clean.\n"+lines.join("\n")));
      }

      async.series(
        [
          function (done) {
            exec(git + " add " + files.join(' '), extra, done);
          }

          , function (done) {
            exec(git + " " + ["commit", "-m", message].join(' '), extra, done);
          }

          , function (done) {
            exec(git + " " + ["tag", "-", "v" + newVer, "-m", message].join(' '), extra, done);
          }
        ]
        , callback
      );
    });
  }
;

exports.get = function (callback) {
  exports._loadFiles(function(err, result) {
    var v1, v2, ret = {};

    if (err) {
      callback(err);
      return void 0;
    }

    v1 = result.pkg;
    v2 = result.cpt;

    if (v1 && v1.version) {
      ret['package.json'] = v1.version;
    }

    if (v2 && v2.version) {
      ret['component.json'] = v2.version;
    }

    callback(null, ret);
  });
};

exports.update = function (ver, commitMessage, callback) {
  var validVer = semver.valid(ver);
  ver = ver.toLowerCase();

  if (!callback && commitMessage && typeof commitMessage  === 'function') {
    callback = commitMessage;
    commitMessage = null;
  }
  if (!callback) {
    callback = function () { };
  }

  exports._loadFiles(function(err, result) {
    var pkg = result.pkg
      , cpt = result.cpt
      , currentVer = pkg ? pkg.version : cpt.version;

    if (err) {
      callback(err);
      return void 0;
    }

    if (validVer === null) {
      validVer = semver.inc(currentVer, ver);
    }

    if (validVer === null) {
      callback(new Error('No valid version given.'));
      return void 0;
    }

    if (pkg && pkg.version) {
      pkg.version = validVer;
    }
    if (cpt && cpt.version) {
      cpt.version = validVer;
    }

    exports._saveFiles(pkg, cpt, function (err, data) {
      var ret = {newVersion: validVer, versions: {}, message: []}
        , files = [];

      if (err) {
        callback(err);
        return void 0;
      }

      if (data.pkg) {
        ret.message.push(data.pkg);
      }
      if (data.cpt) {
        ret.message.push(data.cpt);
      }
      ret.message = ret.message.join("\n");

      if (pkg && pkg.version) {
        ret.versions['package.json'] = pkg.version;
        files.push('package.json');
      }

      if (cpt && cpt.version) {
        ret.versions['component.json'] = cpt.version;
        files.push('component.json');
      }

      if (!commitMessage) {
        callback(null, ret);
        return void 0;
      }

      makeCommit(files, commitMessage, validVer, function (err) {
        if (err) {
          callback(err);
          return void 0;
        }

        callback(null, ret);
      });
    });
  });
};<commit_msg>Fixed git tagging<commit_after>
var semver = require('semver')
  , async = require('async')
  , fs = require('fs')
  , path = require('path')
  , exec = require("child_process").exec
  ;

exports._loadFiles = function (callback) {
  async.parallel({
    'pkg': function (done) {
      fs.readFile(path.join(process.cwd(), "package.json"), function (err, data) {
        done(null, data);
      });
    }

    , 'cpt': function (done) {
      fs.readFile(path.join(process.cwd(), "component.json"), function (err, data) {
        done(null, data);
      });
    }
  }, function (err, result) {
    var ret = {};

    if (!result.pkg && !result.cpt) {
      callback(new Error("Need one of package.json or component.json"));
      return void 0;
    }

    try {
      ret.pkg = JSON.parse(result.pkg)
    } catch (er) {
      ret.pkg = null;
    }

    try {
      ret.cpt = JSON.parse(result.cpt)
    } catch (er) {
      ret.cpt = null;
    }

    callback(null, ret);
  });
};

exports._saveFiles = function (pkg, cpt, callback) {
  // Save package/component file.
  async.parallel({
    'pkg': function (done) {
      if (!pkg) {
        return done(null, null);
      }

      fs.writeFile( path.join(process.cwd(), "package.json"),
          new Buffer(JSON.stringify(pkg, null, 2) + "\n"), function (err) {
            if (err) {
              return done(err);
            }
            done(null, "Updated package.json");
      });
    }

    , 'cpt': function (done) {
      if (!cpt) {
        return done(null, null);
      }
      fs.writeFile( path.join(process.cwd(), "component.json"),
          new Buffer(JSON.stringify(cpt, null, 2) + "\n"), function (err) {
            if (err) {
              return done(err);
            }
            done(null, "Updated component.json");
      });
    }
  }, callback);
};

var makeCommit = function (files, message, newVer, callback) {
    var git = 'git'
      , extra = {env: process.env}
      ;

    message = message.replace('%s', newVer);

    exec(git + " " + [ "status", "--porcelain" ].join(' '), extra, function (er, stdout, stderr) {

      var lines = stdout.trim().split("\n").filter(function (line) {
        return line.trim() && !line.match(/^\?\? /)
                  && line.indexOf('package.json') === -1
                  && line.indexOf('component.json') === -1
      }).map(function (line) {
        return line.trim()
      });

      if (lines.length) {
        return callback(new Error("Git working directory not clean.\n"+lines.join("\n")));
      }

      async.series(
        [
          function (done) {
            exec(git + " add " + files.join(' '), extra, done);
          }

          , function (done) {
            exec(git + " " + ["commit", "-m", message].join(' '), extra, done);
          }

          , function (done) {
            exec(git + " " + ["tag", "-a", "v" + newVer, "-m", message].join(' '), extra, done);
          }
        ]
        , callback
      );
    });
  }
;

exports.get = function (callback) {
  exports._loadFiles(function(err, result) {
    var v1, v2, ret = {};

    if (err) {
      callback(err);
      return void 0;
    }

    v1 = result.pkg;
    v2 = result.cpt;

    if (v1 && v1.version) {
      ret['package.json'] = v1.version;
    }

    if (v2 && v2.version) {
      ret['component.json'] = v2.version;
    }

    callback(null, ret);
  });
};

exports.update = function (ver, commitMessage, callback) {
  var validVer = semver.valid(ver);
  ver = ver.toLowerCase();

  if (!callback && commitMessage && typeof commitMessage  === 'function') {
    callback = commitMessage;
    commitMessage = null;
  }
  if (!callback) {
    callback = function () { };
  }

  exports._loadFiles(function(err, result) {
    var pkg = result.pkg
      , cpt = result.cpt
      , currentVer = pkg ? pkg.version : cpt.version;

    if (err) {
      callback(err);
      return void 0;
    }

    if (validVer === null) {
      validVer = semver.inc(currentVer, ver);
    }

    if (validVer === null) {
      callback(new Error('No valid version given.'));
      return void 0;
    }

    if (pkg && pkg.version) {
      pkg.version = validVer;
    }
    if (cpt && cpt.version) {
      cpt.version = validVer;
    }

    exports._saveFiles(pkg, cpt, function (err, data) {
      var ret = {newVersion: validVer, versions: {}, message: []}
        , files = [];

      if (err) {
        callback(err);
        return void 0;
      }

      if (data.pkg) {
        ret.message.push(data.pkg);
      }
      if (data.cpt) {
        ret.message.push(data.cpt);
      }
      ret.message = ret.message.join("\n");

      if (pkg && pkg.version) {
        ret.versions['package.json'] = pkg.version;
        files.push('package.json');
      }

      if (cpt && cpt.version) {
        ret.versions['component.json'] = cpt.version;
        files.push('component.json');
      }

      if (!commitMessage) {
        callback(null, ret);
        return void 0;
      }

      makeCommit(files, commitMessage, validVer, function (err) {
        if (err) {
          callback(err);
          return void 0;
        }

        callback(null, ret);
      });
    });
  });
};<|endoftext|>


<commit_before>/* @jsx React.DOM */
var uuid = require('node-uuid'),
    React = require('react'),
    TodoApp = require('./js/models');

var TodoView = React.createClass({
  addTodo: function(event) {
    event.preventDefault();
    this.props.app.addTodo();
  },
  shouldComponentUpdate: function(newProps) {
    // val is an immutable representation of the app state:
    // if its the same object, nothing changed
    return newProps.appVal !== this.props.appVal;
  },
  render: function() {
    var edit = this.props.app.get('edit'),
        todos = this.props.app.get('todos'),
        history = this.props.app.get('history');
    return (

        <form id="newtodo" onSubmit={this.addTodo}>
          <input className="edit" type="text" placeholder="Add todo" autoFocus
            value={edit.get('title').val()}
            onChange={edit.get('title').handleChange()} />
        </form>

          {todos.map(function(todo) {
            return (

                  <input
                    className="toggle"
                    type="checkbox"
                    checked={todo.val('completed')}
                    onChange={todo.toggle.bind(todo)} />

                    {todo.val('title')}

            );
          })}

        <button type="button" onClick={history.undo.bind(history)}>Undo</button>
        <button type="button" onClick={history.redo.bind(history)}>Redo</button>

    );
  }
});

window.React = React;
TodoApp.observe(function(val) {
  React.renderComponent(TodoView({
    app: TodoApp,
    appVal: val
  }), document.getElementById('todoapp'));
});
TodoApp.init(); // force a change to start rendering
<commit_msg>todomvc: conditionally hide/show undo/redo<commit_after>/* @jsx React.DOM */
var uuid = require('node-uuid'),
    React = require('react'),
    TodoApp = require('./js/models');

var TodoView = React.createClass({
  addTodo: function(event) {
    event.preventDefault();
    this.props.app.addTodo();
  },
  shouldComponentUpdate: function(newProps) {
    // val is an immutable representation of the app state:
    // if its the same object, nothing changed
    return newProps.appVal !== this.props.appVal;
  },
  render: function() {
    var edit = this.props.app.get('edit'),
        todos = this.props.app.get('todos'),
        history = this.props.app.get('history');
    return (

        <form id="newtodo" onSubmit={this.addTodo}>
          <input className="edit" type="text" placeholder="Add todo" autoFocus
            value={edit.get('title').val()}
            onChange={edit.get('title').handleChange()} />
        </form>

          {todos.map(function(todo) {
            return (

                  <input
                    className="toggle"
                    type="checkbox"
                    checked={todo.val('completed')}
                    onChange={todo.toggle.bind(todo)} />

                    {todo.val('title')}

            );
          })}

        {history.canUndo() ? <button type="button" onClick={history.undo.bind(history)}>Undo</button> : null}
        {history.canRedo() ? <button type="button" onClick={history.redo.bind(history)}>Redo</button> : null}

    );
  }
});

window.React = React;
TodoApp.observe(function(val) {
  React.renderComponent(TodoView({
    app: TodoApp,
    appVal: val
  }), document.getElementById('todoapp'));
});
TodoApp.init(); // force a change to start rendering
<|endoftext|>


<commit_before>import Checkbox from '../Checkbox'
import Button from '../Button'
import Sorter from '../Sorter'
import table from '../../mixins/table'

export default {
  name: 'veui-table-head',
  components: {
    'veui-checkbox': Checkbox,
    'veui-button': Button,
    'veui-sorter': Sorter
  },
  mixins: [table],
  computed: {
    ...table.mapTableData(
      'data',
      'selectable',
      'selectMode',
      'selectStatus',
      { realColumns: 'columns' }
    )
  },
  render () {
    return (

          {
            this.selectable
              ?

                {
                  this.selectMode === 'multiple'
                    ? <veui-checkbox checked={this.selectStatus !== 'none'}
                      disabled={!this.data.length}
                      indeterminate={this.selectStatus === 'partial'}
                      onChange={checked => { this.table.select(checked) }}
                      aria-label={this.checked ? '全部移除' : '全部添加'}/>
                    : null
                }

              : null
          }
          {
            this.columns.map(col => (
              <th
                class={col.align ? `veui-table-column-${col.align}` : null}
                scope="col"
                role="columnheader"
                aria-sort={
                  this.table.orderBy === col.field && this.table.order
                    ? `${this.table.order}ending`
                    : false
                }>

{col.renderHead()}

                {
                  col.sortable
                    ? <veui-sorter
                      order={this.table.orderBy === col.field ? this.table.order : false}
                      onSort={order => { this.$emit('sort', col.field, order) }}>
                    </veui-sorter>
                    : null
                }

            ))
          }

    )
  },
  methods: {
    getAriaSort (order) {
      if (!order) {
        return null
      }
      return order === 'asc' ? 'ascending' : 'descending'
    }
  }
}
<commit_msg>fix: remove unnecessary method<commit_after>import Checkbox from '../Checkbox'
import Button from '../Button'
import Sorter from '../Sorter'
import table from '../../mixins/table'

export default {
  name: 'veui-table-head',
  components: {
    'veui-checkbox': Checkbox,
    'veui-button': Button,
    'veui-sorter': Sorter
  },
  mixins: [table],
  computed: {
    ...table.mapTableData(
      'data',
      'selectable',
      'selectMode',
      'selectStatus',
      { realColumns: 'columns' }
    )
  },
  render () {
    return (

          {
            this.selectable
              ?

                {
                  this.selectMode === 'multiple'
                    ? <veui-checkbox checked={this.selectStatus !== 'none'}
                      disabled={!this.data.length}
                      indeterminate={this.selectStatus === 'partial'}
                      onChange={checked => { this.table.select(checked) }}
                      aria-label={this.checked ? '全部移除' : '全部添加'}/>
                    : null
                }

              : null
          }
          {
            this.columns.map(col => (
              <th
                class={col.align ? `veui-table-column-${col.align}` : null}
                scope="col"
                role="columnheader"
                aria-sort={
                  this.table.orderBy === col.field && this.table.order
                    ? `${this.table.order}ending`
                    : false
                }>

{col.renderHead()}

                {
                  col.sortable
                    ? <veui-sorter
                      order={this.table.orderBy === col.field ? this.table.order : false}
                      onSort={order => { this.$emit('sort', col.field, order) }}>
                    </veui-sorter>
                    : null
                }

            ))
          }

    )
  }
}
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version["enyo-cordova"] = "2.3.0-pre.11-dev";
}
<commit_msg>Update version string to 2.3.0-pre.11<commit_after>if (enyo && enyo.version) {
	enyo.version["enyo-cordova"] = "2.3.0-pre.11";
}
<|endoftext|>


<commit_before>'use strict';

// Required args: args, defaults
function core_args(args){
    if(args['args'] === void 0){
        args['args'] = {};
    }

    for(var arg in args['defaults']){
        if(args['args'][arg] === void 0){
            args['args'][arg] = args['defaults'][arg];
        }
    }

    return args['args'];
}

// Required args: todo
// Optional args: args
function core_call(args){
    args = core_args({
      'args': args,
      'defaults': {
        'args': void 0,
      },
    });

    if(core_type({
      'var': args['todo'],
    })){
        window[args['todo']](args['args']);
    }
}

// Optional args: var
function core_handle_defaults(args){
    args = core_args({
      'args': args,
      'defaults': {
        'var': {},
      },
    });

    if(!core_type({
      'type': 'object',
      'var': args['var'],
    })){
        return args['var'];
    }

    var object = {};

    for(var property in args['var']){
        if(core_type({
          'type': 'object',
          'var': args['var'][property],
        })){
            object[property] = core_handle_defaults({
              'var': args['var'][property],
            });

        }else{
            object[property] = args['var'][property];
        }
    }

    return object;
}

// Required args: var
// Optional args: type
function core_type(args){
    args = core_args({
      'args': args,
      'defaults': {
        'type': 'function',
      },
    });

    if(args['type'] === 'function'){
        return typeof args['var'] === 'function'
          || typeof window[args['var']] === 'function';
    }

    if(args['type'] === 'array'){
        return args['var'] instanceof Array;
    }

    if(args['type'] === 'object'){
        return args['var'] instanceof Object
          && !(args['var'] instanceof Array);
    }

    return typeof args['var'] === args['type'];
}

function core_uid(){
    var uid = core_uid_create();

    while(core_uids[uid] !== void 0){
        uid = core_uid_create();
    }

    core_uids[uid] = true;

    return uid;
}

function core_uid_create(){
    var uid = '';

    for(var i = 0; i < 3; i++){
        uid += parseInt(
          Math.random() * 1e17,
          10
        ).toString(34);
    }

    return uid;
}

var core_uids = {};
<commit_msg>simplified core_handle_defaults()<commit_after>'use strict';

// Required args: args, defaults
function core_args(args){
    if(args['args'] === void 0){
        args['args'] = {};
    }

    for(var arg in args['defaults']){
        if(args['args'][arg] === void 0){
            args['args'][arg] = args['defaults'][arg];
        }
    }

    return args['args'];
}

// Required args: todo
// Optional args: args
function core_call(args){
    args = core_args({
      'args': args,
      'defaults': {
        'args': void 0,
      },
    });

    if(core_type({
      'var': args['todo'],
    })){
        window[args['todo']](args['args']);
    }
}

// Optional args: var
function core_handle_defaults(args){
    args = core_args({
      'args': args,
      'defaults': {
        'var': {},
      },
    });

    if(!core_type({
      'type': 'object',
      'var': args['var'],
    })){
        return args['var'];
    }

    var object = {};

    for(var property in args['var']){
        object[property] = core_handle_defaults({
          'var': args['var'][property],
        });
    }

    return object;
}

// Required args: var
// Optional args: type
function core_type(args){
    args = core_args({
      'args': args,
      'defaults': {
        'type': 'function',
      },
    });

    if(args['type'] === 'function'){
        return typeof args['var'] === 'function'
          || typeof window[args['var']] === 'function';
    }

    if(args['type'] === 'array'){
        return args['var'] instanceof Array;
    }

    if(args['type'] === 'object'){
        return args['var'] instanceof Object
          && !(args['var'] instanceof Array);
    }

    return typeof args['var'] === args['type'];
}

function core_uid(){
    var uid = core_uid_create();

    while(core_uids[uid] !== void 0){
        uid = core_uid_create();
    }

    core_uids[uid] = true;

    return uid;
}

function core_uid_create(){
    var uid = '';

    for(var i = 0; i < 3; i++){
        uid += parseInt(
          Math.random() * 1e17,
          10
        ).toString(34);
    }

    return uid;
}

var core_uids = {};
<|endoftext|>


<commit_before>/* eslint-disable no-restricted-syntax, max-len, no-await-in-loop, no-plusplus */
const { spawn } = require('child_process');

const runtimeSupport = require('../lib/helpers/runtime_support');

let first = true;

function pass({ format, mountTo, mountVia } = {}) {
  const child = spawn(
    'nyc',
    ['--silent', first ? '' : '--no-clean', 'npm', 'run', 'test', '--', `--format=${format}`].filter(Boolean),
    {
      stdio: 'inherit',
      shell: true,
      env: {
        ...process.env,
        CI: true,
        MOUNT_TO: mountTo,
        MOUNT_VIA: mountVia,
      },
    },
  );

  first = false;

  return new Promise((resolve, reject) => {
    child.on('close', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject();
      }
    });
  });
}

function report() {
  const child = spawn(
    'nyc',
    ['report'],
    {
      stdio: 'inherit',
      shell: true,
    },
  );

  return new Promise((resolve) => {
    child.on('close', resolve);
  });
}

function cartesian(...arg) {
  const r = [];
  const max = arg.length - 1;

  function helper(arr, i) {
    for (let j = 0, l = arg[i].length; j < l; j++) {
      const a = arr.slice(0);
      a.push(arg[i][j]);
      if (i === max) r.push(a);
      else helper(a, i + 1);
    }
  }
  helper([], 0);
  return r;
}

(async () => {
  const formats = ['opaque', 'jwt', 'jwt-ietf', runtimeSupport.EdDSA ? 'paseto' : '', 'dynamic'].filter(Boolean);
  const matrix = [
    ['koa', 'express', 'connect'],
    ['/', '/oidc'],
  ];

  for (const format of formats) {
    await pass({ format });
  }

  for (const format of formats) {
    const runs = cartesian(...matrix);
    for (const [mountVia, mountTo] of runs) {
      await pass({ format, mountVia, mountTo });
    }
  }

  await report();
})();
<commit_msg>ci: exit 1 when runs fail<commit_after>/* eslint-disable no-restricted-syntax, max-len, no-await-in-loop, no-plusplus */
const { spawn } = require('child_process');

const runtimeSupport = require('../lib/helpers/runtime_support');

let first = true;

function pass({ format, mountTo, mountVia } = {}) {
  const child = spawn(
    'nyc',
    ['--silent', first ? '' : '--no-clean', 'npm', 'run', 'test', '--', `--format=${format}`].filter(Boolean),
    {
      stdio: 'inherit',
      shell: true,
      env: {
        ...process.env,
        CI: true,
        MOUNT_TO: mountTo,
        MOUNT_VIA: mountVia,
      },
    },
  );

  first = false;

  return new Promise((resolve, reject) => {
    child.on('close', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject();
      }
    });
  });
}

function report() {
  const child = spawn(
    'nyc',
    ['report'],
    {
      stdio: 'inherit',
      shell: true,
    },
  );

  return new Promise((resolve) => {
    child.on('close', resolve);
  });
}

function cartesian(...arg) {
  const r = [];
  const max = arg.length - 1;

  function helper(arr, i) {
    for (let j = 0, l = arg[i].length; j < l; j++) {
      const a = arr.slice(0);
      a.push(arg[i][j]);
      if (i === max) r.push(a);
      else helper(a, i + 1);
    }
  }
  helper([], 0);
  return r;
}

(async () => {
  const formats = ['opaque', 'jwt', 'jwt-ietf', runtimeSupport.EdDSA ? 'paseto' : '', 'dynamic'].filter(Boolean);
  const matrix = [
    ['koa', 'express', 'connect'],
    ['/', '/oidc'],
  ];

  for (const format of formats) {
    await pass({ format });
  }

  for (const format of formats) {
    const runs = cartesian(...matrix);
    for (const [mountVia, mountTo] of runs) {
      await pass({ format, mountVia, mountTo });
    }
  }

  await report();
})().catch(() => {
  process.exitCode = 1;
});
<|endoftext|>


<commit_before>'use strict';

module.exports = function(app) {
  app.controller('ChartController', ['$rootScope', 'GameService', function($rs, GameService) {

    this.games = [];
    let nameData, strokeData, dateData = [];

    this.getAllFromLocalStorage = function() {
      GameService.getAllFromLocalStorage()
        .then((gameData) => {
          this.sortAllData(gameData)
            .then(this.loadChart());
        })
        .catch(() => {
          console.log('error getting data');
        });
    };

    this.sortAllData = function(gameArray) {
      return new Promise((resolve, reject) => {
        this.sortStrokeData(gameArray)
          .then(this.sortDateData(gameArray))
              .then(resolve)
                .catch(reject);
      });
    };

    this.sortStrokeData = function(gameArray) {
      return new Promise((resolve, reject) => {
        if (!gameArray.length) reject;
        let results = [];
        gameArray.forEach((game, index) => {
          results[gameArray.length - index - 1] = game.yourStrokes;
        });
        strokeData = results;
        resolve(results);
      });
    };

    this.sortDateData = function(gameArray) {
      return new Promise((resolve, reject) => {
        if (!gameArray.length) reject;
        let results = [];
        gameArray.forEach((game, index) => {
          results[gameArray.length - index - 1] = game.playedOn.substr(0, game.playedOn.length - 5);
        });
        dateData = results;
        resolve(results);
      });
    };

    this.loadChart = function() {
      let Chart = require('chart.js');
      let ctx = document.getElementById('gameChart').getContext('2d');
      let chartjsPluginAnnotation = require('chartjs-plugin-annotation');
      Chart.pluginService.register(chartjsPluginAnnotation);

      let userHandicap = JSON.parse(window.sessionStorage.getItem('currentUser')).handicap;
      let chartData = {
        labels: dateData,
        datasets: [
          {
            label: 'Strokes',
            // backgroundColor: 'rgba(75, 78, 84, 1)',
            // borderColor: 'rgba(75, 78, 84, 1)',
            borderWidth: 3,
            data: strokeData,
          },
        ],
      };

      let gameChart = new Chart(ctx, {
        type: 'line',
        data: chartData,
        options: {
          responsive: true,
          layout: {
            padding: {
              top: 30,
              right: 15,
              bottom: 15,
              left: 15,
            },
          },
          legend: {
            display: false,
            labels: {
              boxWidth: 5,
              padding: 15,
              fontSize: 14,
            },
          },
          elements: {
            line: {
              tension: 0.1,
              fill: false,
              borderColor: 'rgba(75, 78, 84, 0.9)',
              pointBackgroundColor: 'rgba(254, 172, 0, 1)',
              pointBorderColor: 'rgba(254, 172, 0, 1)',
            },
            point: {
              radius: 3,
              hoverRadius: 5,
              backgroundColor: 'rgba(254, 172, 0, 0.8)',
              borderColor: 'rgba(254, 172, 0, 0.8)',
            },
          },
          tooltips: {
            xPadding: 10,
            yPadding: 10,
            cornerRadius: 2,
            caretSize: 8,
            backgroundColor: 'rgba(75, 78, 84, 0.8)',
            titleFontSize: 14,
            titleSpacing: 4,
            titleMarginBottom: 10,
            bodyFontSize: 14,
            bodySpacing: 4,
          },
          annotation: {
            drawTime: 'afterDatasetsDraw',
            annotations: [{
              drawTime: 'afterDatasetsDraw',
              id: 'h-line-1',
              type: 'line',
              mode: 'horizontal',
              scaleID: 'y-axis-0',
              value: userHandicap,
              borderColor: 'rgba(77, 187, 51, 0.3)',
              borderWidth: 5,
              label: {
                backgroundColor: 'rgba(77, 187, 51, 0.4)',
                position: 'center',
                enabled: true,
                content: 'Handicap: ' + userHandicap,
              },
            }],
          },
        },
      });
    };

  }]);
};
<commit_msg>more changes to chart style<commit_after>'use strict';

module.exports = function(app) {
  app.controller('ChartController', ['$rootScope', 'GameService', function($rs, GameService) {

    this.games = [];
    let nameData, strokeData, dateData = [];

    this.getAllFromLocalStorage = function() {
      GameService.getAllFromLocalStorage()
        .then((gameData) => {
          this.sortAllData(gameData)
            .then(this.loadChart());
        })
        .catch(() => {
          console.log('error getting data');
        });
    };

    this.sortAllData = function(gameArray) {
      return new Promise((resolve, reject) => {
        this.sortStrokeData(gameArray)
          .then(this.sortDateData(gameArray))
              .then(resolve)
                .catch(reject);
      });
    };

    this.sortStrokeData = function(gameArray) {
      return new Promise((resolve, reject) => {
        if (!gameArray.length) reject;
        let results = [];
        gameArray.forEach((game, index) => {
          results[gameArray.length - index - 1] = game.yourStrokes;
        });
        strokeData = results;
        resolve(results);
      });
    };

    this.sortDateData = function(gameArray) {
      return new Promise((resolve, reject) => {
        if (!gameArray.length) reject;
        let results = [];
        gameArray.forEach((game, index) => {
          results[gameArray.length - index - 1] = game.playedOn.substr(0, game.playedOn.length - 5);
        });
        dateData = results;
        resolve(results);
      });
    };

    this.loadChart = function() {
      let Chart = require('chart.js');
      let ctx = document.getElementById('gameChart').getContext('2d');
      let chartjsPluginAnnotation = require('chartjs-plugin-annotation');
      Chart.pluginService.register(chartjsPluginAnnotation);

      let userHandicap = JSON.parse(window.sessionStorage.getItem('currentUser')).handicap;
      let chartData = {
        labels: dateData,
        datasets: [
          {
            label: 'Strokes',
            // backgroundColor: 'rgba(75, 78, 84, 1)',
            // borderColor: 'rgba(75, 78, 84, 1)',
            borderWidth: 3,
            data: strokeData,
          },
        ],
      };

      let gameChart = new Chart(ctx, {
        type: 'line',
        data: chartData,
        options: {
          defaultFontColor: '#fff',
          responsive: true,
          layout: {
            padding: {
              top: 30,
              right: 15,
              bottom: 15,
              left: 15,
            },
          },
          legend: {
            display: false,
          },
          scales: {
            xAxes: [{
              gridLines: {
                color: 'rgba(75, 78, 84, 0.1)',
              },
              ticks: {
                fontColor: '#4b4e54',
              },
            }],
            yAxes: [{
              gridLines: {
                color: 'rgba(75, 78, 84, 0.1)',
              },
              ticks: {
                fontColor: '#4b4e54',
              }
            }],
          },
          elements: {
            line: {
              tension: 0.1,
              fill: false,
              borderColor: 'rgba(75, 78, 84, 0.9)',
              pointBackgroundColor: 'rgba(254, 172, 0, 1)',
              pointBorderColor: 'rgba(254, 172, 0, 1)',
            },
            point: {
              radius: 3,
              hoverRadius: 5,
              backgroundColor: 'rgba(254, 172, 0, 0.8)',
              borderColor: 'rgba(254, 172, 0, 0.8)',
            },
          },
          tooltips: {
            xPadding: 10,
            yPadding: 10,
            cornerRadius: 2,
            caretSize: 8,
            backgroundColor: 'rgba(75, 78, 84, 0.8)',
            titleFontSize: 14,
            titleSpacing: 4,
            titleMarginBottom: 10,
            bodyFontSize: 14,
            bodySpacing: 4,
          },
          annotation: {
            drawTime: 'afterDatasetsDraw',
            annotations: [{
              drawTime: 'afterDatasetsDraw',
              id: 'h-line-1',
              type: 'line',
              mode: 'horizontal',
              scaleID: 'y-axis-0',
              value: userHandicap,
              borderColor: 'rgba(77, 187, 51, 0.3)',
              borderWidth: 5,
              label: {
                backgroundColor: 'rgba(77, 187, 51, 0.4)',
                position: 'center',
                enabled: true,
                content: 'Handicap: ' + userHandicap,
              },
            }],
          },
        },
      });
    };

  }]);
};
<|endoftext|>


<commit_before>
var cobs = require('../'),
    assert = require('assert');

// Working storage with one variable

var parser = new cobs.Parser('\
DATA DIVISION.\r\n\
WORKING-STORAGE SECTION.\r\n\
01 ITEM.\r\n\
    ');

var program = parser.parseProgram();

assert.ok(program);
assert.ok(program.data);
assert.ok(program.data.working_storage);
assert.ok(typeof(program.data.working_storage.item) != 'undefined');

// Working storage with two variables

var parser = new cobs.Parser('\
DATA DIVISION.\r\n\
WORKING-STORAGE SECTION.\r\n\
01 ITEM1.\r\n\
01 ITEM2.\r\n\
    ');

var program = parser.parseProgram();

assert.ok(program);
assert.ok(program.data);
assert.ok(program.data.working_storage);
assert.ok(typeof(program.data.working_storage.item1) != 'undefined');
assert.ok(typeof(program.data.working_storage.item2) != 'undefined');

// Working storage with group item and two subitems

var parser = new cobs.Parser('\
DATA DIVISION.\r\n\
WORKING-STORAGE SECTION.\r\n\
01 GROUP1.\r\n\
02 ITEM1.\r\n\
02 ITEM2.\r\n\
    ');

var program = parser.parseProgram();

assert.ok(program);
assert.ok(program.data);
assert.ok(program.data.working_storage);
assert.ok(typeof(program.data.working_storage.group1) != 'undefined');
assert.ok(typeof(program.data.working_storage.group1.items.item1) != 'undefined');
assert.ok(typeof(program.data.working_storage.group1.items.item2) != 'undefined');
<commit_msg>multi level group/items in working storage, test<commit_after>
var cobs = require('../'),
    assert = require('assert');

// Working storage with one variable

var parser = new cobs.Parser('\
DATA DIVISION.\r\n\
WORKING-STORAGE SECTION.\r\n\
01 ITEM.\r\n\
    ');

var program = parser.parseProgram();

assert.ok(program);
assert.ok(program.data);
assert.ok(program.data.working_storage);
assert.ok(typeof(program.data.working_storage.item) != 'undefined');

// Working storage with two variables

var parser = new cobs.Parser('\
DATA DIVISION.\r\n\
WORKING-STORAGE SECTION.\r\n\
01 ITEM1.\r\n\
01 ITEM2.\r\n\
    ');

var program = parser.parseProgram();

assert.ok(program);
assert.ok(program.data);
assert.ok(program.data.working_storage);
assert.ok(typeof(program.data.working_storage.item1) != 'undefined');
assert.ok(typeof(program.data.working_storage.item2) != 'undefined');

// Working storage with group item and two subitems

var parser = new cobs.Parser('\
DATA DIVISION.\r\n\
WORKING-STORAGE SECTION.\r\n\
01 GROUP1.\r\n\
02 ITEM1.\r\n\
02 ITEM2.\r\n\
    ');

var program = parser.parseProgram();

assert.ok(program);
assert.ok(program.data);
assert.ok(program.data.working_storage);
assert.ok(typeof(program.data.working_storage.group1) != 'undefined');
assert.ok(typeof(program.data.working_storage.group1.items.item1) != 'undefined');
assert.ok(typeof(program.data.working_storage.group1.items.item2) != 'undefined');

// Working storage with two group items and three levels

var parser = new cobs.Parser('\
DATA DIVISION.\r\n\
WORKING-STORAGE SECTION.\r\n\
01 GROUP1.\r\n\
02 ITEM1.\r\n\
03 SUBITEM1.\r\n\
03 SUBITEM2.\r\n\
02 ITEM2.\r\n\
01 GROUP2.\r\n\
02 ITEM1.\r\n\
02 ITEM2.\r\n\
    ');

var program = parser.parseProgram();

assert.ok(program);
assert.ok(program.data);
assert.ok(program.data.working_storage);
assert.ok(program.data.working_storage.group1);
assert.ok(program.data.working_storage.group1.items.item1);
assert.ok(program.data.working_storage.group1.items.item1.items);
assert.ok(typeof(program.data.working_storage.group1.items.item1.items.subitem1) != 'undefined');
assert.ok(typeof(program.data.working_storage.group1.items.item1.items.subitem2) != 'undefined');
assert.ok(typeof(program.data.working_storage.group1.items.item2) != 'undefined');
assert.ok(program.data.working_storage.group2);
assert.ok(typeof(program.data.working_storage.group2.items.item1) != 'undefined');
assert.ok(typeof(program.data.working_storage.group2.items.item2) != 'undefined');
<|endoftext|>


<commit_before>angular.module('pitchfxApp').controller('BattingstatsCtrl', ['$scope', '$log', '$timeout', 'Filters', 'Stats', 'Charting',
    function($scope, $log, $timeout, filtersService, statsService, chartingService) {

        var hipChart, hipScatter, hipScatterDestroyFunction;

        $scope.loading = true;
        $scope.filtersService = filtersService;

        /**
         * Setup the controller
         */
        function init() {
            $scope.$watch('filtersService.filters', function(filters) {
                filtersService.loadingData = true;
                statsService.getStats($scope.playerId, filters).then(function(stats) {
                    $scope.stats = stats;
                    renderCharts();
                    $scope.loading = false;
                    filtersService.loadingData = false;
                });
            }, true);
        }

        /**
         * Gets an HTML label for the tooltip of balls hit-in-play
         *
         * @param {string}
         *            hipType - one of (grounder|liner|flyball|popup)
         * @returns {string} the tooltip contents
         */
        function hipTypesTooltip() {
            $log.debug(this);
            var tooltip = 'Field Distribution',
                fields = null;
            if ($scope.stats.hitBallDistribution && $scope.stats.hitBallDistribution[this.key]) {
                fields = $scope.stats.hitBallDistribution[this.key];
                if (fields.L) {
                    tooltip += '
Left: ' + fields.L + ' (' + (fields.L / this.y * 100).toFixed(1) + '%)';
                }
                if (fields.C) {
                    tooltip += '
Center: ' + fields.C + ' (' + (fields.C / this.y * 100).toFixed(1) + '%)';
                }
                if (fields.R) {
                    tooltip += '
Right: ' + fields.R + ' (' + (fields.R / this.y * 100).toFixed(1) + '%)';
                }
            }
            return tooltip;
        }

        /**
         * Renders advanced charts
         */
        function renderCharts() {
            /*
             * render charts with a timeout to let the screen size snap first
             */
            $timeout(function() {
                renderHipTypes();
                renderHipScatter();
            }, 10);
        }

        /**
         * The scatter plot for hit balls
         */
        function renderHipScatter() {
            var series = [],
                trajectory;

            if (hipScatterDestroyFunction) {
                hipScatterDestroyFunction();
            }
            for (trajectory in $scope.stats.hitBalls) {
                series.push({
                    name: trajectory,
                    data: $scope.stats.hitBalls[trajectory]
                });
            }
            hipScatter = new Highcharts.Chart({
                chart: {
                    type: 'scatter',
                    renderTo: 'hipScatter',
                    backgroundColor: 'transparent',
                    plotBackgroundImage: '/images/stadiums/1.svg',
                    margin: [0, 0, 0, 0],
                    spacingTop: 0,
                    spacingBottom: 0,
                    spacingLeft: 0,
                    spacingRight: 0
                },
                credits: {
                    enabled: false
                },
                title: {
                    text: '',
                    enabled: false
                },
                xAxis: {
                    min: 0,
                    max: 250,
                    labels: {
                        enabled: true,
                    },
                    title: {
                        enabled: false,
                    },
                    lineWidth: 0,
                    minorGridLineWidth: 0,
                    lineColor: 'transparent',
                    minorTickLength: 0,
                    tickLength: 0
                },
                yAxis: {
                    max: 0,
                    min: -250,
                    labels: {
                        enabled: true,
                    },
                    title: {
                        enabled: false,
                    },
                    gridLineColor: 'transparent'
                },
                plotOptions: {
                    series: {
                        animation: false
                    },
                    scatter: {
                        marker: {
                            radius: 5,
                            states: {
                                hover: {
                                    enabled: true,
                                    lineColor: 'rgb(100,100,100)'
                                }
                            }
                        },
                        states: {
                            hover: {
                                marker: {
                                    enabled: false
                                }
                            }
                        },
                    }
                },
                series: series
            });
            hipScatterDestroyFunction = chartingService.keepSquare(hipScatter);
        }

        /**
         * The pie chart for hit ball types
         */
        function renderHipTypes() {
            var series = [],
                trajectory;
            for (trajectory in $scope.stats.hitBalls) {
                series.push([trajectory, $scope.stats.hitBalls[trajectory].length]);
            }
            if (!hipChart) {
                hipChart = new Highcharts.Chart({
                    chart: {
                        renderTo: 'hipTypes',
                        margin: [0, 0, 0, 0],
                        spacingTop: 0,
                        spacingBottom: 0,
                        spacingLeft: 0,
                        spacingRight: 0
                    },
                    credits: {
                        enabled: false
                    },
                    plotOptions: {
                        pie: {
                            size: '100%',
                            dataLabels: {
                                color: '#eee',
                                distance: -40,
                                enabled: true,
                                format: '{point.name}
{point.y} ({point.percentage:.1f}%)'
                            }
                        }
                    },
                    tooltip: {
                        formatter: hipTypesTooltip
                    },
                    title: {
                        text: '',
                        enabled: false
                    },
                    series: [{
                        name: 'Hit Balls',
                        type: 'pie',
                        data: series
                    }]
                });
                chartingService.keepSquare(hipChart);
            } else {
                hipChart.series[0].setData(series, true);
            }
        }

        init();
    }
]);
<commit_msg>#41: breaking jshint on purpose - checking travisci build<commit_after>angular.module('pitchfxApp').controller('BattingstatsCtrl', ['$scope', '$log', '$timeout', 'Filters', 'Stats', 'Charting',
    function($scope, $log, $timeout, filtersService, statsService, chartingService) {

        var hipChart, hipScatter, hipScatterDestroyFunction;

        $scope.loading = true;
        $scope.filtersService = filtersService;

        /**
         * Setup the controller
         */
        function init() {
            $scope.$watch('filtersService.filters', function(filters) {
                filtersService.loadingData = true;
                statsService.getStats($scope.playerId, filters).then(function(stats) {
                    $scope.stats = stats;
                    renderCharts();
                    $scope.loading = false;
                    filtersService.loadingData = false;
                });
            }, true);
        }

        /**
         * Gets an HTML label for the tooltip of balls hit-in-play
         *
         * @param {string}
         *            hipType - one of (grounder|liner|flyball|popup)
         * @returns {string} the tooltip contents
         */
        function hipTypesTooltip() {
            $log.debug(this);
            var tooltip = 'Field Distribution',
                fields = null;
            if ($scope.stats.hitBallDistribution && $scope.stats.hitBallDistribution[this.key]) {
                fields = $scope.stats.hitBallDistribution[this.key];
                if (fields.L) {
                    tooltip += '
Left: ' + fields.L + ' (' + (fields.L / this.y * 100).toFixed(1) + '%)';
                }
                if (fields.C) {
                    tooltip += '
Center: ' + fields.C + ' (' + (fields.C / this.y * 100).toFixed(1) + '%)';
                }
                if (fields.R) {
                    tooltip += '
Right: ' + fields.R + ' (' + (fields.R / this.y * 100).toFixed(1) + '%)';
                }
            }
            return tooltip;
        }

        /**
         * Renders advanced charts
         */
        function renderCharts() {
            /*
             * render charts with a timeout to let the screen size snap first
             */
            $timeout(function() {
                renderHipTypes();
                renderHipScatter();
            }, 10);
        }

        /**
         * The scatter plot for hit balls
         */
        function renderHipScatter() {
            var series = [],
                trajectory;

            if (hipScatterDestroyFunction) {
                hipScatterDestroyFunction();
            }
            for (trajectory in $scope.stats.hitBalls) {
                series.push({
                    name: trajectory,
                    data: $scope.stats.hitBalls[trajectory]
                });
            }
            hipScatter = new Highcharts.Chart({
                chart: {
                    type: 'scatter',
                    renderTo: 'hipScatter',
                    backgroundColor: 'transparent',
                    plotBackgroundImage: '/images/stadiums/1.svg',
                    margin: [0, 0, 0, 0],
                    spacingTop: 0,
                    spacingBottom: 0,
                    spacingLeft: 0,
                    spacingRight: 0
                },
                credits: {
                    enabled: false
                },
                title: {
                    text: '',
                    enabled: false
                },
                xAxis: {
                    min: 0,
                    max: 250,
                    labels: {
                        enabled: true,
                    },
                    title: {
                        enabled: false,
                    },
                    lineWidth: 0,
                    minorGridLineWidth: 0,
                    lineColor: 'transparent',
                    minorTickLength: 0,
                    tickLength: 0
                },
                yAxis: {
                    max: 0,
                    min: -250,
                    labels: {
                        enabled: true,
                    },
                    title: {
                        enabled: false,
                    },
                    gridLineColor: 'transparent'
                },
                plotOptions: {
                    series: {
                        animation: false
                    },
                    scatter: {
                        marker: {
                            radius: 5,
                            states: {
                                hover: {
                                    enabled: true,
                                    lineColor: 'rgb(100,100,100)'
                                }
                            }
                        },
                        states: {
                            hover: {
                                marker: {
                                    enabled: false
                                }
                            }
                        },
                    }
                },
                series: series
            });
            hipScatterDestroyFunction = chartingService.keepSquare(hipScatter);
        }

        /**
         * The pie chart for hit ball types
         */
        function renderHipTypes() {
            var series = [],
                trajectory;
            for (trajectory in $scope.stats.hitBalls) {
                series.push([trajectory, $scope.stats.hitBalls[trajectory].length]);
            }
            if (!hipChart) {
                hipChart = new Highcharts.Chart({
                    chart: {
                        renderTo: 'hipTypes',
                        margin: [0, 0, 0, 0],
                        spacingTop: 0,
                        spacingBottom: 0,
                        spacingLeft: 0,
                        spacingRight: 0
                    },
                    credits: {
                        enabled: false
                    },
                    plotOptions: {
                        pie: {
                            size: '100%',
                            dataLabels: {
                                color: '#eee',
                                distance: -40,
                                enabled: true,
                                format: '{point.name}
{point.y} ({point.percentage:.1f}%)'
                            }
                        }
                    },
                    tooltip: {
                        formatter: hipTypesTooltip
                    },
                    title: {
                        text: '',
                        enabled: false
                    },
                    series: [{
                        name: 'Hit Balls',
                        type: 'pie',
                        data: series
                    }]
                });
                chartingService.keepSquare(hipChart);
            } else {
                hipChart.series[0].setData(series, true);
                var guh;
            }
        }

        init();
    }
]);
<|endoftext|>


<commit_before>"use strict";

var GPS = require('./NMEAReader.js').NMEA;
var gps = new GPS('/dev/ttyUSB0', 4800);
// var gps = new GPS();

gps.onPosition = function(pos) {
  console.log("Position:", pos);
};
gps.onTime = function(epoch) {
  console.log("Time: " + new Date(epoch));
};

var exit = function() {
  gps.exit();
};

process.on('SIGINT', exit); // Ctrl C
<commit_msg>nput from the node console (testGPS)<commit_after>"use strict";

console.log('To stop: Ctrl-C, or enter "quit" + [return]');

var util = require('util');
var GPS = require('./NMEAReader.js').NMEA;
var gps = new GPS('/dev/ttyUSB0', 4800);
// var gps = new GPS();

gps.onPosition = function(pos) {
  console.log("Position:", pos);
};
gps.onTime = function(epoch) {
  console.log("Time: " + new Date(epoch));
};

var exit = function() {
  gps.exit();
  process.stdin.pause();
};

process.on('SIGINT', exit); // Ctrl C
process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (text) {
//console.log('received data:', util.inspect(text));
  if (text.startsWith('quit')) {
    done();
  }
});

function done() {
  console.log("Bye now!");
  exit();
  process.exit();
};
<|endoftext|>


<commit_before>// GLOBAL VARIABLES
var nodes = {
	downloadArea: document.querySelector('#downloadArea'),
	inputArea: document.querySelector('#inputArea'),
	jsonArea: document.querySelector('#jsonArea'),
	transcriptionBox: document.querySelector('#transcriptionBox'),
	translationBox: document.querySelector('#translationBox')
};

var phrase = {
	transcription: '',
	translation: '',
	words: []
};

// CONSTRUCTORS
function Word(token, gloss, partOfSpeech) {
	this.token = token;
	this.gloss = gloss;
	this.partOfSpeech = partOfSpeech;
};

// GLOBAL FUNCTIONS
function displayDictionary() {

};

function displayInterlinear() {

};

function displayJSON() {
	nodes.jsonArea.innerHTML = JSON.stringify(phrase, null, 2);
};

function downloadJSON(){
	// Get the JSON data
	var text = nodes.jsonArea.innerHTML;
	// Encode
	var data = "text/json;charset=utf-8," + encodeURIComponent(text);
	// Create a download link
	nodes.downloadArea.innerHTML = 'Download your data!'
}

// Updates the phrase object, and (re-)renders the JSON, interlinear, and lexicon visualizations
function render() {
	updatePhrase();
	displayJSON();
	displayInterlinear();
	displayDictionary();
};

function updatePhrase() {
	var transcription = nodes.transcriptionBox.value;
	var translation = nodes.translationBox.value;
	var tokens = transcription.split(/[\u3000 .,!?]/g);

	var words = [];
	tokens.forEach(function(token) {
		var word = new Word(token, '', '');
		words.push(word);
	});
	phrase.words = words;

	phrase.transcription = transcription;
	phrase.translation = translation;
};

// EVENT LISTENERS
nodes.inputArea.addEventListener('input', downloadJSON);
window.addEventListener('load', downloadJSON);

nodes.inputArea.addEventListener('input', render);
window.addEventListener('load', render);
<commit_msg>fixes #23 delimiters<commit_after>// GLOBAL VARIABLES
var nodes = {
	downloadArea: document.querySelector('#downloadArea'),
	inputArea: document.querySelector('#inputArea'),
	jsonArea: document.querySelector('#jsonArea'),
	transcriptionBox: document.querySelector('#transcriptionBox'),
	translationBox: document.querySelector('#translationBox')
};

var phrase = {
	transcription: '',
	translation: '',
	words: []
};

// CONSTRUCTORS
function Word(token, gloss, partOfSpeech) {
	this.token = token;
	this.gloss = gloss;
	this.partOfSpeech = partOfSpeech;
};

// GLOBAL FUNCTIONS
function displayDictionary() {

};

function displayInterlinear() {

};

function displayJSON() {
	nodes.jsonArea.innerHTML = JSON.stringify(phrase, null, 2);
};

function downloadJSON(){
	// Get the JSON data
	var text = nodes.jsonArea.innerHTML;
	// Encode
	var data = "text/json;charset=utf-8," + encodeURIComponent(text);
	// Create a download link
	nodes.downloadArea.innerHTML = 'Download your data!'
}

// Updates the phrase object, and (re-)renders the JSON, interlinear, and lexicon visualizations
function render() {
	updatePhrase();
	displayJSON();
	displayInterlinear();
	displayDictionary();
};

function updatePhrase() {
	var transcription = nodes.transcriptionBox.value;
	var translation = nodes.translationBox.value;
    var tokens = transcription.split(/[ .,!?\:\;\/\\\[\]\{\}\<\>\-\u3000\u00A1\u00BF\u0022\u0027\u00AB\u00BB\u2018\u2019\u201A\u201B\u201C\u201D\u201E\u201F\u2039\u203A\u300C\u300D\u300E\u300F\u301D\u301E\u301F\uFE41\uFE42\uFE43\uFE44\uFF02\uFF07\uFF62\uFF63]+/g).filter(Boolean);
	// basics, brackets, inverted !/?, various quotes from around the world
    // the filter(Boolean) will filter out the "" ending split since "" == False
	var words = [];
	tokens.forEach(function(token) {
		var word = new Word(token, '', '');
		words.push(word);
	});
	phrase.words = words;

	phrase.transcription = transcription;
	phrase.translation = translation;
};

// EVENT LISTENERS
nodes.inputArea.addEventListener('input', downloadJSON);
window.addEventListener('load', downloadJSON);

nodes.inputArea.addEventListener('input', render);
window.addEventListener('load', render);
<|endoftext|>