<commit_before>var strutils = require('../../strutils')

function TeamcityReporter(silent, out){
  this.out = out || process.stdout
  this.silent = silent
  this.stoppedOnError = null
  this.id = 1
  this.total = 0
  this.pass = 0
  this.startTime = new Date()
  this.endTime = null
}
TeamcityReporter.prototype = {
  report: function(prefix, data){
    this.out.write('##teamcity[testStarted name="' + escape(data.name.trim()) + '"]\n');
    this.display(prefix, data)
    this.total++
    if (data.passed) this.pass++
  },

  display: function(prefix, result){
    if (this.silent) return
    if (!result.passed) {
      this.out.write('##teamcity[testFailed name="' + escape(result.name.trim()) + '"] message="'+ escape(result.error.message) +'" details="' + escape(result.error.stack) + '"\n');
    }
    this.out.write('##teamcity[testFinished name="' + escape(result.name.trim()) + '"]\n');

  },
  finish: function(){
    if (this.silent) return
    this.endTime = new Date()
    this.out.write('\n\n')
    this.out.write('##teamcity[testSuiteFinished name="mocha.suite" duration="' + this.duration() + '"]\n')
    this.out.write('\n\n')
  },
  duration: function(){
    return Math.round((this.endTime - this.startTime))
  }
}

/**
 * Escape the given `str`.
 */

function escape(str) {
  if (!str) return '';
  return str
    .toString()
    .replace(/\|/g, "||")
    .replace(/\n/g, "|n")
    .replace(/\r/g, "|r")
    .replace(/\[/g, "|[")
    .replace(/\]/g, "|]")
    .replace(/\u0085/g, "|x")
    .replace(/\u2028/g, "|l")
    .replace(/\u2029/g, "|p")
    .replace(/'/g, "|'");
}

module.exports = TeamcityReporter
<commit_msg>Switch double and single quotes for teamcity reporter<commit_after>var strutils = require('../../strutils')

function TeamcityReporter(silent, out){
  this.out = out || process.stdout
  this.silent = silent
  this.stoppedOnError = null
  this.id = 1
  this.total = 0
  this.pass = 0
  this.startTime = new Date()
  this.endTime = null
}
TeamcityReporter.prototype = {
  report: function(prefix, data){
    this.out.write("##teamcity[testStarted name='" + escape(data.name.trim()) + "']\n");
    this.display(prefix, data)
    this.total++
    if (data.passed) this.pass++
  },

  display: function(prefix, result){
    if (this.silent) return
    if (!result.passed) {
      this.out.write("##teamcity[testFailed name='" + escape(result.name.trim()) + "'] message='"+ escape(result.error.message) +"' details='" + escape(result.error.stack) + "'\n");
    }
    this.out.write("##teamcity[testFinished name='" + escape(result.name.trim()) + "']\n");

  },
  finish: function(){
    if (this.silent) return
    this.endTime = new Date()
    this.out.write('\n\n')
    this.out.write("##teamcity[testSuiteFinished name='mocha.suite' duration='" + this.duration() + "']\n")
    this.out.write('\n\n')
  },
  duration: function(){
    return Math.round((this.endTime - this.startTime))
  }
}

/**
 * Borrowed from https://github.com/travisjeffery/mocha-teamcity-reporter
 * Escape the given `str`.
 */

function escape(str) {
  if (!str) return '';
  return str
    .toString()
    .replace(/\|/g, "||")
    .replace(/\n/g, "|n")
    .replace(/\r/g, "|r")
    .replace(/\[/g, "|[")
    .replace(/\]/g, "|]")
    .replace(/\u0085/g, "|x")
    .replace(/\u2028/g, "|l")
    .replace(/\u2029/g, "|p")
    .replace(/'/g, "|'");
}

module.exports = TeamcityReporter
<|endoftext|>


<commit_before>angular.module("app/main", [
    'ngRoute',
    'ngAnimate',
    'ngTouch',

    'app/notice/main',
    'app/home/main'
]).run(['$route', '$http', '$templateCache', '$window', function ($route, $http, $templateCache, $window) {
    // preload the template of routes
    angular.forEach($route.routes, function (r) {
        if (r.templateUrl) {
            $http.get(r.templateUrl, {cache: $templateCache});
        }
    });
}]).controller('MainCtrl', ['$scope'
    , '$rootScope'
    , '$route'
    , '$location'
    , '$window'
    , '$timeout'
    , function ($scope, $rootScope, $route, $location, $window, $timeout) {
        if ($location.path() === ''){
            $scope.isShowLogoPage = true;
            $timeout(function () {
                $location.path('/login');
            }, 3000);
        }

        $scope.actionBar = {
            icon: 'fa fa-th-large',
            viewList: [],
            curViewIndex: 0,
            isShowViewList: false,
            btns: []
        };

        // init
        $scope.navDrawerList = [];

        $window.angular.forEach($route.routes, function (item, key) {
            if (item.parentPage == "drawer") {
                $scope.navDrawerList.push(item);
            }
        });

        $scope.switchPage = function (nav) {
            $scope.hideNavDrawer();

            // 清空浏览器历史？
            $window.history.go(-$window.history.length);

            console.log($window.history);
            $location.path(nav.originalPath);
        };

        console.log($window.history);
        $scope.hideNavDrawer = function () {
            $scope.isShowNavDrawer = false;
        };

        function refreshNavDrawerActive(routeItem) {
            $window.angular.forEach($scope.navDrawerList, function (item, key) {
                item.active = false;
                if (routeItem.name === item.name) {
                    item.active = true;
                }
            });
        }

        $rootScope.$on('$routeChangeSuccess', function (ev, msg) {
            refreshNavDrawerActive(msg.$$route);
        });

        $scope.$on('refreshActionBar', function (ev, msg) {
//                console.log('refreshActionBar', msg);
            $scope.actionBar = msg;
        });

    }]);

<commit_msg>删除多余文件<commit_after><|endoftext|>


<commit_before>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var util = require('util');

var Constants = require('../../../util/constants');
var profile = require('../../../util/profile');
var utils = require('../../../util/utils');
var fs = require('fs');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;

  var group = cli.category('group');
  var deployment = group.category('deployment')
      .description($('Commands to manage your deployment in a resource group'));

  deployment.command('list [resourceGroup] [state]')
    .description($('get deployments'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group.'))
    .option('--state <state>', $('Optional. Filter the deployments by provisioning state. Valid values are Accepted, Running, Failed and Succeeded'))
    .option('--subscription <subscription>', $('Subscription to create resource in'))
    .execute(function(resourceGroup, state, options, _) {
      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('listing deployments'));
      try {
        //TODO: how to pass in state w/o a quot in command line?
        var allDeployments = GetAllDeployment(client, resourceGroup, state, _);

        cli.interaction.formatOutput(allDeployments, function (outputData) {
          if (outputData) {
            for (var i = 0; i < outputData.length; i++) {
              var deployment = outputData[i];
              log.data($('================'), deployment.deploymentName);
              cli.interaction.logEachData($(''), deployment);
              cli.interaction.logEachData($(''), deployment.properties);
              //log.data($('Name:             '), deployment.deploymentName);
              //log.data($('ResourceGroup:    '), deployment.resourceGroup)
              //log.data($('ProvisionState:   '), deployment.properties.provisioningState);
              //log.data($('Timestamp:        '), deployment.properties.timestamp);
              //log.data($('Mode:             '), deployment.properties.mode);
              //log.data($('TemplateLink:     '), deployment.properties.templateLink.uri);
              //log.data($('Parameters:'));
              cli.interaction.logEachData($(''), deployment.properties.parameters);
            }
          }
       });
      } finally {
        progress.end();
      }
    });

  deployment.command('show [resourceGroup] [deploymentName]')
    .usage('[options] <resource-group> <deploymentName>')
    .description($('get deployments'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group.'))
    .option('--deploymentName <deploymentName>', $('Optional. The name of the deployment'))
	  .option('--subscription <subscription>', $('Subscription to create resource in'))
    .execute(function(resourceGroup, deploymentName, options, _) {

      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('getting deployments'));
      var deployment;
      try {
        if (deploymentName) {
          deployment = client.deployments.get(resourceGroup, deploymentName, _);
        }
        else {
          var allDeployments = GetAllDeployment(client, resourceGroup, '', _);
          if (allDeployments && allDeployments.length > 0) {
            allDeployments.sort(function (a, b) { return Date.parse(a.properties.timestamp) < parseFloat(b.properties.timestamp) });
            deployment = allDeployments[0];
          }
        }
        if (deployment){
          log.data($('================'), deployment.name || deployment.deploymentName);
          cli.interaction.logEachData($(''), deployment);
          cli.interaction.logEachData($(''), deployment.properties);
          cli.interaction.logEachData($(''), deployment.properties.parameters);
        }
      } finally {
        progress.end();
      }
  });

  deployment.command('stop [resourceGroup]')
    .description($('stop current running deployment'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group.'))
    .option('-q --quiet', $('quiet mode. Do not ask confirmation for stop deployment'))
    .option('--subscription <subscription>', $('Subcription containing group to delete'))
    .execute(function (resourceGroup, options, _) {
      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('stopping running deployment'));

      try{
        var allRunningDeployments = GetAllDeployment(client, resourceGroup, '\'Failed\'', _);
        var runningDeployment;
        //TODO: assert only one member in the array?
        //TODO: figure out the variable declaration position.
        //TODO: print out nothing to do errors
        //TODO: figure out using single quot or double quot for strings
        if (allRunningDeployments && allRunningDeployments.length > 0) {
          runningDeployment = allRunningDeployments[0];
          //TODO: why i will need to press ENTER twice
          if (!options.quiet && !cli.interaction.confirm(util.format($('stop deployment %s? [y/n]:'), runningDeployment.deploymentName), _)) {
            log.data($('Quitting'));
            return;
          }
          client.deployments.cancel(resourceGroup, runningDeployment.deploymentName, _);
        }
        else {
          log.data($('No running deployment to stop'));
        }
      }
      finally {
        progress.end();
      }
    }
  )

  deployment.command('create [templateLink] [resourceGroup] [mode] [deploymentName] [parametersFile]')
    .option('-f --template-link <templateLink>', $('uri to the template file'))
    .option('-g --resource-group <resourceGroup>', $('name of the resource group'))
    .option('-m --mode <mode>', $('mode of the template deployment. Valid values are Repalce, New and Incremental'))
    .option('-n --deployment-name <deploymentName>', $('name of the deployment'))
    .option('-p --parameters-file <parametersFile>', $('file with parameters'))
    .option('--subscription <subscription>', $('Subcription containing group to delete'))
    .execute(function (templateLink, resourceGroup, mode, deploymentName, parametersFile, options, _) {
      function stripBOM(content) {
        if (content.charCodeAt(0) === 0xFEFF) {
          content = content.slice(1);
        }
        return content;
      }

      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('starting to create deployment'));

      var jsonFile = fs.readFileSync('params.json', 'utf8');
      var deploymentParameters = JSON.parse(stripBOM(jsonFile));

      try{
        client.deployments.create(resourceGroup, deploymentName,
          {
            'parameters': deploymentParameters.properties.parameters,
            'mode':       mode,
            'templateLink':
            {
                'uri': templateLink
            }
          }
          ,_
       )
      }
      finally {
        progress.end();
      }

    })

};

function GetAllDeployment(client, resourceGroup, state, _) {

  var response = client.deployments.listForResourceGroup(resourceGroup, { provisioningState: state }, _);
  var allDeployments = response.deployments;
  var nextLink = response.nextLink;

  while (nextLink) {
    client.deployments.listNext(nextLink, function (newSet) {
      allDeployments.concat(newSet.deployments);
      nextLink = nextSet.nextLink;
    })
  }
  return allDeployments;
}<commit_msg>Fix several nits<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var util = require('util');

var Constants = require('../../../util/constants');
var profile = require('../../../util/profile');
var utils = require('../../../util/utils');
var fs = require('fs');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var log = cli.output;

  var group = cli.category('group');
  var deployment = group.category('deployment')
      .description($('Commands to manage your deployment in a resource group'));

  deployment.command('list [resourceGroup] [state]')
    .description($('Get deployments'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group.'))
    .option('--state <state>', $('Optional. Filter the deployments by provisioning state.'
      + 'Valid values are Accepted, Running, Failed and Succeeded'))
    .option('--subscription <subscription>', $('Subscription containing deployments to list'))
    .execute(function (resourceGroup, state, options, _) {

      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('Listing deployments'));

      try {
        var allDeployments = retrieveDeployments(client, resourceGroup, state, _);
        cli.interaction.formatOutput(allDeployments, function (outputData) {
          if (outputData) {
            for (var i = 0; i < outputData.length; i++) {
              var deployment = outputData[i];
              //TODO, will polish the output later
              log.data($('================'), deployment.deploymentName);
              cli.interaction.logEachData($(''), deployment);
              cli.interaction.logEachData($(''), deployment.properties);
              cli.interaction.logEachData($(''), deployment.properties.parameters);
            }
          }
        });
      } finally {
        progress.end();
      }
    });

  deployment.command('show [resourceGroup] [deploymentName] ')
    .description($('get deployments'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group.'))
    .option('-n --deploymentName <deploymentName>', $('Name of the deployment'))
	  .option('--subscription <subscription>', $('Subscription containing the deployment to display'))
    .execute(function (resourceGroup, name, options, _) {

      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('Getting deployments'));
      var deployment;
      try {
        if (name) {
          deployment = client.deployments.get(resourceGroup, name, _);
        }
        else {
          var allDeployments = retrieveDeployments(client, resourceGroup, '', _);
          if (allDeployments && allDeployments.length > 0) {
            //look for the most recent one
            allDeployments.sort( function (a, b) {
                return Date.parse(a.properties.timestamp) < parseFloat(b.properties.timestamp)
            });
            deployment = allDeployments[0];
          }
        }
        if (deployment) {
          //TODO, will polish the output later
          log.data($('================'), deployment.name || deployment.deploymentName);
          cli.interaction.logEachData($(''), deployment);
          cli.interaction.logEachData($(''), deployment.properties);
          cli.interaction.logEachData($(''), deployment.properties.parameters);
        }
      } finally {
        progress.end();
      }
    });

  deployment.command('stop [resourceGroup]')
    .description($('stop current running deployment'))
    .option('-g --resource-group <resourceGroup>', $('Name of the resource group.'))
    .option('-q --quiet', $('Quiet mode. Do not ask confirmation for stop deployment'))
    .option('--subscription <subscription>', $('Subcription containing the deployment to stop'))
    .execute(function (resourceGroup, options, _) {
      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('Stopping deployment'));

      try {
        var allRunningDeployments = retrieveDeployments(client, resourceGroup, '\'Running\'', _);
        if (allRunningDeployments && allRunningDeployments.length > 0) {
          //Each resource group can only have 1 running deployment, we just take the first one
          var runningDeployment = allRunningDeployments[0];
          if (!options.quiet &&
              !cli.interaction.confirm(util.format($('Stop deployment %s? [y/n]: '),
                  runningDeployment.deploymentName), _)) {
            return;
          }
          client.deployments.cancel(resourceGroup, runningDeployment.deploymentName, _);
        }
        else {
          log.data($('There is no running deployments to stop'));
        }
      }
      finally {
        progress.end();
      }
    }
  )

  deployment.command('create [templateLink] [resourceGroup] [mode] [deploymentName] [parametersFile]')
    .option('-f --template-link <templateLink>', $('uri to the template file'))
    .option('-g --resource-group <resourceGroup>', $('name of the resource group'))
    .option('-m --mode <mode>', $('mode of the template deployment. Valid values are Repalce, New and Incremental'))
    .option('-n --deployment-name <deploymentName>', $('name of the deployment'))
    .option('-p --parameters-file <parametersFile>', $('file with parameters'))
    .option('--subscription <subscription>', $('Subcription containing group to delete'))
    .execute(function (templateLink, resourceGroup, mode, deploymentName, parametersFile, options, _) {

      function stripBOM(content) {
        if (content.charCodeAt(0) === 0xFEFF) {
          content = content.slice(1);
        }
        return content;
      }

      var subscription = profile.current.getSubscription(options.subscription);
      var client = subscription.createResourceClient('createResourceManagementClient');
      var progress = cli.interaction.progress($('starting to create deployment'));

      var jsonFile = fs.readFileSync('params.json', 'utf8');
      var deploymentParameters = JSON.parse(stripBOM(jsonFile));

      try {
        client.deployments.create(resourceGroup, deploymentName,
          {
            'parameters': deploymentParameters.properties.parameters,
            'mode': mode,
            'templateLink':
            {
              'uri': templateLink
            }
          }
          , _
       )
      }
      finally {
        progress.end();
      }

    })
};

function retrieveDeployments(client, resourceGroup, state, _) {
  //Wrap the value with single quot(needed for constructing RESTful query string)
  var stateFilter = state;
  if (stateFilter && !(utils.stringStartsWith(stateFilter, '\''))) {
    stateFilter = '\'' + stateFilter + '\'';
  }

  var response = client.deployments.listForResourceGroup(resourceGroup, { provisioningState: stateFilter }, _);
  var allDeployments = response.deployments;
  var nextLink = response.nextLink;
  while (nextLink) {
    client.deployments.listNext(nextLink, function (newSet) {
      allDeployments.concat(newSet.deployments);
      nextLink = nextSet.nextLink;
    })
  }
  return allDeployments;
}<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

class Account extends React.Component {
    constructor(props) {
        super(props);
    };
    render() {
        return (
            <React.Fragment>

Your account

                <UserStats/>
                <AccountForm documentRoot={this.props.documentRoot} userId={this.props.userId}
                             accountId={this.props.accountId} username={this.props.username}/>
            </React.Fragment>
        );
    }
}

function UserStats() {
    return (

Here's your progress

Level 1

33%

You need to complete 15 more plots to reach Level 2

                    Projects Worked So Far
                    2

                    Speed Score Total
                    205

                    Plots Completed Per Project
                    8

                    Accuracy Score Per Project
                    10

                    Plots Completed Total
                    16

                    Accuracy Score Total
                    10

                    Speed Score Per Project
                    205

            <form style={{visibility: 'visible'}}>
                <fieldset>
                    Congratulations! You are ranked #3 overall and #1 in your organization.
                </fieldset>

            </form>

    );
}

function AccountForm(props) {
    if (props.userId == props.accountId) {
        return (

Account Settings

{props.username}

                <form action={props.documentRoot + "/account/" + props.accountId} method="post">

                        Reset email
                        <input autoComplete="off" id="email" name="email" placeholder="New email" defaultValue=""
                               type="email"
                               className="form-control"/>

                        Reset password

                                <input autoComplete="off" id="password" name="password" placeholder="New password"
                                       defaultValue=""
                                       type="password" className="form-control mb-1"/>

                                <input autoComplete="off" id="password-confirmation" name="password-confirmation"
                                       placeholder="New password confirmation" defaultValue="" type="password"
                                       className="form-control"/>

                        Verify your identity
                        <input autoComplete=" off" id="current-password" name="current-password" placeholder="
                                       Current password" defaultValue="" type="password" className="form-control"/>

                    <input className="btn btn-outline-lightgreen btn-block" name="update-account" defaultValue="Update
                                       account settings" type="submit"/>
                </form>

        );
    }
    else {
        return (

Account Settings

{props.username}

        );
    }
}

export function renderAccountPage(args) {
    ReactDOM.render(
        <Account documentRoot={args.documentRoot} userId={args.userId} accountId={args.accountId} username={args.username}/>,
        document.getElementById("account")
    );
}
<commit_msg>hidden account progress<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

class Account extends React.Component {
    constructor(props) {
        super(props);
    };
    render() {
        return (
            <React.Fragment>

Your account

                <UserStats/>
                <AccountForm documentRoot={this.props.documentRoot} userId={this.props.userId}
                             accountId={this.props.accountId} username={this.props.username}/>
            </React.Fragment>
        );
    }
}

function UserStats() {
    return (

Here's your progress

Level 1

33%

You need to complete 15 more plots to reach Level 2

                    Projects Worked So Far
                    2

                    Speed Score Total
                    205

                    Plots Completed Per Project
                    8

                    Accuracy Score Per Project
                    10

                    Plots Completed Total
                    16

                    Accuracy Score Total
                    10

                    Speed Score Per Project
                    205

            <form style={{visibility: 'visible'}}>
                <fieldset>
                    Congratulations! You are ranked #3 overall and #1 in your organization.
                </fieldset>

            </form>

    );
}

function AccountForm(props) {
    if (props.userId == props.accountId) {
        return (

Account Settings

{props.username}

                <form action={props.documentRoot + "/account/" + props.accountId} method="post">

                        Reset email
                        <input autoComplete="off" id="email" name="email" placeholder="New email" defaultValue=""
                               type="email"
                               className="form-control"/>

                        Reset password

                                <input autoComplete="off" id="password" name="password" placeholder="New password"
                                       defaultValue=""
                                       type="password" className="form-control mb-1"/>

                                <input autoComplete="off" id="password-confirmation" name="password-confirmation"
                                       placeholder="New password confirmation" defaultValue="" type="password"
                                       className="form-control"/>

                        Verify your identity
                        <input autoComplete=" off" id="current-password" name="current-password" placeholder="
                                       Current password" defaultValue="" type="password" className="form-control"/>

                    <input className="btn btn-outline-lightgreen btn-block" name="update-account" defaultValue="Update
                                       account settings" type="submit"/>
                </form>

        );
    }
    else {
        return (

Account Settings

{props.username}

        );
    }
}

export function renderAccountPage(args) {
    ReactDOM.render(
        <Account documentRoot={args.documentRoot} userId={args.userId} accountId={args.accountId} username={args.username}/>,
        document.getElementById("account")
    );
}
<|endoftext|>


<commit_before>require('env2')('config.env');

var wsclient = require('./lib/ws-client');
var fs = require('fs');
var utils = require('./lib/utils')
var events = require('events')
var util = require('util');
var async = require('async');
var fs = require('fs');
var debug = require('debug')('explore');
var getopt = require('node-getopt');

var options = new getopt([
  ['a' , 'no-advertisements'   , 'do not save advertisements (default: save)'],
  ['r' , 'no-read'             , 'do not read characteristics values (default: read), helpful when device requires auth and service exploring stalls'],
  ['o' , 'overwrite'           , 'overwrite peripheral services file'],
  ['f' , 'funmode'             , 'have fun!'],
  [''  , 'jk'                  , 'see http://xkcd.com/1692'],
  ['h' , 'help'                , 'display this help'],
]);
options.setHelp('Usage: node scan [ -a ] [ -r ] [ peripheral ]\n' +
'peripheral - optional peripheral device do explore services (MAC address e.g. ec:fe:7e:12:34:56 or id e.g. ecfe7e123456). If not provided, broadcast advertisement scan.' +
'Command-line options:\n[[OPTIONS]]' )

opt=options.parseSystem();

if (opt.options.help) {
  options.showHelp()
  process.exit(0)
}

if (opt.options.funmode) {
  console.log('>>>>>>>>>>>>>>>>> MAY THE FUN BE WITH YOU! <<<<<<<<<<<<<<<<<<'.rainbow.inverse)
}

if (opt.argv.length > 0) {
  var specifiedPeripheral = opt.argv[0].replace(/:/g,'').toLowerCase();
}

var devicesPath=process.env.DEVICES_PATH;
var scanOrExplore = '';
var peripherals=[];
var saveAdvertisements=true;
var readValues=true;
var overWriteServices=false;

if (opt.options.a) {
    console.log('Not saving advertisement discovery.');
    saveAdvertisements=false;
}

if (opt.options.r) {
    console.log('Not reading characteristic values.')
    readValues=false;
}

if (opt.options.overwrite) {
    console.log('Overwrite services file if exists.');
    overWriteServices=true;
}

function exploreSpecified(peripheralId) {

  checkFile(peripheralId, function(exists){
    if (!exists) {
        console.log('Start to explore ' + peripheralId)
        wsclient.explore(peripheralId, readValues);
    } else {
        console.log('Services file for ' + peripheralId + ' already saved, skipping. Use -o option to overwrite.');
    }
  })

}

//check if the services file exists
function checkFile(peripheralId, callback) {
  if (overWriteServices) {
    callback(false);
  } else {
    fs.stat(devicesPath + '/' + peripheralId + '.srv.json', function(err, stat) {
      if(err == null) {
        callback(true);
        //  console.log('File exists');
      } else {
        callback(false)
      }
    });
  }
}

wsclient.on('stateChange', function(state) {
  if (state === 'poweredOn') {
    if (specifiedPeripheral) {
      console.log('Start exploring ' + specifiedPeripheral);
      exploreSpecified(specifiedPeripheral)
    } else {
      console.log('Start scanning.');
      wsclient.startScanning();
    }
  } else if (state === 'unknown') {
    console.log('state unknown - waiting...')
  } else {
    wsclient.stopScanning();
  }
});

wsclient.on('discover', function(peripheralId, address, addressType, connectable, advertisement, rssi) {

        if (saveAdvertisements) {
          utils.saveAdvertisement(peripheralId, address, addressType, connectable, advertisement, rssi);
        }

        if (!peripherals[peripheralId]) {
          peripherals[peripheralId] = { explored: false, triedToExplore: false};
        }

})

wsclient.on('explore', function(peripheralId, state, servicesJson){

  console.log('explore state: ' + peripheralId + ' : ' + state);
  if(state === 'finished') {

    var filename = devicesPath+'/'+peripheralId+'.srv.json';

    fs.writeFile(filename, JSON.stringify(servicesJson, null, 4), function(err) {
        if(err) {
           return console.log(err);
        }
         console.log("Services file "+ filename +" saved!");
         if (peripheralId === specifiedPeripheral) {
            process.exit(0);
         }

    });
  }
})
<commit_msg>bugfix for proper parsing scan.js command-line parameters<commit_after>require('env2')('config.env');

var wsclient = require('./lib/ws-client');
var fs = require('fs');
var utils = require('./lib/utils')
var events = require('events')
var util = require('util');
var async = require('async');
var fs = require('fs');
var debug = require('debug')('explore');
var getopt = require('node-getopt');

var options = new getopt([
  ['a' , 'no-advertisements'   , 'do not save advertisements (default: save)'],
  ['r' , 'no-read'             , 'do not read characteristics values (default: read), helpful when device requires auth and service exploring stalls'],
  ['o' , 'overwrite'           , 'overwrite peripheral services file'],
  ['f' , 'funmode'             , 'have fun!'],
  [''  , 'jk'                  , 'see http://xkcd.com/1692'],
  ['h' , 'help'                , 'display this help'],
]);
options.setHelp('Usage: node scan [ -a ] [ -r ] [ peripheral ]\n' +
'peripheral - optional peripheral device do explore services (MAC address e.g. ec:fe:7e:12:34:56 or id e.g. ecfe7e123456). If not provided, broadcast advertisement scan.' +
'Command-line options:\n[[OPTIONS]]' )

opt=options.parseSystem();

if (opt.options.help) {
  options.showHelp()
  process.exit(0)
}

if (opt.options.funmode) {
  console.log('>>>>>>>>>>>>>>>>> MAY THE FUN BE WITH YOU! <<<<<<<<<<<<<<<<<<'.rainbow.inverse)
}

if (opt.argv.length > 0) {
  var specifiedPeripheral = opt.argv[0].replace(/:/g,'').toLowerCase();
}

var devicesPath=process.env.DEVICES_PATH;
var scanOrExplore = '';
var peripherals=[];
var saveAdvertisements=true;
var readValues=true;
var overWriteServices=false;

if (opt.options["no-advertisements"]) {
    console.log('Not saving advertisement discovery.');
    saveAdvertisements=false;
}

if (opt.options["no-read"]) {
    console.log('Not reading characteristic values.')
    readValues=false;
}

if (opt.options.overwrite) {
    console.log('Overwrite services file if exists.');
    overWriteServices=true;
}

function exploreSpecified(peripheralId) {

  checkFile(peripheralId, function(exists){
    if (!exists) {
        console.log('Start to explore ' + peripheralId)
        wsclient.explore(peripheralId, readValues);
    } else {
        console.log('Services file for ' + peripheralId + ' already saved, skipping. Use -o option to overwrite.');
    }
  })

}

//check if the services file exists
function checkFile(peripheralId, callback) {
  if (overWriteServices) {
    callback(false);
  } else {
    fs.stat(devicesPath + '/' + peripheralId + '.srv.json', function(err, stat) {
      if(err == null) {
        callback(true);
        //  console.log('File exists');
      } else {
        callback(false)
      }
    });
  }
}

wsclient.on('stateChange', function(state) {
  if (state === 'poweredOn') {
    if (specifiedPeripheral) {
      console.log('Start exploring ' + specifiedPeripheral);
      exploreSpecified(specifiedPeripheral)
    } else {
      console.log('Start scanning.');
      wsclient.startScanning();
    }
  } else if (state === 'unknown') {
    console.log('state unknown - waiting...')
  } else {
    wsclient.stopScanning();
  }
});

wsclient.on('discover', function(peripheralId, address, addressType, connectable, advertisement, rssi) {

        if (saveAdvertisements) {
          utils.saveAdvertisement(peripheralId, address, addressType, connectable, advertisement, rssi);
        }

        if (!peripherals[peripheralId]) {
          peripherals[peripheralId] = { explored: false, triedToExplore: false};
        }

})

wsclient.on('explore', function(peripheralId, state, servicesJson){

  console.log('explore state: ' + peripheralId + ' : ' + state);
  if(state === 'finished') {

    var filename = devicesPath+'/'+peripheralId+'.srv.json';

    fs.writeFile(filename, JSON.stringify(servicesJson, null, 4), function(err) {
        if(err) {
           return console.log(err);
        }
         console.log("Services file "+ filename +" saved!");
         if (peripheralId === specifiedPeripheral) {
            process.exit(0);
         }

    });
  }
})
<|endoftext|>


<commit_before>var calendarEvents = [];

var currentOptions = {};

var selectedCameras = null;

var calendarChannelOptions = {
	bookings: true,
	staffAbsences: true
};

function setupCalendar(selector, onSelect, viewOptions) {
	var cal = selector.show().fullCalendar({
		// basic appearance
		header: {
			left: 'prev,next today',
			center: 'title',
			right: ''
		},
		defaultView: 'agendaWeek',
		selectable: true,
		selectHelper: true,
		allDaySlot: false,
		timeFormat: 'HH:mm',
		weekends: true,
		slotMinutes: 15,

		// set data source
		events: calendarEvents,

		// TODO
		minTime: "08:00:00",
		maxTime: "19:00:00",

		// what to display?
		viewDisplay: function (e) {
			// clear bookings
			calendarEvents.length = 0;

			// reload for new date range
			updateCalendar(selector, e.start, e.end, viewOptions);

			// resize
			var v = this;
			e.setHeight($(window).height() - $(v).position().top - 60);
			setTimeout(function () {
				e.setHeight($(window).height() - $(v).position().top - 60);
			}, 500);
		},

		// on-select function
		select: onSelect,

		// pop-up with details
		eventRender: function (event, element) {
			element.addClass(event.type);

			element.popover({
				title: event.title,
				placement: 'auto',
				html: true,
				trigger: 'hover',
				animation: 'true',
				content: event.msg,
				container: 'body'
			});

			// click listener to hide
			$('body').on('click', function (e) {
				if (!element.is(e.target) && element.has(e.target).length === 0
					&& $('.popover').has(e.target).length === 0)
					element.popover('hide');
			});
		},

		eventClick: function (calEvent, jsEvent, view) {
			if (calEvent.url && viewOptions['linkEvents']) {
				window.location.href = calEvent.url;
			}
			return false;
		},

		windowResize: function (calView) {
			calView.setHeight($(window).height() - $(this).position().top - 60);
		}
	});

	// add loading icon and toggle buttons
	cal.find('.fc-header-right').html('' +
	'' +
	'' +
	'    ' +
	'Loading...' +
	'    ' +
	'' +
	'' +
	'<button class="btn btn-default calendar-channel-toggle" data-target="staffAbsences"> Absences</button>' +
	'  ' +
	'<button class="btn btn-default calendar-channel-toggle" data-target="genericEvents"> Events</button>' +
	'  ' +
	'<button class="btn btn-default calendar-channel-cameras"> Bookings</button>' +
	'');

	// perform action for toggle buttons
	$('.calendar-channel-toggle').click(function (e) {
		e.preventDefault();

		// get target
		var target = $(this).data('target');

		// switch button classes
		if (calendarChannelOptions[target]) {
			$(this).find('i').removeClass('fa-check-square-o').addClass('fa-square-o');
		} else {
			$(this).find('i').removeClass('fa-square-o').addClass('fa-check-square-o');
		}

		// change option
		calendarChannelOptions[target] = !calendarChannelOptions[target];

		// redraw
		calendarEvents.length = 0;
		updateCalendar(
			currentOptions['selector'],
			currentOptions['startDate'],
			currentOptions['endDate'],
			currentOptions['options']
		);

		// drop focus
		$(this).blur();
	});

	// perform action for camera selection buttons
	$('.calendar-channel-cameras').click(function (e) {
		e.preventDefault();
		openCameraSelectModal();
	});

	return cal;
}

function updateCalendar(selector, startDate, endDate, options) {
	// store current options
	currentOptions['selector'] = selector;
	currentOptions['startDate'] = startDate;
	currentOptions['endDate'] = endDate;
	currentOptions['options'] = options;

	// show loading message
	$('.calendar-loading-msg').show();
	$('.calendar-channel-filters').hide();

	// adjust end date backwards by one
	endDate = new Date(((endDate.getTime()) - 86400000));

	// get start/end strings to pass to calendar data route
	var startDateString = startDate.getFullYear()
		+ '-'
		+ (startDate.getMonth() < 10 ? '0' : '') + (startDate.getMonth() + 1)
		+ '-'
		+ ((startDate.getDate()) < 10 ? '0' : '') + (startDate.getDate());
	var endDateString = endDate.getFullYear()
		+ '-'
		+ (endDate.getMonth() < 10 ? '0' : '') + (endDate.getMonth() + 1)
		+ '-'
		+ ((endDate.getDate()) < 10 ? '0' : '') + (endDate.getDate());

	// build URL
	var url = '/calendar-data?start=' + startDateString + '&end=' + endDateString;
	for (var key in options) url += '&' + key + '=' + (options[key] === true ? '1' : options[key]);
	for (key in calendarChannelOptions) url += '&' + key + '=' + (calendarChannelOptions[key] === true ? '1' : calendarChannelOptions[key]);
	url += '&cameras=';
	if (selectedCameras == null) {
		// default to all
		url += 'all';
	} else {
		url += selectedCameras.join(',');
	}

	// send AJAX call
	$.get(url)
		.done(function (result) {
			var rawJson = result.toString();
			var parsedJson = JSON.parse(rawJson);

			// loop through bookings
			if (calendarChannelOptions['bookings'] && typeof(parsedJson.bookings) != "undefined") {
				var bookingTitle, bookingCameraType, bookingStart, bookingEnd;
				for (var i = 0; i < parsedJson.bookings.length; ++i) {
					for (var j = 0; j < parsedJson.bookings[i].bookingSections.length; ++j) {
						// build title
						bookingTitle = parsedJson.bookings[i].therapyName + ":\n" + parsedJson.bookings[i].patientName;

						// build camera type
						bookingCameraType = parsedJson.bookings[i].cameraName;

						// start and end time
						bookingStart = parsedJson.bookings[i].bookingSections[j].startTime + ":00";
						bookingStart = bookingStart.replace(" ", "T");
						bookingEnd = parsedJson.bookings[i].bookingSections[j].endTime + ":00";
						bookingEnd = bookingEnd.replace(" ", "T");

						// add event
						calendarEvents.push({
							title: bookingTitle,
							start: bookingStart,
							end: bookingEnd,
							msg: "" +
							"Start time: " + parsedJson.bookings[i].bookingSections[j].startTime.substring(10, 16) + ""
							+ "
" +
							"End time: " + parsedJson.bookings[i].bookingSections[j].endTime.substring(10, 16) + ""
							+ "
" + bookingCameraType,
							allDay: false,
							url: '/booking-details/' + parsedJson.bookings[i].id,
							type: 'booking booking-' + parsedJson.bookings[i].colourNumber
						});
					}
				}
			}

			// loop through absences
			if (calendarChannelOptions['staffAbsences'] && typeof(parsedJson.staffAbsences) != "undefined") {
				var absenceTitle, absenceStart, absenceEnd;
				for (i = 0; i < parsedJson.staffAbsences.length; ++i) {
					// build title
					absenceTitle = "Absent: " + parsedJson.staffAbsences[i].staffName;

					// start and end time
					absenceStart = parsedJson.staffAbsences[i].from + ":00";
					absenceStart = absenceStart.replace(" ", "T");
					absenceEnd = parsedJson.staffAbsences[i].to + ":00";
					absenceEnd = absenceEnd.replace(" ", "T");

					// add event
					calendarEvents.push({
						title: absenceTitle,
						start: absenceStart,
						end: absenceEnd,
						msg: "" +
						"Start time: " + parsedJson.staffAbsences[i].from.substring(10, 16) + "" +
						"
" +
						"End time: " + parsedJson.staffAbsences[i].to.substring(10, 16) + "",
						allDay: false,
						type: 'absence'
					});
				}
			}

			// update events
			selector.fullCalendar('refetchEvents');

			// hide loading message
			$('.calendar-loading-msg').hide();
			$('.calendar-channel-filters').removeClass('hide').show();
		})
		.fail(function (xhr, textStatus, errorThrown) {
			toastr.error("Failed to load calendar data.")
			$('.calendar-loading-msg').hide();
		}
	);
}

function openCameraSelectModal() {
	var modal = $('.camera-select-modal');

	modal.removeClass('hide').modal({
		backdrop: 'static',
		keyboard: false
	});

	$('.btn-update').unbind('click').click(function (e) {
		// get selected
		selectedCameras = $('.selected-cameras:checked').map(function () {
			return this.value;
		}).get();

		// redraw
		calendarEvents.length = 0;
		updateCalendar(
			currentOptions['selector'],
			currentOptions['startDate'],
			currentOptions['endDate'],
			currentOptions['options']
		);

		// close modal
		modal.modal('hide');
	});

	$('.btn-cancel').unbind('click').click(function (e) {
		modal.modal('hide');
	});
}<commit_msg>Changed button to "Camera Use"<commit_after>var calendarEvents = [];

var currentOptions = {};

var selectedCameras = null;

var calendarChannelOptions = {
	bookings: true,
	staffAbsences: true
};

function setupCalendar(selector, onSelect, viewOptions) {
	var cal = selector.show().fullCalendar({
		// basic appearance
		header: {
			left: 'prev,next today',
			center: 'title',
			right: ''
		},
		defaultView: 'agendaWeek',
		selectable: true,
		selectHelper: true,
		allDaySlot: false,
		timeFormat: 'HH:mm',
		weekends: true,
		slotMinutes: 15,

		// set data source
		events: calendarEvents,

		// TODO
		minTime: "08:00:00",
		maxTime: "19:00:00",

		// what to display?
		viewDisplay: function (e) {
			// clear bookings
			calendarEvents.length = 0;

			// reload for new date range
			updateCalendar(selector, e.start, e.end, viewOptions);

			// resize
			var v = this;
			e.setHeight($(window).height() - $(v).position().top - 60);
			setTimeout(function () {
				e.setHeight($(window).height() - $(v).position().top - 60);
			}, 500);
		},

		// on-select function
		select: onSelect,

		// pop-up with details
		eventRender: function (event, element) {
			element.addClass(event.type);

			element.popover({
				title: event.title,
				placement: 'auto',
				html: true,
				trigger: 'hover',
				animation: 'true',
				content: event.msg,
				container: 'body'
			});

			// click listener to hide
			$('body').on('click', function (e) {
				if (!element.is(e.target) && element.has(e.target).length === 0
					&& $('.popover').has(e.target).length === 0)
					element.popover('hide');
			});
		},

		eventClick: function (calEvent, jsEvent, view) {
			if (calEvent.url && viewOptions['linkEvents']) {
				window.location.href = calEvent.url;
			}
			return false;
		},

		windowResize: function (calView) {
			calView.setHeight($(window).height() - $(this).position().top - 60);
		}
	});

	// add loading icon and toggle buttons
	cal.find('.fc-header-right').html('' +
	'' +
	'' +
	'    ' +
	'Loading...' +
	'    ' +
	'' +
	'' +
	'<button class="btn btn-default calendar-channel-toggle" data-target="staffAbsences"> Absences</button>' +
	'  ' +
	'<button class="btn btn-default calendar-channel-toggle" data-target="genericEvents"> Events</button>' +
	'  ' +
	'<button class="btn btn-default calendar-channel-cameras"> Camera Use</button>' +
	'');

	// perform action for toggle buttons
	$('.calendar-channel-toggle').click(function (e) {
		e.preventDefault();

		// get target
		var target = $(this).data('target');

		// switch button classes
		if (calendarChannelOptions[target]) {
			$(this).find('i').removeClass('fa-check-square-o').addClass('fa-square-o');
		} else {
			$(this).find('i').removeClass('fa-square-o').addClass('fa-check-square-o');
		}

		// change option
		calendarChannelOptions[target] = !calendarChannelOptions[target];

		// redraw
		calendarEvents.length = 0;
		updateCalendar(
			currentOptions['selector'],
			currentOptions['startDate'],
			currentOptions['endDate'],
			currentOptions['options']
		);

		// drop focus
		$(this).blur();
	});

	// perform action for camera selection buttons
	$('.calendar-channel-cameras').click(function (e) {
		e.preventDefault();
		openCameraSelectModal();
	});

	return cal;
}

function updateCalendar(selector, startDate, endDate, options) {
	// store current options
	currentOptions['selector'] = selector;
	currentOptions['startDate'] = startDate;
	currentOptions['endDate'] = endDate;
	currentOptions['options'] = options;

	// show loading message
	$('.calendar-loading-msg').show();
	$('.calendar-channel-filters').hide();

	// adjust end date backwards by one
	endDate = new Date(((endDate.getTime()) - 86400000));

	// get start/end strings to pass to calendar data route
	var startDateString = startDate.getFullYear()
		+ '-'
		+ (startDate.getMonth() < 10 ? '0' : '') + (startDate.getMonth() + 1)
		+ '-'
		+ ((startDate.getDate()) < 10 ? '0' : '') + (startDate.getDate());
	var endDateString = endDate.getFullYear()
		+ '-'
		+ (endDate.getMonth() < 10 ? '0' : '') + (endDate.getMonth() + 1)
		+ '-'
		+ ((endDate.getDate()) < 10 ? '0' : '') + (endDate.getDate());

	// build URL
	var url = '/calendar-data?start=' + startDateString + '&end=' + endDateString;
	for (var key in options) url += '&' + key + '=' + (options[key] === true ? '1' : options[key]);
	for (key in calendarChannelOptions) url += '&' + key + '=' + (calendarChannelOptions[key] === true ? '1' : calendarChannelOptions[key]);
	url += '&cameras=';
	if (selectedCameras == null) {
		// default to all
		url += 'all';
	} else {
		url += selectedCameras.join(',');
	}

	// send AJAX call
	$.get(url)
		.done(function (result) {
			var rawJson = result.toString();
			var parsedJson = JSON.parse(rawJson);

			// loop through bookings
			if (calendarChannelOptions['bookings'] && typeof(parsedJson.bookings) != "undefined") {
				var bookingTitle, bookingCameraType, bookingStart, bookingEnd;
				for (var i = 0; i < parsedJson.bookings.length; ++i) {
					for (var j = 0; j < parsedJson.bookings[i].bookingSections.length; ++j) {
						// build title
						bookingTitle = parsedJson.bookings[i].therapyName + ":\n" + parsedJson.bookings[i].patientName;

						// build camera type
						bookingCameraType = parsedJson.bookings[i].cameraName;

						// start and end time
						bookingStart = parsedJson.bookings[i].bookingSections[j].startTime + ":00";
						bookingStart = bookingStart.replace(" ", "T");
						bookingEnd = parsedJson.bookings[i].bookingSections[j].endTime + ":00";
						bookingEnd = bookingEnd.replace(" ", "T");

						// add event
						calendarEvents.push({
							title: bookingTitle,
							start: bookingStart,
							end: bookingEnd,
							msg: "" +
							"Start time: " + parsedJson.bookings[i].bookingSections[j].startTime.substring(10, 16) + ""
							+ "
" +
							"End time: " + parsedJson.bookings[i].bookingSections[j].endTime.substring(10, 16) + ""
							+ "
" + bookingCameraType,
							allDay: false,
							url: '/booking-details/' + parsedJson.bookings[i].id,
							type: 'booking booking-' + parsedJson.bookings[i].colourNumber
						});
					}
				}
			}

			// loop through absences
			if (calendarChannelOptions['staffAbsences'] && typeof(parsedJson.staffAbsences) != "undefined") {
				var absenceTitle, absenceStart, absenceEnd;
				for (i = 0; i < parsedJson.staffAbsences.length; ++i) {
					// build title
					absenceTitle = "Absent: " + parsedJson.staffAbsences[i].staffName;

					// start and end time
					absenceStart = parsedJson.staffAbsences[i].from + ":00";
					absenceStart = absenceStart.replace(" ", "T");
					absenceEnd = parsedJson.staffAbsences[i].to + ":00";
					absenceEnd = absenceEnd.replace(" ", "T");

					// add event
					calendarEvents.push({
						title: absenceTitle,
						start: absenceStart,
						end: absenceEnd,
						msg: "" +
						"Start time: " + parsedJson.staffAbsences[i].from.substring(10, 16) + "" +
						"
" +
						"End time: " + parsedJson.staffAbsences[i].to.substring(10, 16) + "",
						allDay: false,
						type: 'absence'
					});
				}
			}

			// update events
			selector.fullCalendar('refetchEvents');

			// hide loading message
			$('.calendar-loading-msg').hide();
			$('.calendar-channel-filters').removeClass('hide').show();
		})
		.fail(function (xhr, textStatus, errorThrown) {
			toastr.error("Failed to load calendar data.")
			$('.calendar-loading-msg').hide();
		}
	);
}

function openCameraSelectModal() {
	var modal = $('.camera-select-modal');

	modal.removeClass('hide').modal({
		backdrop: 'static',
		keyboard: false
	});

	$('.btn-update').unbind('click').click(function (e) {
		// get selected
		selectedCameras = $('.selected-cameras:checked').map(function () {
			return this.value;
		}).get();

		// redraw
		calendarEvents.length = 0;
		updateCalendar(
			currentOptions['selector'],
			currentOptions['startDate'],
			currentOptions['endDate'],
			currentOptions['options']
		);

		// close modal
		modal.modal('hide');
	});

	$('.btn-cancel').unbind('click').click(function (e) {
		modal.modal('hide');
	});
}<|endoftext|>


<commit_before>var page = require('webpage').create(),
	server = 'http://exam.cusat.ac.in/erp5/cusat/Cusat-Hall-Ticket',
	data = 'regno1=12130024&deg_name=B.Tech&semister=8&month=September&year=2016&reg_type=Supply/Improvement&checktype=check';

page.onError = function(msg, trace) {
  var msgStack = ['PHANTOM ERROR: ' + msg];
  if (trace && trace.length) {
    msgStack.push('TRACE:');
    trace.forEach(function(t) {
      msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
    });
  }
  console.error(msgStack.join('\n'));
  phantom.exit(1);
};
page.open(server, 'post', data, function(status) {
	console.log("Status: " + status);
	if(status === "success") {
	}
	page.render('example.pdf');
	phantom.exit();
});
<commit_msg>Server<commit_after>var page = require('webpage').create(),
	server = 'http://exam.cusat.ac.in/erp5/cusat/Cusat-Hall-Ticket',
	data = 'regno1=12130024&deg_name=B.Tech&semister=8&month=September&year=2016&reg_type=Supply/Improvement&checktype=check';
page.onResourceRequested = function (request) {
    system.stderr.writeLine('= onResourceRequested()');
    system.stderr.writeLine('  request: ' + JSON.stringify(request, undefined, 4));
};

page.onResourceReceived = function(response) {
    system.stderr.writeLine('= onResourceReceived()' );
    system.stderr.writeLine('  id: ' + response.id + ', stage: "' + response.stage + '", response: ' + JSON.stringify(response));
};

page.onLoadStarted = function() {
    system.stderr.writeLine('= onLoadStarted()');
    var currentUrl = page.evaluate(function() {
        return window.location.href;
    });
    system.stderr.writeLine('  leaving url: ' + currentUrl);
};

page.onLoadFinished = function(status) {
    system.stderr.writeLine('= onLoadFinished()');
    system.stderr.writeLine('  status: ' + status);
};

page.onNavigationRequested = function(url, type, willNavigate, main) {
    system.stderr.writeLine('= onNavigationRequested');
    system.stderr.writeLine('  destination_url: ' + url);
    system.stderr.writeLine('  type (cause): ' + type);
    system.stderr.writeLine('  will navigate: ' + willNavigate);
    system.stderr.writeLine('  from page\'s main frame: ' + main);
};

page.onResourceError = function(resourceError) {
    system.stderr.writeLine('= onResourceError()');
    system.stderr.writeLine('  - unable to load url: "' + resourceError.url + '"');
    system.stderr.writeLine('  - error code: ' + resourceError.errorCode + ', description: ' + resourceError.errorString );
};

page.onError = function(msg, trace) {
    system.stderr.writeLine('= onError()');
    var msgStack = ['  ERROR: ' + msg];
    if (trace) {
        msgStack.push('  TRACE:');
        trace.forEach(function(t) {
            msgStack.push('    -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
        });
    }
    system.stderr.writeLine(msgStack.join('\n'));
};
page.open(server, 'post', data, function(status) {
	console.log("Status: " + status);
	if(status === "success") {
	}
	page.render('example.pdf');
	phantom.exit();
});
<|endoftext|>


<commit_before>/**
 * @providesModule YouTube
 * @flow
 */

'use strict';

import React, { Component, PropTypes } from 'react';
import ReactNative, {
  View,
  StyleSheet,
  requireNativeComponent,
  NativeModules,
  NativeMethodsMixin
} from 'react-native';

const RCTYouTube = requireNativeComponent('ReactYouTube', YouTube,
{
  nativeOnly: {onError:true,
              onReady:true,
              onChangeState:true,
              onChangeQuality:true
              }
});

export default class YouTube extends Component {
  static propTypes = {
    style: View.propTypes.style,
    videoId: PropTypes.string.isRequired,
    apiKey: PropTypes.string.isRequired,
    playsInline: PropTypes.bool,
    showinfo: PropTypes.bool,
    modestbranding: PropTypes.bool,
    controls: PropTypes.oneOf([0,1,2]),
    origin: PropTypes.string,
    play: PropTypes.bool,
    rel: PropTypes.bool,
    hidden: PropTypes.bool,
    onReady: PropTypes.func,
    onChangeState: PropTypes.func,
    onChangeQuality: PropTypes.func,
    onError: PropTypes.func,
    loop: PropTypes.bool,
  };

  static defaultProps = {
    loop: false
  };

  constructor(props) {
    super(props);
    this._exportedProps = NativeModules.YouTubeManager && NativeModules.YouTubeManager.exportedProps;
  }

  _onReady(event) {
    console.log('ok ready');
    return this.props.onReady && this.props.onReady(event.nativeEvent);
  }

  _onChangeState(event) {
    if(event.nativeEvent.state == 'ended' && this.props.loop) {
      this.seekTo(0);
    }
    return this.props.onChangeState && this.props.onChangeState(event.nativeEvent);
  }

  _onChangeQuality(event) {
    return this.props.onChangeQuality && this.props.onChangeQuality(event.nativeEvent);
  }

  _onError(event) {
    console.log('ok error');
    return this.props.onError && this.props.onError(event.nativeEvent);
  }
  _onProgress(event){
      return this.props.onProgress && this.props.onProgress(event.nativeEvent);
  }
  seekTo(seconds){
    console.log("seconds : " + seconds);
    NativeModules.YouTubeModule.seekTo(parseInt(seconds, 10));
    //this.refs.youtubePlayer.seekTo(ReactNative.findNodeHandle(this), parseInt(seconds, 10));
  }

  render() {
    var style = [styles.base, this.props.style];
    var nativeProps = Object.assign({}, this.props);
    nativeProps.style = style;
    nativeProps.onYoutubeVideoReady = this._onReady.bind(this);
    nativeProps.onYoutubeVideoChangeState = this._onChangeState.bind(this);
    nativeProps.onYoutubeVideoChangeQuality = this._onChangeQuality.bind(this);
    nativeProps.onYoutubeVideoError = this._onError.bind(this);
    nativeProps.onYoutubeProgress = this._onProgress.bind(this);

    /*
     * Try to use `playerParams` instead of settings `playsInline` and
     * `videoId` individually.
     */
    if (this._exportedProps) {
      if (this._exportedProps.playerParams) {
        nativeProps.playerParams = {
          videoId: this.props.videoId,
        };
        delete nativeProps.videoId;

        nativeProps.playerParams.playerVars = {};

        if (this.props.playsInline) {
          nativeProps.playerParams.playerVars.playsinline = 1;
          delete nativeProps.playsInline;
        };
        if (this.props.modestbranding) {
          nativeProps.playerParams.playerVars.modestbranding = 1;
          delete nativeProps.modestbranding;
        };

        if (this.props.showinfo!==undefined) {
          nativeProps.playerParams.playerVars.showinfo = this.props.showinfo ? 1 : 0;
          delete nativeProps.showinfo;
        };
        if (this.props.controls!==undefined) {
          nativeProps.playerParams.playerVars.controls = this.props.controls;
          delete nativeProps.controls;
        };
        if (this.props.origin!==undefined) {
          nativeProps.playerParams.playerVars.origin = this.props.origin;
          delete nativeProps.origin;
        };
        if (this.props.rel!==undefined) {
          nativeProps.playerParams.playerVars.rel = this.props.rel ? 1 : 0;
          delete nativeProps.rel;
        };
      };
    } else {
      /*
       * For compatibility issues with an older version where setting both
       * `playsInline` and `videoId` in quick succession would cause the video
       * to sometimes not play.
       */
      delete nativeProps.playsInline;
    }

    return <RCTYouTube {... nativeProps} />;
  }
}

const styles = StyleSheet.create({
  base: {
    overflow: 'hidden',
  },
});
<commit_msg>some logs removed<commit_after>/**
 * @providesModule YouTube
 * @flow
 */

'use strict';

import React, { Component, PropTypes } from 'react';
import ReactNative, {
  View,
  StyleSheet,
  requireNativeComponent,
  NativeModules,
  NativeMethodsMixin
} from 'react-native';

const RCTYouTube = requireNativeComponent('ReactYouTube', YouTube,
{
  nativeOnly: {onError:true,
              onReady:true,
              onChangeState:true,
              onChangeQuality:true
              }
});

export default class YouTube extends Component {
  static propTypes = {
    style: View.propTypes.style,
    videoId: PropTypes.string.isRequired,
    apiKey: PropTypes.string.isRequired,
    playsInline: PropTypes.bool,
    showinfo: PropTypes.bool,
    modestbranding: PropTypes.bool,
    controls: PropTypes.oneOf([0,1,2]),
    origin: PropTypes.string,
    play: PropTypes.bool,
    rel: PropTypes.bool,
    hidden: PropTypes.bool,
    onReady: PropTypes.func,
    onChangeState: PropTypes.func,
    onChangeQuality: PropTypes.func,
    onError: PropTypes.func,
    loop: PropTypes.bool,
  };

  static defaultProps = {
    loop: false
  };

  constructor(props) {
    super(props);
    this._exportedProps = NativeModules.YouTubeManager && NativeModules.YouTubeManager.exportedProps;
  }

  _onReady(event) {
    return this.props.onReady && this.props.onReady(event.nativeEvent);
  }

  _onChangeState(event) {
    if(event.nativeEvent.state == 'ended' && this.props.loop) {
      this.seekTo(0);
    }
    return this.props.onChangeState && this.props.onChangeState(event.nativeEvent);
  }

  _onChangeQuality(event) {
    return this.props.onChangeQuality && this.props.onChangeQuality(event.nativeEvent);
  }

  _onError(event) {
    return this.props.onError && this.props.onError(event.nativeEvent);
  }
  _onProgress(event){
      return this.props.onProgress && this.props.onProgress(event.nativeEvent);
  }
  seekTo(seconds){
    NativeModules.YouTubeModule.seekTo(parseInt(seconds, 10));
    //this.refs.youtubePlayer.seekTo(ReactNative.findNodeHandle(this), parseInt(seconds, 10));
  }

  render() {
    var style = [styles.base, this.props.style];
    var nativeProps = Object.assign({}, this.props);
    nativeProps.style = style;
    nativeProps.onYoutubeVideoReady = this._onReady.bind(this);
    nativeProps.onYoutubeVideoChangeState = this._onChangeState.bind(this);
    nativeProps.onYoutubeVideoChangeQuality = this._onChangeQuality.bind(this);
    nativeProps.onYoutubeVideoError = this._onError.bind(this);
    nativeProps.onYoutubeProgress = this._onProgress.bind(this);

    /*
     * Try to use `playerParams` instead of settings `playsInline` and
     * `videoId` individually.
     */
    if (this._exportedProps) {
      if (this._exportedProps.playerParams) {
        nativeProps.playerParams = {
          videoId: this.props.videoId,
        };
        delete nativeProps.videoId;

        nativeProps.playerParams.playerVars = {};

        if (this.props.playsInline) {
          nativeProps.playerParams.playerVars.playsinline = 1;
          delete nativeProps.playsInline;
        };
        if (this.props.modestbranding) {
          nativeProps.playerParams.playerVars.modestbranding = 1;
          delete nativeProps.modestbranding;
        };

        if (this.props.showinfo!==undefined) {
          nativeProps.playerParams.playerVars.showinfo = this.props.showinfo ? 1 : 0;
          delete nativeProps.showinfo;
        };
        if (this.props.controls!==undefined) {
          nativeProps.playerParams.playerVars.controls = this.props.controls;
          delete nativeProps.controls;
        };
        if (this.props.origin!==undefined) {
          nativeProps.playerParams.playerVars.origin = this.props.origin;
          delete nativeProps.origin;
        };
        if (this.props.rel!==undefined) {
          nativeProps.playerParams.playerVars.rel = this.props.rel ? 1 : 0;
          delete nativeProps.rel;
        };
      };
    } else {
      /*
       * For compatibility issues with an older version where setting both
       * `playsInline` and `videoId` in quick succession would cause the video
       * to sometimes not play.
       */
      delete nativeProps.playsInline;
    }

    return <RCTYouTube {... nativeProps} />;
  }
}

const styles = StyleSheet.create({
  base: {
    overflow: 'hidden',
  },
});
<|endoftext|>


<commit_before>// Copyright (C) 2014 Makoto Mizukami

(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (requestListener !== undefined) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);
	Server.prototype.timeout = DEFAULTS.timeout;
	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (socket) {
		EE.call(this);

		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);
	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
		};

		EE.call(this);

		this.socket = socket;

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);
	ServerResponse.prototype.headerFinalized = false;
	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};
	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}
		headerInfo.fieldQueue.push(fieldName);
	};
	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		var socket = this.socket;

		if (socket.writable !== true || this.headerFinalized === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				socket.write(headerInfo.fields[field] + CRLF);
			});
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			socket.write(CRLF);
			this.headerFinalized = true;
		}
	};
	ServerResponse.prototype.write = function (data) {
		if (this.socket.writable !== true) {
			return;
		}

		this.headerFinalized !== true && this.flushHeaders(true);
		this.socket.write(data);
	};
	ServerResponse.prototype.end = function (data) {
		data !== undefined && this.write(data);

		if (this.socket._writableState.writing === false) {
			this.socket.end();
		} else {
			this.socket.once("drain", this.socket.end);
		}
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			reqDraft : {},
			req : new ClientRequest(socket),
			res : new ServerResponse(socket),
			clientPhase : 0
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		var reqDraft = this.reqDraft,
		i = 0, dataChar = "";

		if (this.clientPhase === 0) {	// Beginning
			if (reqDraft.headerLengthStr === undefined) {
				reqDraft.headerLengthStr = "";
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (isNaN(parseInt(dataChar, 10))) {
					if (dataChar !== ":" || reqDraft.headerLengthStr.length < 1) {
						this.server.emit("clientError", new Error("Malformed netstring of headers"), this.socket);
						return;
					} else {
						reqDraft.headerLength = parseInt(reqDraft.headerLengthStr, 10);
						this.clientPhase += 1;
						i += 1;
						break;
					}
				}

				reqDraft.headerLengthStr += dataChar;
			}
		}

		if (this.clientPhase === 1) {	// Midst header
			if (reqDraft.parsedHeaderLength === undefined) {
				reqDraft.parsedHeaderLength = 0;
				reqDraft.headerState = 0;
				reqDraft.headerParserStack = ["", ""];
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (reqDraft.parsedHeaderLength === reqDraft.headerLength) {
					if (dataChar !== ",") {
						this.server.emit("clientError", new Error("Header section is longer than declared"), this.socket);
					}

					this.clientPhase += 1;
					this.server.emit("request", this.req, this.res);

					reqDraft.bodyLength = parseInt(this.req.params.CONTENT_LENGTH, 10);
					process.nextTick(onClientData.bind(this, data.slice(i + 1)));

					return;
				}

				reqDraft.parsedHeaderLength += 1;

				if (dataChar === "\u0000") {
					if (reqDraft.headerState === 1) {
						this.req.params[reqDraft.headerParserStack[0]] = reqDraft.headerParserStack[1];
						reqDraft.headerParserStack = ["", ""];
					}

					reqDraft.headerState ^= 1;
					continue;
				}

				reqDraft.headerParserStack[reqDraft.headerState] += dataChar;
			}
		}

		if (this.clientPhase === 2) {
			if (reqDraft.bodyReceivedLength === undefined) {
				reqDraft.bodyReceivedLength = 0;
			}

			reqDraft.bodyReceivedLength += data.length;

			if (reqDraft.bodyReceivedLength > reqDraft.bodyLength) {
				this.server.emit("clientError", new Error("Body is larger than declared"), this.socket);
				return;
			}

			this.req.emit("data", data);

			if (reqDraft.bodyReceivedLength === reqDraft.bodyLength) {
				reqDraft.clientPhase += 1;
				this.req.emit("end");
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		if (this.clientPhase < 2) {
			this.server.emit("clientError", new Error("Client FIN before request completes"), this.socket);
		}
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		this.socket.removeAllListeners();

		this.req.emit("close");
		this.res.emit((hadError === false && this.socket._writableState.ended === true) ? "finish" : "close");
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.socket);

		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<commit_msg>[scgi] Improved type check for event listener attachment<commit_after>// Copyright (C) 2014 Makoto Mizukami

(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (typeof requestListener === typeof Function) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);
	Server.prototype.timeout = DEFAULTS.timeout;
	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (socket) {
		EE.call(this);

		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);
	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
		};

		EE.call(this);

		this.socket = socket;

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);
	ServerResponse.prototype.headerFinalized = false;
	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};
	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}
		headerInfo.fieldQueue.push(fieldName);
	};
	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		var socket = this.socket;

		if (socket.writable !== true || this.headerFinalized === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				socket.write(headerInfo.fields[field] + CRLF);
			});
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			socket.write(CRLF);
			this.headerFinalized = true;
		}
	};
	ServerResponse.prototype.write = function (data) {
		if (this.socket.writable !== true) {
			return;
		}

		this.headerFinalized !== true && this.flushHeaders(true);
		this.socket.write(data);
	};
	ServerResponse.prototype.end = function (data) {
		data !== undefined && this.write(data);

		if (this.socket._writableState.writing === false) {
			this.socket.end();
		} else {
			this.socket.once("drain", this.socket.end);
		}
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			reqDraft : {},
			req : new ClientRequest(socket),
			res : new ServerResponse(socket),
			clientPhase : 0
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		var reqDraft = this.reqDraft,
		i = 0, dataChar = "";

		if (this.clientPhase === 0) {	// Beginning
			if (reqDraft.headerLengthStr === undefined) {
				reqDraft.headerLengthStr = "";
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (isNaN(parseInt(dataChar, 10))) {
					if (dataChar !== ":" || reqDraft.headerLengthStr.length < 1) {
						this.server.emit("clientError", new Error("Malformed netstring of headers"), this.socket);
						return;
					} else {
						reqDraft.headerLength = parseInt(reqDraft.headerLengthStr, 10);
						this.clientPhase += 1;
						i += 1;
						break;
					}
				}

				reqDraft.headerLengthStr += dataChar;
			}
		}

		if (this.clientPhase === 1) {	// Midst header
			if (reqDraft.parsedHeaderLength === undefined) {
				reqDraft.parsedHeaderLength = 0;
				reqDraft.headerState = 0;
				reqDraft.headerParserStack = ["", ""];
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (reqDraft.parsedHeaderLength === reqDraft.headerLength) {
					if (dataChar !== ",") {
						this.server.emit("clientError", new Error("Header section is longer than declared"), this.socket);
					}

					this.clientPhase += 1;
					this.server.emit("request", this.req, this.res);

					reqDraft.bodyLength = parseInt(this.req.params.CONTENT_LENGTH, 10);
					process.nextTick(onClientData.bind(this, data.slice(i + 1)));

					return;
				}

				reqDraft.parsedHeaderLength += 1;

				if (dataChar === "\u0000") {
					if (reqDraft.headerState === 1) {
						this.req.params[reqDraft.headerParserStack[0]] = reqDraft.headerParserStack[1];
						reqDraft.headerParserStack = ["", ""];
					}

					reqDraft.headerState ^= 1;
					continue;
				}

				reqDraft.headerParserStack[reqDraft.headerState] += dataChar;
			}
		}

		if (this.clientPhase === 2) {
			if (reqDraft.bodyReceivedLength === undefined) {
				reqDraft.bodyReceivedLength = 0;
			}

			reqDraft.bodyReceivedLength += data.length;

			if (reqDraft.bodyReceivedLength > reqDraft.bodyLength) {
				this.server.emit("clientError", new Error("Body is larger than declared"), this.socket);
				return;
			}

			this.req.emit("data", data);

			if (reqDraft.bodyReceivedLength === reqDraft.bodyLength) {
				reqDraft.clientPhase += 1;
				this.req.emit("end");
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		if (this.clientPhase < 2) {
			this.server.emit("clientError", new Error("Client FIN before request completes"), this.socket);
		}
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		this.socket.removeAllListeners();

		this.req.emit("close");
		this.res.emit((hadError === false && this.socket._writableState.ended === true) ? "finish" : "close");
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.socket);

		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<|endoftext|>


<commit_before>(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (requestListener !== undefined) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);
	Server.prototype.timeout = DEFAULTS.timeout;
	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (socket) {
		EE.call(this);

		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);
	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
			inBody : false
		};

		EE.call(this);

		this.socket = socket;

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);
	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};
	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}
		headerInfo.fieldQueue.push(fieldName);
	};
	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		var socket = this.socket;

		if (socket.writable !== true || headerInfo.inBody === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				socket.write(headerInfo.fields[field] + CRLF);
			});
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			socket.write(CRLF);
			headerInfo.inBody = true;
		}
	};
	ServerResponse.prototype.write = function (data) {
		if (this.socket.writable !== true) {
			return;
		}

		this.flushHeaders(true);
		this.socket.write(data);
	};
	ServerResponse.prototype.end = function () {
		if (this.socket._writableState.writing === false) {
			this.socket.end();
		} else {
			this.socket.once("drain", this.socket.end);
		}
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			reqDraft : {},
			req : new ClientRequest(socket),
			res : new ServerResponse(socket),
			clientPhase : 0
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		var reqDraft = this.reqDraft,
		i = 0, dataChar = "";

		if (this.clientPhase === 0) {	// Beginning
			if (reqDraft.headerLengthStr === undefined) {
				reqDraft.headerLengthStr = "";
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (isNaN(parseInt(dataChar, 10))) {
					if (dataChar !== ":" || reqDraft.headerLengthStr.length < 1) {
						this.server.emit("clientError", new Error("Malformed netstring of headers"), this.socket);
						return;
					} else {
						reqDraft.headerLength = parseInt(reqDraft.headerLengthStr, 10);
						this.clientPhase += 1;
						i += 1;
						break;
					}
				}

				reqDraft.headerLengthStr += dataChar;
			}
		}

		if (this.clientPhase === 1) {	// Midst header
			if (reqDraft.parsedHeaderLength === undefined) {
				reqDraft.parsedHeaderLength = 0;
				reqDraft.headerState = 0;
				reqDraft.headerParserStack = ["", ""];
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (reqDraft.parsedHeaderLength === reqDraft.headerLength) {
					if (dataChar !== ",") {
						this.server.emit("clientError", new Error("Header section is longer than declared"), this.socket);
					}

					this.clientPhase += 1;
					this.server.emit("request", this.req, this.res);

					reqDraft.bodyLength = parseInt(this.req.params.CONTENT_LENGTH, 10);
					process.nextTick(onClientData.bind(this, data.slice(i + 1)));

					return;
				}

				reqDraft.parsedHeaderLength += 1;

				if (dataChar === "\u0000") {
					if (reqDraft.headerState === 1) {
						this.req.params[reqDraft.headerParserStack[0]] = reqDraft.headerParserStack[1];
						reqDraft.headerParserStack = ["", ""];
					}

					reqDraft.headerState ^= 1;
					continue;
				}

				reqDraft.headerParserStack[reqDraft.headerState] += dataChar;
			}
		}

		if (this.clientPhase === 2) {
			if (reqDraft.bodyReceivedLength === undefined) {
				reqDraft.bodyReceivedLength = 0;
			}

			reqDraft.bodyReceivedLength += data.length;

			if (reqDraft.bodyReceivedLength > reqDraft.bodyLength) {
				this.server.emit("clientError", new Error("Body is larger than declared"), this.socket);
				return;
			}

			this.req.emit("data", data);

			if (reqDraft.bodyReceivedLength === reqDraft.bodyLength) {
				reqDraft.clientPhase += 1;
				this.req.emit("end");
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		if (this.clientPhase < 2) {
			this.server.emit("clientError", new Error("Client FIN before request completes"), this.socket);
		}
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		this.socket.removeAllListeners();

		this.req.emit("close");
		this.res.emit((hadError === false && this.socket._writableState.ended === true) ? "finish" : "close");
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.req);
		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<commit_msg>[scgi] Socket timeout events now throw sockets themselves to Server<commit_after>(function () {
	"use strict";

	var DEFAULTS = {
		timeout : 180 * 1000	// Unit: second
	},

	// Classes
	Server, ClientRequest, ServerResponse,
	// Methods
	createServer,
	// Internal functions
	defaultStatusPhrase, onConnection, onClientData, onClientError, onClientFin, onSocketError, onSocketClose, onSocketTimeout,
	// Internal values
	CRLF = "\r\n", wellknownStatuses = require("./http_status.js").IANAStatuses,

	EE = require("events").EventEmitter, net = require("net"), util = require("util");

	Server = function (requestListener) {
		net.Server.call(this, { allowHalfOpen : true });

		if (requestListener !== undefined) {
			this.on("request", requestListener);
		}

		this.on("connection", onConnection);
		this.on("clientError", onClientError);
	};
	util.inherits(Server, net.Server);
	Server.prototype.timeout = DEFAULTS.timeout;
	Server.prototype.setTimeout = function (timeoutAfter, callback) {
		this.timeout = timeoutAfter;

		if (callback !== undefined) {
			this.on("timeout", callback);
		}
	};

	ClientRequest = function (socket) {
		EE.call(this);

		this.socket = socket;
		this.params = {};

		this.on("close", this.removeAllListeners);
	};
	util.inherits(ClientRequest, EE);
	ClientRequest.prototype.setTimeout = function (timeoutAfter, callback) {
		this.socket.setTimeout(timeoutAfter);

		if (callback !== undefined) {
			this.socket.on("timeout", callback);
		}
	};

	ServerResponse = function (socket) {
		var headerInfo = {
			fields : {},
			fieldQueue : [],
			inBody : false
		};

		EE.call(this);

		this.socket = socket;

		this.setHeader = ServerResponse.prototype.setHeader.bind(this, headerInfo);
		this.flushHeaders = ServerResponse.prototype.flushHeaders.bind(this, headerInfo);

		this.setStatus(200);

		this.on("close", this.removeAllListeners);
		this.on("finish", this.removeAllListeners);
	};
	util.inherits(ServerResponse, EE);
	ServerResponse.prototype.setStatus = function (sCode, reasonPhrase) {
		this.setHeader(["Status:", sCode.toString(), reasonPhrase !== undefined ? reasonPhrase : defaultStatusPhrase(sCode)].join(" "));
	};
	ServerResponse.prototype.setHeader = function (headerInfo, headerStatement) {
		var fieldName = headerStatement.split(":").shift().toLowerCase(),
		queued = headerInfo.fieldQueue.indexOf(fieldName);

		if (headerInfo.fields[fieldName] !== undefined && queued === -1) {
			return;
		}

		headerInfo.fields[fieldName] = headerStatement.trim();

		if (queued >= 0) {
			headerInfo.fieldQueue.splice(queued, 1);
		}
		headerInfo.fieldQueue.push(fieldName);
	};
	ServerResponse.prototype.flushHeaders = function (headerInfo, finalizeHeader) {
		var socket = this.socket;

		if (socket.writable !== true || headerInfo.inBody === true) {
			return;
		}

		if (headerInfo.fieldQueue.length > 0) {
			headerInfo.fieldQueue.forEach(function (field) {
				socket.write(headerInfo.fields[field] + CRLF);
			});
		}
		headerInfo.fieldQueue = [];

		if (finalizeHeader === true) {
			socket.write(CRLF);
			headerInfo.inBody = true;
		}
	};
	ServerResponse.prototype.write = function (data) {
		if (this.socket.writable !== true) {
			return;
		}

		this.flushHeaders(true);
		this.socket.write(data);
	};
	ServerResponse.prototype.end = function () {
		if (this.socket._writableState.writing === false) {
			this.socket.end();
		} else {
			this.socket.once("drain", this.socket.end);
		}
	};

	defaultStatusPhrase = function (sCode) {
		return wellknownStatuses[sCode] !== undefined ? wellknownStatuses[sCode] : [sCode.toString(), "Unknown Reason"].join(" ");
	};

	createServer = function (requestListener) {
		return new Server(requestListener);
	};

	onConnection = function (socket) {
		var connection = {
			server : this,
			socket : socket,
			reqDraft : {},
			req : new ClientRequest(socket),
			res : new ServerResponse(socket),
			clientPhase : 0
		};

		socket.setTimeout(this.timeout);

		socket.on("data", onClientData.bind(connection));
		socket.on("error", onSocketError.bind(connection));
		socket.on("end", onClientFin.bind(connection));
		socket.on("close", onSocketClose.bind(connection));
		socket.on("timeout", onSocketTimeout.bind(connection));
	};

	onClientData = function (data) {
		var reqDraft = this.reqDraft,
		i = 0, dataChar = "";

		if (this.clientPhase === 0) {	// Beginning
			if (reqDraft.headerLengthStr === undefined) {
				reqDraft.headerLengthStr = "";
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (isNaN(parseInt(dataChar, 10))) {
					if (dataChar !== ":" || reqDraft.headerLengthStr.length < 1) {
						this.server.emit("clientError", new Error("Malformed netstring of headers"), this.socket);
						return;
					} else {
						reqDraft.headerLength = parseInt(reqDraft.headerLengthStr, 10);
						this.clientPhase += 1;
						i += 1;
						break;
					}
				}

				reqDraft.headerLengthStr += dataChar;
			}
		}

		if (this.clientPhase === 1) {	// Midst header
			if (reqDraft.parsedHeaderLength === undefined) {
				reqDraft.parsedHeaderLength = 0;
				reqDraft.headerState = 0;
				reqDraft.headerParserStack = ["", ""];
			}

			for (; i < data.length; i += 1) {
				dataChar = String.fromCharCode(data[i]);

				if (reqDraft.parsedHeaderLength === reqDraft.headerLength) {
					if (dataChar !== ",") {
						this.server.emit("clientError", new Error("Header section is longer than declared"), this.socket);
					}

					this.clientPhase += 1;
					this.server.emit("request", this.req, this.res);

					reqDraft.bodyLength = parseInt(this.req.params.CONTENT_LENGTH, 10);
					process.nextTick(onClientData.bind(this, data.slice(i + 1)));

					return;
				}

				reqDraft.parsedHeaderLength += 1;

				if (dataChar === "\u0000") {
					if (reqDraft.headerState === 1) {
						this.req.params[reqDraft.headerParserStack[0]] = reqDraft.headerParserStack[1];
						reqDraft.headerParserStack = ["", ""];
					}

					reqDraft.headerState ^= 1;
					continue;
				}

				reqDraft.headerParserStack[reqDraft.headerState] += dataChar;
			}
		}

		if (this.clientPhase === 2) {
			if (reqDraft.bodyReceivedLength === undefined) {
				reqDraft.bodyReceivedLength = 0;
			}

			reqDraft.bodyReceivedLength += data.length;

			if (reqDraft.bodyReceivedLength > reqDraft.bodyLength) {
				this.server.emit("clientError", new Error("Body is larger than declared"), this.socket);
				return;
			}

			this.req.emit("data", data);

			if (reqDraft.bodyReceivedLength === reqDraft.bodyLength) {
				reqDraft.clientPhase += 1;
				this.req.emit("end");
			}
		}
	};

	onClientError = function (e, socket) {
		socket.destroy();
	};

	onClientFin = function () {
		if (this.clientPhase < 2) {
			this.server.emit("clientError", new Error("Client FIN before request completes"), this.socket);
		}
	};

	onSocketError = function (e) {
		this.server.emit("clientError", e, this.socket);
	};

	onSocketClose = function (hadError) {
		this.socket.removeAllListeners();

		this.req.emit("close");
		this.res.emit((hadError === false && this.socket._writableState.ended === true) ? "finish" : "close");
	};

	onSocketTimeout = function () {
		this.server.emit("timeout", this.socket);

		process.nextTick(this.socket.end.bind(this.socket));
		process.nextTick(this.socket.destroy.bind(this.socket));
	};

	// Exporting
	exports.Server = Server;
	exports.ClientRequest = ClientRequest;
	exports.ServerResponse = ServerResponse;
	exports.createServer = createServer;
})();
<|endoftext|>