<commit_before>/**
 * Routine that generates a SignedURL based upon the paramters provided making use of the AWSSigner
 *
 * @param actionName - Action to be invoked by AWS
 * @param params - Parameters to be serialized into the URL
 * @param accessKeyId - AccessKey provided by the user
 * @param secretKey - SecretKey provided by the user
 * @param endpoint - Service Endpoint
 * @param version - Version of the Service to be invoked
 */

Ti.include("/module/awssigner.js");
exports.generateSignedURL = function(actionName, params, accessKeyId, secretKey, endpoint, version) {
    var host = endpoint.replace(/.*:\/\//, "");
    var payload = null;
    var displayUri = endpoint;

    params.Action = actionName;
    params.Version = version;
    var signer = new AWSV2Signer(accessKeyId, secretKey);
    params = signer.sign(params, new Date(), {
        "verb": "GET",
        "host": host,
        "uriPath": "/"
    });

    var encodedParams = [];
    for (var key in params) {
        if (params[key] !== null) {
            encodedParams.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
        } else {
            encodedParams.push(encodeURIComponent(key));
        }
    }
    payload = encodedParams.join("&");
    displayUri += "?" + payload;
    return displayUri;
}

/**
 * Routine that generates the signed string based upn the params passed
 *
 * @param - Its a javascript object ar contains all elements required for creating signed string
 * more on the signing string here --http://docs.amazonwebservices.com/AmazonS3/2006-03-01/dev/RESTAuthentication.html
 */
exports.generateS3Params = function(params) {
	if(params.hasOwnProperty('bucketName')) {
		if(params.hasOwnProperty('objectName')) {
			if(params.hasOwnProperty('copySource')) {
				params.canonicalizedAmzHeaders = '\n' + 'x-amz-copy-source:' + params.copySource;
			} else {
				params.canonicalizedAmzHeaders = '';
			}
			if(params.hasOwnProperty('uploadId')) {
				if(params.hasOwnProperty('partNumber')) {
					params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + params.canonicalizedAmzHeaders + '\n/' + params.bucketName + '/' + params.objectName + params.subResource + 'partNumber=' + params.partNumber + '&' + 'uploadId=' + params.uploadId;
					params.url = params.url.concat(params.bucketName + '/' + params.objectName + params.subResource + 'partNumber=' + params.partNumber + '&' + 'uploadId=' + params.uploadId);
				} else {
					params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + params.canonicalizedAmzHeaders + '\n/' + params.bucketName + '/' + params.objectName + params.subResource + 'uploadId=' + params.uploadId;
					params.url = params.url.concat(params.bucketName + '/' + params.objectName + params.subResource + 'uploadId=' + params.uploadId);
				}
			} else {
				params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + params.canonicalizedAmzHeaders + '\n/' + params.bucketName + '/' + params.objectName + params.subResource;
				params.url = params.url.concat(params.bucketName + '/' + params.objectName + params.subResource);
			}
		} else {
			params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + '\n/' + params.bucketName + '/' + params.subResource;
			params.url = params.url.concat(params.bucketName + '/' + params.subResource);
		}
	} else {
		params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + '\n/' + params.subResource;
	}
	return;
}

/* Standard validators supported by the AWS API */
validators = {
	//Checks if all the mandatory parameters specified under data.params, have some value in them
	required:function(request_params, data){
		var param_names=data.params; //Array of parameter names to be checked
		param_names.forEach(function(name){
			var val=request_params[name]; //value of a parameter
			if ((undefined == val) || (val == null) || (val != ""))
				return false; //Validation failed
				//TBD: Need to write mechanism to raise an Error with all relevant details
		});
		return true;
	},
	//Checks to see if there are any matching regualar expressions within the Parameters
	//Useful for validating collection of input parameters.
	patternExistsValidator:function(request_params, data){
		return true;
	}
}

/**
 * Routine that validates the Parameters provided by the User based upon the Rules associated with the method.
 *
 * NOTE: This is work in progress
 *
 * @param params - Parameters to be serialized into the URL
 * @param validations - List of Validation rules to apply, along with their inherent parameters
 */
exports.validateParams = function(request_params, validations) {
	for (var validationRule in validations) {
		fnValidate=validators[validationRule];
		data=validations[validationRule];

		res=fnValidate(request_params, data);
		Ti.API.info('Validation '+validationRule+' = '+res)
	}
}<commit_msg>Added comments to generateS3Params function<commit_after>/**
 * Routine that generates a SignedURL based upon the paramters provided making use of the AWSSigner
 *
 * @param actionName - Action to be invoked by AWS
 * @param params - Parameters to be serialized into the URL
 * @param accessKeyId - AccessKey provided by the user
 * @param secretKey - SecretKey provided by the user
 * @param endpoint - Service Endpoint
 * @param version - Version of the Service to be invoked
 */

Ti.include("/module/awssigner.js");
exports.generateSignedURL = function(actionName, params, accessKeyId, secretKey, endpoint, version) {
    var host = endpoint.replace(/.*:\/\//, "");
    var payload = null;
    var displayUri = endpoint;

    params.Action = actionName;
    params.Version = version;
    var signer = new AWSV2Signer(accessKeyId, secretKey);
    params = signer.sign(params, new Date(), {
        "verb": "GET",
        "host": host,
        "uriPath": "/"
    });

    var encodedParams = [];
    for (var key in params) {
        if (params[key] !== null) {
            encodedParams.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
        } else {
            encodedParams.push(encodeURIComponent(key));
        }
    }
    payload = encodedParams.join("&");
    displayUri += "?" + payload;
    return displayUri;
}

/**
 * Routine that generates the signed string based upn the params passed
 *
 * @param - Its a javascript object that contains all elements required for creating signed string
 * more on the signing string here --http://docs.amazonwebservices.com/AmazonS3/2006-03-01/dev/RESTAuthentication.html
 */
exports.generateS3Params = function(params) {
	//check if the bucket name is passed by the user. If its passed then include it as part of stringtosign data
	if(params.hasOwnProperty('bucketName')) {
		//check if objectName is passed by user if yes then include it as part of stringtosign data
		if(params.hasOwnProperty('objectName')) {
			//copySource is used by 'Put object copy and Upload part ' api's, which needs to be part of stringtosign
			if(params.hasOwnProperty('copySource')) {
				params.canonicalizedAmzHeaders = '\n' + 'x-amz-copy-source:' + params.copySource;
			} else {
				params.canonicalizedAmzHeaders = '';
			}
			if(params.hasOwnProperty('uploadId')) {
				if(params.hasOwnProperty('partNumber')) {
					params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + params.canonicalizedAmzHeaders + '\n/' + params.bucketName + '/' + params.objectName + params.subResource + 'partNumber=' + params.partNumber + '&' + 'uploadId=' + params.uploadId;
					params.url = params.url.concat(params.bucketName + '/' + params.objectName + params.subResource + 'partNumber=' + params.partNumber + '&' + 'uploadId=' + params.uploadId);
				} else {
					params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + params.canonicalizedAmzHeaders + '\n/' + params.bucketName + '/' + params.objectName + params.subResource + 'uploadId=' + params.uploadId;
					params.url = params.url.concat(params.bucketName + '/' + params.objectName + params.subResource + 'uploadId=' + params.uploadId);
				}
			} else {
				params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + params.canonicalizedAmzHeaders + '\n/' + params.bucketName + '/' + params.objectName + params.subResource;
				params.url = params.url.concat(params.bucketName + '/' + params.objectName + params.subResource);
			}
		} else {
			params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + '\n/' + params.bucketName + '/' + params.subResource;
			params.url = params.url.concat(params.bucketName + '/' + params.subResource);
		}
	} else {
		params.stringToSign = params.verb + '\n' + params.contentMD5 + '\n' + params.contentType + '\n' + params.curDate + '\n/' + params.subResource;
	}
	return;
}

/* Standard validators supported by the AWS API */
validators = {
	//Checks if all the mandatory parameters specified under data.params, have some value in them
	required:function(request_params, data){
		var param_names=data.params; //Array of parameter names to be checked
		param_names.forEach(function(name){
			var val=request_params[name]; //value of a parameter
			if ((undefined == val) || (val == null) || (val != ""))
				return false; //Validation failed
				//TBD: Need to write mechanism to raise an Error with all relevant details
		});
		return true;
	},
	//Checks to see if there are any matching regualar expressions within the Parameters
	//Useful for validating collection of input parameters.
	patternExistsValidator:function(request_params, data){
		return true;
	}
}

/**
 * Routine that validates the Parameters provided by the User based upon the Rules associated with the method.
 *
 * NOTE: This is work in progress
 *
 * @param params - Parameters to be serialized into the URL
 * @param validations - List of Validation rules to apply, along with their inherent parameters
 */
exports.validateParams = function(request_params, validations) {
	for (var validationRule in validations) {
		fnValidate=validators[validationRule];
		data=validations[validationRule];

		res=fnValidate(request_params, data);
		Ti.API.info('Validation '+validationRule+' = '+res)
	}
}<|endoftext|>


<commit_before>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');
const utils = require('./utils');

const Flags = {
  DEBUG_DEVTOOLS: '--debug-devtools',
  DEBUG_DEVTOOLS_SHORTHAND: '-d',
  FETCH_CONTENT_SHELL: '--fetch-content-shell',
  CHROMIUM_PATH: '--chromium-path',  // useful for bisecting
  TARGET: '--target',                // build sub-directory (e.g. Release, Default)
};

const IS_DEBUG_ENABLED =
    utils.includes(process.argv, Flags.DEBUG_DEVTOOLS) || utils.includes(process.argv, Flags.DEBUG_DEVTOOLS_SHORTHAND);
const CUSTOM_CHROMIUM_PATH = utils.parseArgs(process.argv)[Flags.CHROMIUM_PATH];
const TARGET = utils.parseArgs(process.argv)[Flags.TARGET] || 'Release';

const CURRENT_PATH = process.env.PWD || process.cwd();  // Using env.PWD to account for symlinks.
const isThirdParty = CURRENT_PATH.includes('third_party');
const CHROMIUM_SRC_PATH = CUSTOM_CHROMIUM_PATH || getChromiumSrcPath(isThirdParty);
const RELEASE_PATH = path.resolve(CHROMIUM_SRC_PATH, 'out', TARGET);
const BLINK_TEST_PATH = path.resolve(CHROMIUM_SRC_PATH, 'third_party', 'blink', 'tools', 'run_web_tests.py');
const DEVTOOLS_PATH = path.resolve(CHROMIUM_SRC_PATH, 'third_party', 'devtools-frontend', 'src');
const CACHE_PATH = path.resolve(DEVTOOLS_PATH, '.test_cache');

function main() {
  if (!utils.isDir(CACHE_PATH)) {
    fs.mkdirSync(CACHE_PATH);
  }

  const hasUserCompiledContentShell = utils.isFile(getContentShellBinaryPath(RELEASE_PATH));
  if (!hasUserCompiledContentShell) {
    return;
  }
  const outDir = path.resolve(RELEASE_PATH, '..');

  runTests(outDir, IS_DEBUG_ENABLED);
}
main();

function getChromiumSrcPath(isThirdParty) {
  if (isThirdParty)
  // Assume we're in `chromium/src/third_party/devtools-frontend/src`.
  {
    return path.resolve(CURRENT_PATH, '..', '..', '..');
  }
  // Assume we're in `devtools/devtools-frontend`, where `devtools` is
  // on the same level as `chromium`.
  const srcPath = path.resolve(CURRENT_PATH, '..', '..', 'chromium', 'src');
  if (!utils.isDir(srcPath)) {
    throw new Error(
        `Chromium source directory not found at \`${srcPath}\`. ` +
        'Either move your standalone `devtools/devtools-frontend` checkout ' +
        'so that `devtools` is at the same level as `chromium` in ' +
        '`chromium/src`, or use `--chromium-path`.');
  }
  return srcPath;
}

function getContentShellBinaryPath(dirPath) {
  if (process.platform === 'linux') {
    return path.resolve(dirPath, 'content_shell');
  }

  if (process.platform === 'win32') {
    return path.resolve(dirPath, 'content_shell.exe');
  }

  if (process.platform === 'darwin') {
    return path.resolve(dirPath, 'Content Shell.app', 'Contents', 'MacOS', 'Content Shell');
  }
}

function runTests(buildDirectoryPath, useDebugDevtools) {
  const testArgs = getInspectorTests().concat([
    '--build-directory',
    buildDirectoryPath,
    '--target',
    TARGET,
  ]);
  if (useDebugDevtools) {
    testArgs.push('--additional-driver-flag=--debug-devtools');
  } else {
    console.log('TIP: You can debug a test using: npm run debug-test inspector/test-name.html');
  }

  if (IS_DEBUG_ENABLED) {
    testArgs.push('--additional-driver-flag=--remote-debugging-port=9222');
    testArgs.push('--time-out-ms=6000000');
    console.log('\n=============================================');
    const unitTest = testArgs.find(arg => arg.includes('http/tests/devtools/unit/'));
    if (unitTest) {
      const unitTestPath = `http://localhost:8080/${unitTest.slice('http/tests/'.length)}`;
      const link =
          `http://localhost:8080/inspector-sources/debug/integration_test_runner.html?test=${unitTestPath}`;
      console.log('1) Go to: ', link);
      console.log('2) Go to: http://localhost:9222/, click on "inspected-page.html", and copy the ws query parameter');
      console.log('3) Open DevTools on DevTools and you can refresh to re-run the test');
    } else {
      console.log('Go to: http://localhost:9222/');
      console.log('Click on link and in console execute: test()');
    }
    console.log('=============================================\n');
  }
  const args = [...testArgs, ...getTestFlags()];
  console.log(`Running web tests with args: ${args.join(' ')}`);
  childProcess.spawn(BLINK_TEST_PATH, args, {stdio: 'inherit'});
}

function getTestFlags() {
  const flagValues = Object.keys(Flags).map(key => Flags[key]);
  return process.argv.slice(2).filter(arg => {
    const flagName = utils.includes(arg, '=') ? arg.slice(0, arg.indexOf('=')) : arg;
    return !utils.includes(flagValues, flagName) && !utils.includes(arg, 'inspector') &&
        !utils.includes(arg, 'http/tests/devtools');
  });
}

function getInspectorTests() {
  const specificTests =
      process.argv.filter(arg => utils.includes(arg, 'inspector') || utils.includes(arg, 'http/tests/devtools'));
  if (specificTests.length) {
    return specificTests;
  }
  return [
    'inspector*',
    'http/tests/inspector*',
    'http/tests/devtools',
  ];
}
<commit_msg>Rename arg name --time-out-ms for rwt<commit_after>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');
const utils = require('./utils');

const Flags = {
  DEBUG_DEVTOOLS: '--debug-devtools',
  DEBUG_DEVTOOLS_SHORTHAND: '-d',
  FETCH_CONTENT_SHELL: '--fetch-content-shell',
  CHROMIUM_PATH: '--chromium-path',  // useful for bisecting
  TARGET: '--target',                // build sub-directory (e.g. Release, Default)
};

const IS_DEBUG_ENABLED =
    utils.includes(process.argv, Flags.DEBUG_DEVTOOLS) || utils.includes(process.argv, Flags.DEBUG_DEVTOOLS_SHORTHAND);
const CUSTOM_CHROMIUM_PATH = utils.parseArgs(process.argv)[Flags.CHROMIUM_PATH];
const TARGET = utils.parseArgs(process.argv)[Flags.TARGET] || 'Release';

const CURRENT_PATH = process.env.PWD || process.cwd();  // Using env.PWD to account for symlinks.
const isThirdParty = CURRENT_PATH.includes('third_party');
const CHROMIUM_SRC_PATH = CUSTOM_CHROMIUM_PATH || getChromiumSrcPath(isThirdParty);
const RELEASE_PATH = path.resolve(CHROMIUM_SRC_PATH, 'out', TARGET);
const BLINK_TEST_PATH = path.resolve(CHROMIUM_SRC_PATH, 'third_party', 'blink', 'tools', 'run_web_tests.py');
const DEVTOOLS_PATH = path.resolve(CHROMIUM_SRC_PATH, 'third_party', 'devtools-frontend', 'src');
const CACHE_PATH = path.resolve(DEVTOOLS_PATH, '.test_cache');

function main() {
  if (!utils.isDir(CACHE_PATH)) {
    fs.mkdirSync(CACHE_PATH);
  }

  const hasUserCompiledContentShell = utils.isFile(getContentShellBinaryPath(RELEASE_PATH));
  if (!hasUserCompiledContentShell) {
    return;
  }
  const outDir = path.resolve(RELEASE_PATH, '..');

  runTests(outDir, IS_DEBUG_ENABLED);
}
main();

function getChromiumSrcPath(isThirdParty) {
  if (isThirdParty)
  // Assume we're in `chromium/src/third_party/devtools-frontend/src`.
  {
    return path.resolve(CURRENT_PATH, '..', '..', '..');
  }
  // Assume we're in `devtools/devtools-frontend`, where `devtools` is
  // on the same level as `chromium`.
  const srcPath = path.resolve(CURRENT_PATH, '..', '..', 'chromium', 'src');
  if (!utils.isDir(srcPath)) {
    throw new Error(
        `Chromium source directory not found at \`${srcPath}\`. ` +
        'Either move your standalone `devtools/devtools-frontend` checkout ' +
        'so that `devtools` is at the same level as `chromium` in ' +
        '`chromium/src`, or use `--chromium-path`.');
  }
  return srcPath;
}

function getContentShellBinaryPath(dirPath) {
  if (process.platform === 'linux') {
    return path.resolve(dirPath, 'content_shell');
  }

  if (process.platform === 'win32') {
    return path.resolve(dirPath, 'content_shell.exe');
  }

  if (process.platform === 'darwin') {
    return path.resolve(dirPath, 'Content Shell.app', 'Contents', 'MacOS', 'Content Shell');
  }
}

function runTests(buildDirectoryPath, useDebugDevtools) {
  const testArgs = getInspectorTests().concat([
    '--build-directory',
    buildDirectoryPath,
    '--target',
    TARGET,
  ]);
  if (useDebugDevtools) {
    testArgs.push('--additional-driver-flag=--debug-devtools');
  } else {
    console.log('TIP: You can debug a test using: npm run debug-test inspector/test-name.html');
  }

  if (IS_DEBUG_ENABLED) {
    testArgs.push('--additional-driver-flag=--remote-debugging-port=9222');
    testArgs.push('--timeout-ms=6000000');
    console.log('\n=============================================');
    const unitTest = testArgs.find(arg => arg.includes('http/tests/devtools/unit/'));
    if (unitTest) {
      const unitTestPath = `http://localhost:8080/${unitTest.slice('http/tests/'.length)}`;
      const link =
          `http://localhost:8080/inspector-sources/debug/integration_test_runner.html?test=${unitTestPath}`;
      console.log('1) Go to: ', link);
      console.log('2) Go to: http://localhost:9222/, click on "inspected-page.html", and copy the ws query parameter');
      console.log('3) Open DevTools on DevTools and you can refresh to re-run the test');
    } else {
      console.log('Go to: http://localhost:9222/');
      console.log('Click on link and in console execute: test()');
    }
    console.log('=============================================\n');
  }
  const args = [...testArgs, ...getTestFlags()];
  console.log(`Running web tests with args: ${args.join(' ')}`);
  childProcess.spawn(BLINK_TEST_PATH, args, {stdio: 'inherit'});
}

function getTestFlags() {
  const flagValues = Object.keys(Flags).map(key => Flags[key]);
  return process.argv.slice(2).filter(arg => {
    const flagName = utils.includes(arg, '=') ? arg.slice(0, arg.indexOf('=')) : arg;
    return !utils.includes(flagValues, flagName) && !utils.includes(arg, 'inspector') &&
        !utils.includes(arg, 'http/tests/devtools');
  });
}

function getInspectorTests() {
  const specificTests =
      process.argv.filter(arg => utils.includes(arg, 'inspector') || utils.includes(arg, 'http/tests/devtools'));
  if (specificTests.length) {
    return specificTests;
  }
  return [
    'inspector*',
    'http/tests/inspector*',
    'http/tests/devtools',
  ];
}
<|endoftext|>


<commit_before>//Translated from goban.rb using babyruby2js
'use strict';

var main = require('./main');
var Grid = require('./Grid');
var Stone = require('./Stone');
var Group = require('./Group');

/** @class Stores what we have on the board (namely, the stones and the empty spaces).
 *  - Giving coordinates, a Goban can return an existing stone.
 *  - It also remembers the list of stones played and can share this info for undo feature.
 *  - For console game and debug features, a goban can also "draw" its content as text.
 *  See Stone and Group classes for the layer above this.
 *  public read-only attribute: gsize, grid, scoringGrid, mergedGroups, killedGroups, garbageGroups
 */
function Goban(gsize) {
    if (gsize === undefined) gsize = 19;
    this.gsize = gsize;
    this.grid = new Grid(gsize);
    this.scoringGrid = new Grid(gsize);
    this.ban = this.grid.yx;
    for (var j = 1; j <= gsize; j++) {
        for (var i = 1; i <= gsize; i++) {
            this.ban[j][i] = new Stone(this, i, j, main.EMPTY);
        }
    }
    for (j = 1; j <= gsize; j++) {
        for (i = 1; i <= gsize; i++) {
            this.ban[j][i].findNeighbors();
        }
    }
    // sentinel for group list searches; NB: values like -100 helps detecting bugs when value is used by mistake
    Goban.sentinel = new Group(this, new Stone(this, -50, -50, main.EMPTY), -100, 0);
    this.killedGroups = [Goban.sentinel]; // so that we can always do @killed_groups.last.color, etc.
    this.mergedGroups = [Goban.sentinel];
    this.garbageGroups = [];
    this.numGroups = 0;
    this.history = [];
}
module.exports = Goban;

// Prepares the goban for another game (same size, same number of players)
Goban.prototype.clear = function () {
    for (var j = 1; j <= this.gsize; j++) {
        for (var i = 1; i <= this.gsize; i++) {
            var stone = this.ban[j][i];
            if (stone.group) {
                stone.group.clear();
            }
        }
    }
    // Collect all the groups and put them into @garbage_groups
    this.killedGroups.shift(); // removes @@sentinel
    this.mergedGroups.shift(); // removes @@sentinel
    this.garbageGroups.concat(this.killedGroups);
    this.garbageGroups.concat(this.mergedGroups);
    this.killedGroups.clear();
    this.killedGroups.push(Goban.sentinel);
    this.mergedGroups.clear();
    this.mergedGroups.push(Goban.sentinel);
    this.numGroups = 0;
    return this.history.clear();
};

// Allocate a new group or recycles one from garbage list.
// For efficiency, call this one, do not call the regular Group.new method.
Goban.prototype.newGroup = function (stone, lives) {
    var group = this.garbageGroups.pop();
    if (group) {
        return group.recycle(stone, lives);
    } else {
        this.numGroups += 1;
        return new Group(this, stone, lives, this.numGroups);
    }
};

Goban.prototype.image = function () {
    return this.grid.toLine(function (s) {
        return Grid.colorToChar(s.color);
    });
};

// For debugging only
Goban.prototype.debugDisplay = function () {
    console.log('Board:');
    console.log(this.grid.toText(function (s) {
        return Grid.colorToChar(s.color);
    }));
    console.log('Groups:');
    console.log(this.grid.toText(function (s) {
        if (s.group) {
            return '' + s.group.ndx;
        } else {
            return '.';
        }
    }));
    console.log('Full info on groups and stones:');
    var groups = {};
    for (var row, row_array = this.grid.yx, row_ndx = 0; row=row_array[row_ndx], row_ndx < row_array.length; row_ndx++) {
        for (var s, s_array = row, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
            if (s && s.group) {
                groups[s.group.ndx] = s.group;
            }
        }
    }
    for (var ndx = 1; ndx <= this.numGroups; ndx++) {
        if (groups[ndx]) {
            console.log(groups[ndx].debugDump());
        }
    }
};

// This display is for debugging and text-only game
Goban.prototype.consoleDisplay = function () {
    console.log(this.grid.toText(function (s) {
        return Grid.colorToChar(s.color);
    }));
};

// Basic validation only: coordinates and checks the intersection is empty
// See Stone class for evolved version of this (calling this one)
Goban.prototype.validMove = function (i, j) {
    if (i < 1 || i > this.gsize || j < 1 || j > this.gsize) {
        return false;
    }
    return this.ban[j][i].empty();
};

Goban.prototype.stoneAt = function (i, j) {
    return this.ban[j][i];
};

Goban.prototype.color = function (i, j) {
    var stone = this.ban[j][i];
    if (stone) { // works because BORDER == nil
        return stone.color;
    }
    return main.BORDER;
};

// No validity test here
Goban.prototype.empty = function (i, j) {
    return this.ban[j][i].empty();
};

Goban.prototype.moveNumber = function () {
    return this.history.length;
};

// Plays a stone and stores it in history
// Actually we simply return the existing stone and the caller will update it
Goban.prototype.playAt = function (i, j) {
    var stone = this.ban[j][i];
    if (stone.color !== main.EMPTY) {
        throw new Error('Tried to play on existing stone in ' + stone);
    }
    this.history.push(stone);
    return stone;
};

// Removes the last stone played from the board
// Actually we simply return the existing stone and the caller will update it
Goban.prototype.undo = function () {
    return this.history.pop();
};

Goban.prototype.previousStone = function () {
    return this.history[this.history.length-1];
};

// E02: unknown method: concat(...)<commit_msg>Goban#toString instead of consoleDisplay<commit_after>//Translated from goban.rb using babyruby2js
'use strict';

var main = require('./main');
var Grid = require('./Grid');
var Stone = require('./Stone');
var Group = require('./Group');

/** @class Stores what we have on the board (namely, the stones and the empty spaces).
 *  - Giving coordinates, a Goban can return an existing stone.
 *  - It also remembers the list of stones played and can share this info for undo feature.
 *  - For console game and debug features, a goban can also "draw" its content as text.
 *  See Stone and Group classes for the layer above this.
 *  public read-only attribute: gsize, grid, scoringGrid, mergedGroups, killedGroups, garbageGroups
 */
function Goban(gsize) {
    if (gsize === undefined) gsize = 19;
    this.gsize = gsize;
    this.grid = new Grid(gsize);
    this.scoringGrid = new Grid(gsize);
    this.ban = this.grid.yx;
    for (var j = 1; j <= gsize; j++) {
        for (var i = 1; i <= gsize; i++) {
            this.ban[j][i] = new Stone(this, i, j, main.EMPTY);
        }
    }
    for (j = 1; j <= gsize; j++) {
        for (i = 1; i <= gsize; i++) {
            this.ban[j][i].findNeighbors();
        }
    }
    // sentinel for group list searches; NB: values like -100 helps detecting bugs when value is used by mistake
    Goban.sentinel = new Group(this, new Stone(this, -50, -50, main.EMPTY), -100, 0);
    this.killedGroups = [Goban.sentinel]; // so that we can always do @killed_groups.last.color, etc.
    this.mergedGroups = [Goban.sentinel];
    this.garbageGroups = [];
    this.numGroups = 0;
    this.history = [];
}
module.exports = Goban;

// Prepares the goban for another game (same size, same number of players)
Goban.prototype.clear = function () {
    for (var j = 1; j <= this.gsize; j++) {
        for (var i = 1; i <= this.gsize; i++) {
            var stone = this.ban[j][i];
            if (stone.group) {
                stone.group.clear();
            }
        }
    }
    // Collect all the groups and put them into @garbage_groups
    this.killedGroups.shift(); // removes @@sentinel
    this.mergedGroups.shift(); // removes @@sentinel
    this.garbageGroups.concat(this.killedGroups);
    this.garbageGroups.concat(this.mergedGroups);
    this.killedGroups.clear();
    this.killedGroups.push(Goban.sentinel);
    this.mergedGroups.clear();
    this.mergedGroups.push(Goban.sentinel);
    this.numGroups = 0;
    return this.history.clear();
};

// Allocate a new group or recycles one from garbage list.
// For efficiency, call this one, do not call the regular Group.new method.
Goban.prototype.newGroup = function (stone, lives) {
    var group = this.garbageGroups.pop();
    if (group) {
        return group.recycle(stone, lives);
    } else {
        this.numGroups += 1;
        return new Group(this, stone, lives, this.numGroups);
    }
};

Goban.prototype.image = function () {
    return this.grid.toLine(function (s) {
        return Grid.colorToChar(s.color);
    });
};

// For debugging only
Goban.prototype.debugDisplay = function () {
    console.log('Board:');
    console.log(this.grid.toText(function (s) {
        return Grid.colorToChar(s.color);
    }));
    console.log('Groups:');
    console.log(this.grid.toText(function (s) {
        if (s.group) {
            return '' + s.group.ndx;
        } else {
            return '.';
        }
    }));
    console.log('Full info on groups and stones:');
    var groups = {};
    for (var row, row_array = this.grid.yx, row_ndx = 0; row=row_array[row_ndx], row_ndx < row_array.length; row_ndx++) {
        for (var s, s_array = row, s_ndx = 0; s=s_array[s_ndx], s_ndx < s_array.length; s_ndx++) {
            if (s && s.group) {
                groups[s.group.ndx] = s.group;
            }
        }
    }
    for (var ndx = 1; ndx <= this.numGroups; ndx++) {
        if (groups[ndx]) {
            console.log(groups[ndx].debugDump());
        }
    }
};

// This display is for debugging and text-only game
Goban.prototype.toString = function () {
    return this.grid.toText(function (s) {
        return Grid.colorToChar(s.color);
    });
};

// Basic validation only: coordinates and checks the intersection is empty
// See Stone class for evolved version of this (calling this one)
Goban.prototype.validMove = function (i, j) {
    if (i < 1 || i > this.gsize || j < 1 || j > this.gsize) {
        return false;
    }
    return this.ban[j][i].empty();
};

Goban.prototype.stoneAt = function (i, j) {
    return this.ban[j][i];
};

Goban.prototype.color = function (i, j) {
    var stone = this.ban[j][i];
    if (stone) { // works because BORDER == nil
        return stone.color;
    }
    return main.BORDER;
};

// No validity test here
Goban.prototype.empty = function (i, j) {
    return this.ban[j][i].empty();
};

Goban.prototype.moveNumber = function () {
    return this.history.length;
};

// Plays a stone and stores it in history
// Actually we simply return the existing stone and the caller will update it
Goban.prototype.playAt = function (i, j) {
    var stone = this.ban[j][i];
    if (stone.color !== main.EMPTY) {
        throw new Error('Tried to play on existing stone in ' + stone);
    }
    this.history.push(stone);
    return stone;
};

// Removes the last stone played from the board
// Actually we simply return the existing stone and the caller will update it
Goban.prototype.undo = function () {
    return this.history.pop();
};

Goban.prototype.previousStone = function () {
    return this.history[this.history.length-1];
};

// E02: unknown method: concat(...)<|endoftext|>


<commit_before>const schema = require('./../schemas')

const SchoolSchema = schema.object(
  {
    title: 'School',
    description:
      'A school or school-level educational institution or business location, potentially belonging to a school district or other educational network'
  },
  {
    district: schema.objectId({
      links: [{ rel: 'extra', href: '/db/district/{($)}' }]
    }),
    name: schema.shortString(),
    ncesId: { type: 'string', minLength: 12, maxLength: 12 },
    type: schema.shortString({ description: 'Type of school' }),
    phone: schema.shortString({ description: 'Phone number' }),
    students: schema.int({ description: 'Total students all grades' }),
    teachers: schema.int({ description: 'Full-Time equivalent teachers' }),
    level: schema.shortString({ description: 'School Level' }),
    website: schema.shortString({ description: 'Website' }),
    geo: schema.object(
      {},
      {
        country: { description: '2 letter ISO-3166-1 country code' },
        countryName: { description: 'Full country name' },
        region: { description: '2 character region code' },
        regionName: { description: 'Full region name -- use for full state name' },
        county: { description: 'County Name' },
        city: { description: 'Full city name' },
        ll: schema.array(
          {},
          { description: 'Latitude and longitude of the city' }
        ),
        metro: { description: 'Metro code' },
        zip: { type: 'string', description: 'Postal code' },
        address: schema.shortString({ description: 'Address of school' }),
        localeCode: schema.shortString({ description: 'The Urban Centric Locale code for a school' })
      }
    )
  }
)

schema.extendBasicProperties(SchoolSchema, 'school')

module.exports = SchoolSchema
<commit_msg>School schema name is required<commit_after>const schema = require('./../schemas')

const SchoolSchema = schema.object(
  {
    title: 'School',
    description:
      'A school or school-level educational institution or business location, potentially belonging to a school district or other educational network',
    required: ['name']
  },
  {
    district: schema.objectId({
      links: [{ rel: 'extra', href: '/db/district/{($)}' }]
    }),
    name: schema.shortString(),
    ncesId: { type: 'string', minLength: 12, maxLength: 12 },
    type: schema.shortString({ description: 'Type of school' }),
    phone: schema.shortString({ description: 'Phone number' }),
    students: schema.int({ description: 'Total students all grades' }),
    teachers: schema.int({ description: 'Full-Time equivalent teachers' }),
    level: schema.shortString({ description: 'School Level' }),
    website: schema.shortString({ description: 'Website' }),
    geo: schema.object(
      {},
      {
        country: { description: '2 letter ISO-3166-1 country code' },
        countryName: { description: 'Full country name' },
        region: { description: '2 character region code' },
        regionName: { description: 'Full region name -- use for full state name' },
        county: { description: 'County Name' },
        city: { description: 'Full city name' },
        ll: schema.array(
          {},
          { description: 'Latitude and longitude of the city' }
        ),
        metro: { description: 'Metro code' },
        zip: { type: 'string', description: 'Postal code' },
        address: schema.shortString({ description: 'Address of school' }),
        localeCode: schema.shortString({ description: 'The Urban Centric Locale code for a school' })
      }
    )
  }
)

schema.extendBasicProperties(SchoolSchema, 'school')

module.exports = SchoolSchema
<|endoftext|>


<commit_before>// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide('frappe.energy_points');

Object.assign(frappe.energy_points, {
	get_points(points) {
		return `= 0 ? '#45A163': '#e42121'}">
			${points > 0 ? '+': ''}${points}
		`;
	},
	format_form_log(log) {
		const separator = `<span> - </span>`;
		const formatted_log = `
			${this.get_points(log.points)}
			${this.get_form_log_message(log)}
			${log.reason ? separator + log.reason: ''}
		`;
		return formatted_log;
	},
	format_history_log(log) {
		// redundant code to honor readability and to avoid confusion
		const separator = `<span> - </span>`;
		const route = frappe.utils.get_form_link(log.reference_doctype, log.reference_name);
		const formatted_log = `
			${this.get_points(log.points)}
			${this.get_history_log_message(log)}
			${log.reason ? separator + log.reason: ''}
			${separator + frappe.datetime.comment_when(log.creation)}
		`;
		return formatted_log;
	},
	get_history_log_message(log) {
		const owner_name = frappe.user.full_name(log.owner).bold();
		const ref_doc = log.reference_name;

		if (log.type === 'Appreciation') {
			return __('{0} appreciated on {1}', [owner_name, ref_doc]);
		}
		if (log.type === 'Criticism') {
			return __('{0} criticized on {1}', [owner_name, ref_doc]);
		}
		if (log.type === 'Revert') {
			return __('{0} reverted {1}', [owner_name, log.revert_of]);
		}
		return __('via automatic rule {0} on {1}', [log.rule.bold(), ref_doc]);
	},
	get_form_log_message(log) {
		// redundant code to honor readability and to avoid confusion
		const owner_name = frappe.user.full_name(log.owner).bold();
		const user = frappe.user.full_name(log.user).bold();
		if (log.type === 'Appreciation') {
			return __('{0} appreciated {1}', [owner_name, user]);
		}
		if (log.type === 'Criticism') {
			return __('{0} criticized {1}', [owner_name, user]);
		}
		if (log.type === 'Revert') {
			return __('{0} reverted {1}', [owner_name, log.revert_of]);
		}
		return __('gained by {0} via automatic rule {1}', [user, log.rule.bold()]);
	},
});<commit_msg>fix: Show bold points everywhere<commit_after>// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide('frappe.energy_points');

Object.assign(frappe.energy_points, {
	get_points(points) {
		return `= 0 ? '#45A163': '#e42121'}">
			${points > 0 ? '+': ''}${points}
		`;
	},
	format_form_log(log) {
		const separator = `<span> - </span>`;
		const formatted_log = `
			${this.get_points(log.points)}
			${this.get_form_log_message(log)}
			${log.reason ? separator + log.reason: ''}
		`;
		return formatted_log;
	},
	format_history_log(log) {
		// redundant code to honor readability and to avoid confusion
		const separator = `<span> - </span>`;
		const route = frappe.utils.get_form_link(log.reference_doctype, log.reference_name);
		const formatted_log = `
			${this.get_points(log.points)}
			${this.get_history_log_message(log)}
			${log.reason ? separator + log.reason: ''}
			${separator + frappe.datetime.comment_when(log.creation)}
		`;
		return formatted_log;
	},
	get_history_log_message(log) {
		const owner_name = frappe.user.full_name(log.owner).bold();
		const ref_doc = log.reference_name;

		if (log.type === 'Appreciation') {
			return __('{0} appreciated on {1}', [owner_name, ref_doc]);
		}
		if (log.type === 'Criticism') {
			return __('{0} criticized on {1}', [owner_name, ref_doc]);
		}
		if (log.type === 'Revert') {
			return __('{0} reverted {1}', [owner_name, log.revert_of]);
		}
		return __('via automatic rule {0} on {1}', [log.rule.bold(), ref_doc]);
	},
	get_form_log_message(log) {
		// redundant code to honor readability and to avoid confusion
		const owner_name = frappe.user.full_name(log.owner).bold();
		const user = frappe.user.full_name(log.user).bold();
		if (log.type === 'Appreciation') {
			return __('{0} appreciated {1}', [owner_name, user]);
		}
		if (log.type === 'Criticism') {
			return __('{0} criticized {1}', [owner_name, user]);
		}
		if (log.type === 'Revert') {
			return __('{0} reverted {1}', [owner_name, log.revert_of]);
		}
		return __('gained by {0} via automatic rule {1}', [user, log.rule.bold()]);
	},
});
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Pascal Mainini
 * Licensed under MIT license, see included file LICENSE or
 * http://opensource.org/licenses/MIT
 */

/**
 * This module implements the basic decomposition (DEC) algorithm for blinding
 * of the modexp-params.
 * Functions in this module should not be called directly, instead calls should
 * be made via FamodulusClient-object.
 * @see famodulus-client/client
 * @module famodulus-client/dec
 */

/* global Promise */
'use strict';

const _I = require('BigInt');
const util = require('./util.js');
const direct = require('./direct.js');

/**
 * Calculate a single or multiple modexp(s) with blinded exponent on two servers. If options.checked
 * is true, for each modexp, an identical modexp will be sent additionally to both servers and an error
 * will be raised if they are not identical. The order of the modexps and of the calls to the servers is randomized.
 *
 * Required options are 'servers' containing two full URIs to a famodulus modexp-API and 'brief',
 * indicating if a brief response is desired.
 *
 * @param {Object[]} modexps    An Array with modexps in the form {b:'base', e:'exponent', m:'modulus'}
 *                              (values are hexadecimal and may be undefined)
 * @param {Object} defaults     Default params given as {b:'base', e:'exponent', m:'modulus'}, applied if
 *                              omitted in any modexp (values are hexadecimal and may be undefined)
 * @param {Object} options      Options, requires 'servers' and 'brief'
 * @returns {Promise}           A promise to the remote modexp calculation.
 */
function decExponent (modexps, defaults, options) {
  // fill in default values for each modexp, where missing
  let data;
  if (defaults.b || defaults.e || defaults.m) {
    data = modexps.map(modexp =>
      ({
        b: modexp.b || defaults.b,
        e: modexp.e || defaults.e,
        m: modexp.m || defaults.m
      }));
  } else data = modexps;

  // ======= 1.) split exponents and prepare a list with modexps for each server =======

  let moduli = [];            // moduli of modexps may be different, we need to remember them for final multiplication
  let modexpsB = [];          // modexps with exponent b
  let modexpsC = [];          // modexps with exponent c
  for (let modexp of data) {
    let a = _I.str2bigInt(modexp.e, 16, 0);             // a <- exponent
    let p = _I.str2bigInt(modexp.m, 16, 0);             // p <- modulus
    let q = _I.sub(p, util.ONE);                        // q <- p-1 (p is prime by definition!)
    let b = util.random(q);                             // b <- random in Z_q
    let c = _I.mod(_I.sub(_I.add(a, q), b), q);         // c <- (a+q)-b mod q, we add q first to ensure c > 0
    //                                                                (BigInt returns 2s-complement otherwise)

    // sanity check, a has to be in Z_q
    if (_I.greater(a, q) || _I.equals(a, q)) return Promise.reject(new RangeError('Exponent not in Z_q!'));

    // add modexp to lists
    moduli.push(p);
    modexpsB.push({b: modexp.b, e: _I.bigInt2str(b, 16), m: modexp.m});
    modexpsC.push({b: modexp.b, e: _I.bigInt2str(c, 16), m: modexp.m});

    // if checked calculations are desired, add a modexp with randomized
    // exponent but same base and modulus for each server
    if (options.checked) {
      moduli.push(p);
      let rStr = _I.bigInt2str(util.random(q), 16);
      modexpsB.push({b: modexp.b, e: rStr, m: modexp.m});
      modexpsC.push({b: modexp.b, e: rStr, m: modexp.m});
    }
  }

  // ======= 2.) Randomize order of modexps and send them in random order to servers =======

  let listShuffle = util.randomList(moduli.length);
  let servers = util.shuffleList(options.servers);

  return Promise.resolve(Promise.all([
    direct.direct(util.shuffleList(modexpsB, listShuffle), {}, {server: servers[0]}),
    direct.direct(util.shuffleList(modexpsC, listShuffle), {}, {server: servers[1]})
  ]).then(data => {
    if (data[0].length !== data[1].length) throw new Error('Inequal amount of results obtained!');

    // ======= 3.) having obtained all results, multiply them ( u^b*u^c mod p ) and return =======

    let res1 = util.unshuffleList(data[0], listShuffle);
    let res2 = util.unshuffleList(data[1], listShuffle);

    // check if the test-values for checkability correspond
    if (options.checked) {
      let dataLength = res1.length / 2;
      for (let i = 0; i < dataLength; i++) {
        if (res1.splice(i + 1, 1)[0].r !== res2.splice(i + 1, 1)[0].r) throw new Error('Checking failed!');
      }
    }

    // multiply results and return them
    let results = new Array(res1.length);
    for (let i = 0; i < res1.length; i++) {
      if (options.brief) results[i] = {};
      else results[i] = {b: modexps[i].b, e: modexps[i].e, m: modexps[i].m};
      results[i].r = _I.bigInt2str(_I.multMod(_I.str2bigInt(res1[i].r, 16, 0), _I.str2bigInt(res2[i].r, 16, 0), moduli[i]), 16);
    }

    return results;
  }));
}

module.exports = {decExponent: decExponent};
<commit_msg>second version by Rolf (first not added)<commit_after>/*
 * Copyright 2016 Pascal Mainini
 * Licensed under MIT license, see included file LICENSE or
 * http://opensource.org/licenses/MIT
 */

/**
 * This module implements the basic decomposition (DEC) algorithm for blinding
 * of the modexp-params.
 * Functions in this module should not be called directly, instead calls should
 * be made via FamodulusClient-object.
 * @see famodulus-client/client
 * @module famodulus-client/dec
 */

/* global Promise */
'use strict';
const _I = require('BigInt');
const util = require('./util.js');
const direct = require('./direct.js');

var bpi = 52; // bit size of mantissa of JS numbers
var bpe = 0; // max bit size to perform integer multiplications
for (bpe = 0; (1 << (bpe + 1)) > (1 << bpe); bpe++)
  ;
bpe >>= 1;

var z = [""]; // precomputation of strings with leading zeros
for (var i = 1; i < bpi; i++) {
  z.push(z[z.length - 1] + "0");
}

function bigInt2Hex (x) {
  return bin2Hex(bigInt2Bin(x));
}

function hex2BigInt (h) {
  return bin2BigInt(hex2Bin(h));
}

function bigInt2Bin (x) {
  var s = "";
  for (var i = x.length - 2; i >= 0; i--) {
    var b = x[i].toString(2);
    if (i < x.length - 2) {
      s += z[bpe - b.length];
    }
    s += b;
  }
  return s;
}

function bin2Hex (b) {
  var h = "";
  for (var i = -(b.length % bpi); i < b.length; i = i + bpi) {
    h += parseInt(b.substring(i, i + bpi), 2).toString(16).toUpperCase();
  }
  return h;
}

function bin2BigInt (b) {
  var x = [];
  for (var i = b.length; i > 0; i = i - bpe) {
    x.push(parseInt(b.substring(i - bpe, i), 2));
  }
  x.push(0);
  return x;
}

function hex2Bin (h) {
  var b = "";
  for (var i = -(h.length % (bpi / 4)); i < h.length; i = i + bpi / 4) {
    b += parseInt(h.substring(i, i + bpi / 4), 16).toString(2);
  }
  return b;
}

/**
 * Calculate a single or multiple modexp(s) with blinded exponent on two servers. If options.checked
 * is true, for each modexp, an identical modexp will be sent additionally to both servers and an error
 * will be raised if they are not identical. The order of the modexps and of the calls to the servers is randomized.
 *
 * Required options are 'servers' containing two full URIs to a famodulus modexp-API and 'brief',
 * indicating if a brief response is desired.
 *
 * @param {Object[]} modexps    An Array with modexps in the form {b:'base', e:'exponent', m:'modulus'}
 *                              (values are hexadecimal and may be undefined)
 * @param {Object} defaults     Default params given as {b:'base', e:'exponent', m:'modulus'}, applied if
 *                              omitted in any modexp (values are hexadecimal and may be undefined)
 * @param {Object} options      Options, requires 'servers' and 'brief'
 * @returns {Promise}           A promise to the remote modexp calculation.
 */
function decExponent (modexps, defaults, options) {
  // fill in default values for each modexp, where missing
  let data;
  if (defaults.b || defaults.e || defaults.m) {
    data = modexps.map(modexp =>
      ({
        b: modexp.b || defaults.b,
        e: modexp.e || defaults.e,
        m: modexp.m || defaults.m
      }));
  } else data = modexps;

  // ======= 1.) split exponents and prepare a list with modexps for each server =======

  let moduli = [];            // moduli of modexps may be different, we need to remember them for final multiplication
  let modexpsB = [];          // modexps with exponent b
  let modexpsC = [];          // modexps with exponent c
  for (let modexp of data) {
    let a = hex2BigInt(modexp.e); // a <- exponent
    let p = hex2BigInt(modexp.m);             // p <- modulus
    let q = _I.sub(p, util.ONE);                        // q <- p-1 (p is prime by definition!)
    let b = util.random(q);                             // b <- random in Z_q
    let c = _I.mod(_I.sub(_I.add(a, q), b), q);         // c <- (a+q)-b mod q, we add q first to ensure c > 0
    //                                                                (BigInt returns 2s-complement otherwise)

    // sanity check, a has to be in Z_q
    if (_I.greater(a, q) || _I.equals(a, q)) return Promise.reject(new RangeError('Exponent not in Z_q!'));

    // add modexp to lists
    moduli.push(p);
    modexpsB.push({b: modexp.b, e: _I.bigInt2str(b, 16), m: modexp.m});
    modexpsC.push({b: modexp.b, e: _I.bigInt2str(c, 16), m: modexp.m});

    // if checked calculations are desired, add a modexp with randomized
    // exponent but same base and modulus for each server
    if (options.checked) {
      moduli.push(p);
      let rStr = _I.bigInt2str(util.random(q), 16);
      modexpsB.push({b: modexp.b, e: rStr, m: modexp.m});
      modexpsC.push({b: modexp.b, e: rStr, m: modexp.m});
    }
  }

  // ======= 2.) Randomize order of modexps and send them in random order to servers =======

  let listShuffle = util.randomList(moduli.length);
  let servers = util.shuffleList(options.servers);

  return Promise.resolve(Promise.all([
    direct.direct(util.shuffleList(modexpsB, listShuffle), {}, {server: servers[0]}),
    direct.direct(util.shuffleList(modexpsC, listShuffle), {}, {server: servers[1]})
  ]).then(data => {
    if (data[0].length !== data[1].length) throw new Error('Inequal amount of results obtained!');

    // ======= 3.) having obtained all results, multiply them ( u^b*u^c mod p ) and return =======

    let res1 = util.unshuffleList(data[0], listShuffle);
    let res2 = util.unshuffleList(data[1], listShuffle);

    // check if the test-values for checkability correspond
    if (options.checked) {
      let dataLength = res1.length / 2;
      for (let i = 0; i < dataLength; i++) {
        if (res1.splice(i + 1, 1)[0].r !== res2.splice(i + 1, 1)[0].r) throw new Error('Checking failed!');
      }
    }

    // multiply results and return them
    let results = new Array(res1.length);
    for (let i = 0; i < res1.length; i++) {
      if (options.brief) results[i] = {};
      else results[i] = {b: modexps[i].b, e: modexps[i].e, m: modexps[i].m};
      results[i].r = _I.bigInt2str(_I.multMod(bigInt2Hex(res1[i].r), bigInt2Hex(res2[i].r), moduli[i]), 16);
//      results[i].r = _I.bigInt2str(_I.multMod(_I.str2bigInt(res1[i].r, 16, 0), _I.str2bigInt(res2[i].r, 16, 0), moduli[i]), 16);
    }

    return results;
  }));
}

module.exports = {decExponent: decExponent};
<|endoftext|>


<commit_before>function Login(app) {
	this.app = app;
	if(!this.is_logged_in()) {
		this.log_in();
		if(!this.onLine()) alert("You need to be on line to log in to your server.");
	}
	else this.app.after_login(localStorage.backend);
};

Login.prototype.onLine = function() {
	return navigator.onLine;
};

Login.prototype.is_logged_in = function() {
	return localStorage.backend && localStorage.server_url && localStorage.session_id;
};

Login.prototype.log_in = function() {
	this.app.changeToPage("#login");
	$("#login form").addEventListener('submit', this.authenticate.bind(this));
};

Login.prototype.authenticate = function(e) {
	// do not reload page
	e.preventDefault();
 	e.stopPropagation();

 	var backend = "TinyTinyRSS";
 	if($("#login form").backend[1].checked) backend = "OwnCloud";

	var server_url = $("#url").value;
	var user = $("#un").value;
	var password = $("#pw").value;

	if(!this.onLine()) {
		alert("You need to be on line to log in to your server.");
		return false;
	}

	var errs = [];
	if(!server_url || server_url.indexOf("http") != 0) errs.push("add a server url that starts with http");
	if((user && !password) || (!user && password)) errs.push("add both username and password or neither");

	if(errs.length > 0) {
		alert("Please " + errs.join(",\n") + ".");
		return false;
	}

	var _this = this;

	if(backend == "OwnCloud") {
		OwnCloud.login(server_url, user, password, function(data) {
			if(data.version) {
				var auth = btoa(user + ':' + password);
				localStorage.server_url = server_url;
				localStorage.session_id = auth;
				localStorage.backend = "OwnCloud";
				_this.app.after_login(localStorage.backend);

				$("#url").value = "";
				$("#un").value = "";
				$("#pw").value = "";
			} else {
				alert("Something went wrong, please check every input field and try again.");
			}
		});

	} else {
		TinyTinyRSS.login(server_url, user, password, function(data) {
			if(data.error) {
				if(data.error == "API_DISABLED") {
					alert("You need to enable API access in your TTRSS preferences.\n\nTo do so go to your server log in and then in Preferences -> General -> Enable API access. Check the box and save. Then try again to log in.")
				} else if(data.error == "LOGIN_ERROR") {
					alert("Login error\n\nIt seems you provided a wrong username or password.")
				} else {
					alert(data.error);
				}

			} else {
				localStorage.server_url = server_url;
				localStorage.session_id = data.session_id;
				localStorage.backend = "TinyTinyRSS";
				_this.app.after_login(localStorage.backend);

				$("#url").value = "";
				$("#un").value = "";
				$("#pw").value = "";
			}
		});
	}

	return false;
};

Login.prototype.log_out = function() {
	localStorage.removeItem("server_url");
	localStorage.removeItem("session_id");
	localStorage.removeItem("unread_articles");
	this.log_in();
}<commit_msg>changing server placeholder in login<commit_after>function Login(app) {
	this.app = app;
	if(!this.is_logged_in()) {
		this.log_in();
		if(!this.onLine()) alert("You need to be on line to log in to your server.");
	}
	else this.app.after_login(localStorage.backend);
};

Login.prototype.onLine = function() {
	return navigator.onLine;
};

Login.prototype.is_logged_in = function() {
	return localStorage.backend && localStorage.server_url && localStorage.session_id;
};

Login.prototype.log_in = function() {
	this.app.changeToPage("#login");
	$("#login form").backend.forEach(function(o, i) {
		o.addEventListener("change", function(e) {
			if(e.target.checked) {
				if(e.target.value == "OwnCloud") {
					$("#url").placeholder = "http://example.com/owncloud/";
				} else {
					$("#url").placeholder = "http://example.com/tt-rss/";
				}
			}
		});
	});
	$("#login form").addEventListener('submit', this.authenticate.bind(this));
};

Login.prototype.authenticate = function(e) {
	// do not reload page
	e.preventDefault();
 	e.stopPropagation();

 	var backend = "TinyTinyRSS";
 	if($("#login form").backend[1].checked) backend = "OwnCloud";

	var server_url = $("#url").value;
	var user = $("#un").value;
	var password = $("#pw").value;

	if(!this.onLine()) {
		alert("You need to be on line to log in to your server.");
		return false;
	}

	var errs = [];
	if(!server_url || server_url.indexOf("http") != 0) errs.push("add a server url that starts with http");
	if((user && !password) || (!user && password)) errs.push("add both username and password or neither");

	if(errs.length > 0) {
		alert("Please " + errs.join(",\n") + ".");
		return false;
	}

	var _this = this;

	if(backend == "OwnCloud") {
		OwnCloud.login(server_url, user, password, function(data) {
			if(data.version) {
				var auth = btoa(user + ':' + password);
				localStorage.server_url = server_url;
				localStorage.session_id = auth;
				localStorage.backend = "OwnCloud";
				_this.app.after_login(localStorage.backend);

				$("#url").value = "";
				$("#un").value = "";
				$("#pw").value = "";
			} else {
				alert("Something went wrong, please check every input field and try again.");
			}
		});

	} else {
		TinyTinyRSS.login(server_url, user, password, function(data) {
			if(data.error) {
				if(data.error == "API_DISABLED") {
					alert("You need to enable API access in your TTRSS preferences.\n\nTo do so go to your server log in and then in Preferences -> General -> Enable API access. Check the box and save. Then try again to log in.")
				} else if(data.error == "LOGIN_ERROR") {
					alert("Login error\n\nIt seems you provided a wrong username or password.")
				} else {
					alert(data.error);
				}

			} else {
				localStorage.server_url = server_url;
				localStorage.session_id = data.session_id;
				localStorage.backend = "TinyTinyRSS";
				_this.app.after_login(localStorage.backend);

				$("#url").value = "";
				$("#un").value = "";
				$("#pw").value = "";
			}
		});
	}

	return false;
};

Login.prototype.log_out = function() {
	localStorage.removeItem("server_url");
	localStorage.removeItem("session_id");
	localStorage.removeItem("unread_articles");
	this.log_in();
}<|endoftext|>


<commit_before>import m from 'mithril';
import ClipboardJS from 'clipboard';
import classNames from '../classnames.js';

// The area of the game UI consisting of game UI controls and status messages
class DashboardComponent {

  oninit({ attrs: { game, session } }) {
    this.game = game;
    this.session = session;
  }

  // Prepare game players by creating new players (if necessary) and deciding
  // which player has the starting move
  setPlayers(gameType) {
    if (this.game.players.length > 0) {
      // Reset new games before choosing number of players (no need to reset
      // the very first game)
      this.game.resetGame();
    }
    this.game.setPlayers(gameType);
  }

  startGame(newStartingPlayer) {
    this.game.startGame({
      startingPlayer: newStartingPlayer
    });
  }

  endGame() {
    this.game.endGame();
  }

  createNewPlayer() {
    this.session.status = 'newPlayer';
  }

  setNewPlayerName(inputEvent) {
    this.newPlayerName = inputEvent.target.value;
    inputEvent.redraw = false;
  }

  submitNewPlayer(submitEvent, roomCode) {
    submitEvent.preventDefault();
    if (roomCode) {
      this.addNewPlayerToGame(roomCode);
    } else {
      this.startOnlineGame();
    }
  }

  addNewPlayerToGame(roomCode) {
    this.session.status = 'connecting';
    let submittedPlayer = { name: this.newPlayerName, color: 'blue' };
    this.session.emit('add-player', { roomCode, player: submittedPlayer }, ({ game, localPlayer }) => {
      this.game.restoreFromServer({ game, localPlayer });
      m.redraw();
    });
  }

  startOnlineGame() {
    this.session.connect();
    this.session.on('connect', () => {
      // Construct a placeholder player with the name we entered and the default
      // first player color
      let submittedPlayer = { name: this.newPlayerName, color: 'red' };
      // Request a new room and retrieve the room code returned from the server
      this.session.emit('open-room', { player: submittedPlayer }, ({ roomCode, game, localPlayer }) => {
        this.game.restoreFromServer({ game, localPlayer });
        console.log('new room', roomCode);
        m.route.set(`/room/${roomCode}`);
      });
      // When P2 joins, automatically update P1's screen
      this.session.on('add-player', ({ game, localPlayer }) => {
        this.game.restoreFromServer({ game, localPlayer });
        m.redraw();
      });
    });
  }

  configureCopyControl({ dom }) {
    this.shareLinkCopier = new ClipboardJS(dom);
    this.copyStatusDuration = 1000;
    this.shareLinkCopier.on('success', () => {
      this.copyStatus = 'Copied!';
      this.copyStatusFlash = true;
      m.redraw();
      // Reset status message after a second or two
      clearTimeout(this.copyStatusTimer);
      this.copyStatusTimer = setTimeout(() => {
        this.copyStatus = null;
        this.copyStatusFlash = false;
        m.redraw();
      }, this.copyStatusDuration);
    });
  }

  view({ attrs: { roomCode } }) {
    return m('div#game-dashboard', [
      m('p#game-message',
        // If the current player needs to enter a name
        this.session.status === 'newPlayer' ?
          'Enter your player name:' :
        this.session.status === 'waitingForPlayers' ?
          [
            'Waiting for other player...',
            m('div#share-controls', [
              m('input[type=text]#share-link', {
                value: window.location.href,
                onclick: ({ target }) => target.select()
              }),
              m('button#copy-share-link', {
                'data-clipboard-text': window.location.href,
                oncreate: ({ dom }) => this.configureCopyControl({ dom })
              }, 'Copy'),
              m('span#share-link-copy-status', {
                class: classNames({ 'copy-status-flash': this.copyStatusFlash })
              }, this.copyStatus)
            ])
          ] :
        this.session.status === 'connecting' ?
          'Connecting to server...' :
        this.session.status === 'roomNotFound' ?
          'This room does not exist.' :
        // If user has not started any game yet
        this.game.players.length === 0 ?
          'Welcome! How many players?' :
        // If a game is in progress
        this.game.currentPlayer ?
          `${this.game.currentPlayer.name}, your turn!` :
        // If a player wins the game
        this.game.winner ?
          `${this.game.winner.name} wins! Play again?` :
        // If the grid is completely full
        this.game.grid.checkIfFull() ?
          'We\'ll call it a draw! Play again?' :
        // If the user just chose a number of players for the game to be started
        !this.session.socket && this.game.type !== null ?
          'Which player should start first?' :
        // Otherwise, if game was ended manually by the user
        'Game ended. Play again?'
      ),
      // If game is in progress, allow user to end game at any time
      this.game.inProgress ? [
        m('button', { onclick: () => this.endGame() }, 'End Game')
      ] :
      this.session.status === 'newPlayer' ? [
        m('form', {
          onsubmit: (submitEvent) => this.submitNewPlayer(submitEvent, roomCode)
        }, [
          m('input[type=text]#new-player-name', {
            name: 'new-player-name',
            autofocus: true,
            oninput: (inputEvent) => this.setNewPlayerName(inputEvent)
          }),
          m('button[type=submit]', roomCode ? 'Join Game' : 'Start Game')
        ])
      ] :
      !this.session.socket ? [
        // If number of players has been chosen, ask user to choose starting player
        this.game.type !== null ?
          this.game.players.map((player) => {
            return m('button', {
              onclick: () => this.startGame(player)
            }, player.name);
          }) :
          // Select a number of human players
          !roomCode ? [
            m('button', {
              onclick: () => this.setPlayers({ gameType: '1P' })
            }, '1 Player'),
            m('button', {
              onclick: () => this.setPlayers({ gameType: '2P' })
            }, '2 Players'),
            m('button', {
              onclick: () => this.createNewPlayer()
            }, 'Online')
          ] : null
        ] : null
    ]);
  }

}

export default DashboardComponent;
<commit_msg>Replace !this.session.socket check with !roomCode<commit_after>import m from 'mithril';
import ClipboardJS from 'clipboard';
import classNames from '../classnames.js';

// The area of the game UI consisting of game UI controls and status messages
class DashboardComponent {

  oninit({ attrs: { game, session } }) {
    this.game = game;
    this.session = session;
  }

  // Prepare game players by creating new players (if necessary) and deciding
  // which player has the starting move
  setPlayers(gameType) {
    if (this.game.players.length > 0) {
      // Reset new games before choosing number of players (no need to reset
      // the very first game)
      this.game.resetGame();
    }
    this.game.setPlayers(gameType);
  }

  startGame(newStartingPlayer) {
    this.game.startGame({
      startingPlayer: newStartingPlayer
    });
  }

  endGame() {
    this.game.endGame();
  }

  createNewPlayer() {
    this.session.status = 'newPlayer';
  }

  setNewPlayerName(inputEvent) {
    this.newPlayerName = inputEvent.target.value;
    inputEvent.redraw = false;
  }

  submitNewPlayer(submitEvent, roomCode) {
    submitEvent.preventDefault();
    if (roomCode) {
      this.addNewPlayerToGame(roomCode);
    } else {
      this.startOnlineGame();
    }
  }

  addNewPlayerToGame(roomCode) {
    this.session.status = 'connecting';
    let submittedPlayer = { name: this.newPlayerName, color: 'blue' };
    this.session.emit('add-player', { roomCode, player: submittedPlayer }, ({ game, localPlayer }) => {
      this.game.restoreFromServer({ game, localPlayer });
      m.redraw();
    });
  }

  startOnlineGame() {
    this.session.connect();
    this.session.on('connect', () => {
      // Construct a placeholder player with the name we entered and the default
      // first player color
      let submittedPlayer = { name: this.newPlayerName, color: 'red' };
      // Request a new room and retrieve the room code returned from the server
      this.session.emit('open-room', { player: submittedPlayer }, ({ roomCode, game, localPlayer }) => {
        this.game.restoreFromServer({ game, localPlayer });
        console.log('new room', roomCode);
        m.route.set(`/room/${roomCode}`);
      });
      // When P2 joins, automatically update P1's screen
      this.session.on('add-player', ({ game, localPlayer }) => {
        this.game.restoreFromServer({ game, localPlayer });
        m.redraw();
      });
    });
  }

  configureCopyControl({ dom }) {
    this.shareLinkCopier = new ClipboardJS(dom);
    this.copyStatusDuration = 1000;
    this.shareLinkCopier.on('success', () => {
      this.copyStatus = 'Copied!';
      this.copyStatusFlash = true;
      m.redraw();
      // Reset status message after a second or two
      clearTimeout(this.copyStatusTimer);
      this.copyStatusTimer = setTimeout(() => {
        this.copyStatus = null;
        this.copyStatusFlash = false;
        m.redraw();
      }, this.copyStatusDuration);
    });
  }

  view({ attrs: { roomCode } }) {
    return m('div#game-dashboard', [
      m('p#game-message',
        // If the current player needs to enter a name
        this.session.status === 'newPlayer' ?
          'Enter your player name:' :
        this.session.status === 'waitingForPlayers' ?
          [
            'Waiting for other player...',
            m('div#share-controls', [
              m('input[type=text]#share-link', {
                value: window.location.href,
                onclick: ({ target }) => target.select()
              }),
              m('button#copy-share-link', {
                'data-clipboard-text': window.location.href,
                oncreate: ({ dom }) => this.configureCopyControl({ dom })
              }, 'Copy'),
              m('span#share-link-copy-status', {
                class: classNames({ 'copy-status-flash': this.copyStatusFlash })
              }, this.copyStatus)
            ])
          ] :
        this.session.status === 'connecting' ?
          'Connecting to server...' :
        this.session.status === 'roomNotFound' ?
          'This room does not exist.' :
        // If user has not started any game yet
        this.game.players.length === 0 ?
          'Welcome! How many players?' :
        // If a game is in progress
        this.game.currentPlayer ?
          `${this.game.currentPlayer.name}, your turn!` :
        // If a player wins the game
        this.game.winner ?
          `${this.game.winner.name} wins! Play again?` :
        // If the grid is completely full
        this.game.grid.checkIfFull() ?
          'We\'ll call it a draw! Play again?' :
        // If the user just chose a number of players for the game to be started
        !roomCode && this.game.type !== null ?
          'Which player should start first?' :
        // Otherwise, if game was ended manually by the user
        'Game ended. Play again?'
      ),
      // If game is in progress, allow user to end game at any time
      this.game.inProgress ? [
        m('button', { onclick: () => this.endGame() }, 'End Game')
      ] :
      this.session.status === 'newPlayer' ? [
        m('form', {
          onsubmit: (submitEvent) => this.submitNewPlayer(submitEvent, roomCode)
        }, [
          m('input[type=text]#new-player-name', {
            name: 'new-player-name',
            autofocus: true,
            oninput: (inputEvent) => this.setNewPlayerName(inputEvent)
          }),
          m('button[type=submit]', roomCode ? 'Join Game' : 'Start Game')
        ])
      ] :
      !roomCode ? [
        // If number of players has been chosen, ask user to choose starting player
        this.game.type !== null ?
          this.game.players.map((player) => {
            return m('button', {
              onclick: () => this.startGame(player)
            }, player.name);
          }) : [
            // Select a number of human players
            m('button', {
              onclick: () => this.setPlayers({ gameType: '1P' })
            }, '1 Player'),
            m('button', {
              onclick: () => this.setPlayers({ gameType: '2P' })
            }, '2 Players'),
            m('button', {
              onclick: () => this.createNewPlayer()
            }, 'Online')
          ]
        ] : null
    ]);
  }

}

export default DashboardComponent;
<|endoftext|>


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

const decoder = new TextDecoder("utf-8");

const buildEndpoint = async function buildEndpoint() {
  const [secret] = Deno.args;
  const stdinBuf = await Deno.readAll(Deno.stdin);
  const [url, star] = decoder.decode(stdinBuf).split("***");
  const encodedUrl = encodeURIComponent(url);
  let endpoint =
    `https://alec-reads.glitch.me/read?secret=${secret}&url=${encodedUrl}`;
  if (star) {
    endpoint += "&star=%20";
    if (star !== "nocomment") {
      endpoint += star;
    }
  }
  return endpoint;
};

const main = async function main() {
  const endpoint = await buildEndpoint();
  try {
    const res = await fetch(endpoint, { method: "POST" });
    console.log(res.statusText);
  } catch (err) {
    console.log(err);
  }
};

main();
<commit_msg>Encode a URI component<commit_after>#!/usr/bin/env deno

const decoder = new TextDecoder("utf-8");

const buildEndpoint = async function buildEndpoint() {
  const [secret] = Deno.args;
  const stdinBuf = await Deno.readAll(Deno.stdin);
  const [url, star] = decoder.decode(stdinBuf).split("***");
  const encodedUrl = encodeURIComponent(url);
  let endpoint =
    `https://alec-reads.glitch.me/read?secret=${secret}&url=${encodedUrl}`;
  if (star) {
    endpoint += "&star=%20";
    if (star !== "nocomment") {
      endpoint += encodeURIComponent(star);
    }
  }
  return endpoint;
};

const main = async function main() {
  const endpoint = await buildEndpoint();
  try {
    const res = await fetch(endpoint, { method: "POST" });
    console.log(res.statusText);
  } catch (err) {
    console.log(err);
  }
};

main();
<|endoftext|>


<commit_before>import { Button } from './Widgets';

export default class Ready extends React.Component {
    ready(r) {
        ws.send({cmd: r ? 'ready' : 'not_ready'});
    }
    render() {
        const r = this.ready;
        const btn =
        !this.props.ready ?
            <Button bg="green" onClick={r.bind(this, true)}>
                {this.props.readyText ? this.props.readyText : 'Ready'}
            </Button>
        : this.props.state === 'Waiting' ?
            <Button bg="red" onClick={r.bind(this, false)}>Not Ready</Button>
        :   <Button bg="green">Waiting...</Button>;
        return btn;
    }
}
<commit_msg>Change ready button to be a gradient to stand out<commit_after>import { Button } from './Widgets';

export default class Ready extends React.Component {
    ready(r) {
        ws.send({cmd: r ? 'ready' : 'not_ready'});
    }
    render() {
        const r = this.ready;
        const btn =
        !this.props.ready ?
            <Button onClick={r.bind(this, true)}
                style={{background: "radial-gradient(circle, orange 40%, red)"}}>
              {this.props.readyText ? this.props.readyText : 'Ready'}
            </Button>
        : this.props.state === 'Waiting' ?
            <Button bg="red" onClick={r.bind(this, false)}>Not Ready</Button>
        :   <Button bg="green">Waiting...</Button>;
        return btn;
    }
}
<|endoftext|>


<commit_before>'use strict';

/* Main Controller  */

angular.module('septWebRadioControllers').controller('MainCtrl', ['$scope', 'applicationServices', 'Page', '$location', 'userServices',
  function ($scope, applicationServices, Page, $location, userServices) {

    $scope.connexionButtonLabel = undefined;
    $scope.user = userServices.getUser();
    $scope.userServices = userServices;
    $scope.Page = Page;

    $scope.$watch('userServices.user', function (newValue, oldValue) {
      if (newValue !== oldValue) {
        console.log('new value');
        $scope.user = newValue;
      }
    });

    applicationServices.getInitApplication().then(function (data) {
      //$scope.user = data;

      // Check if the user is connected
      if (data) {
        // The user is connected
      }
      $scope.connexionButtonLabel = applicationServices.getConnexionLabel();
    });

    $scope.logInLogOutClick = function () {
      applicationServices.logInLogOut().then(function (label) {
        $scope.connexionButtonLabel = label;
      });
    };

    $scope.go = function (path) {
      $location.path(path);
    };

    $scope.logOutClick = function () {
      userServices.logOut();
    };
  }]
);<commit_msg>Correct console.log error<commit_after>'use strict';

/* Main Controller  */

angular.module('septWebRadioControllers').controller('MainCtrl', ['$scope', 'applicationServices', 'Page', '$location', 'userServices',
  function ($scope, applicationServices, Page, $location, userServices) {

    $scope.connexionButtonLabel = undefined;
    $scope.user = userServices.getUser();
    $scope.userServices = userServices;
    $scope.Page = Page;

    applicationServices.getInitApplication().then(function (data) {
      //$scope.user = data;

      // Check if the user is connected
      if (data) {
        // The user is connected
      }
      $scope.connexionButtonLabel = applicationServices.getConnexionLabel();
    });

    $scope.logInLogOutClick = function () {
      applicationServices.logInLogOut().then(function (label) {
        $scope.connexionButtonLabel = label;
      });
    };

    $scope.go = function (path) {
      $location.path(path);
    };

    $scope.logOutClick = function () {
      userServices.logOut();
    };
  }]
);<|endoftext|>


<commit_before>import React from 'react'
import GenericForm from '../genericform'
import Loading from '../loading'

let Channel=React.createClass({
  getInitialState(){
    console.log(this.props)
    this.props.onEnableChange(this.props.channel.is_active)
    return {
      active: this.props.channel.is_active
    }
  },
  componentDidMount(){
    $(this.refs.enable).checkbox({
      onChecked: () =>{
        this.setState({ active: true })
        this.props.onEnableChange(true)
      },
      onUnchecked: () =>{
        this.setState({ active: false })
        this.props.onEnableChange(false)
      },
      onChange(){ console.log(3) },
    })
  },
  render(){
    const props=this.props
    console.log(this.props)
    console.log(this.state)
    return (

{props.channel.name}

          <input type="checkbox" name="active" defaultChecked={this.state.active}/>
          {this.state.active ? "Active" : "Disabled"}

{props.channel.description}

        <GenericForm
          fields={props.channel.fields}
          updateForm={(data) => props.updateForm(data)}
          />

    )
  }
})

function Notifications(props){
  if (!props.channels)
    return (
      <Loading>Notification channels</Loading>
    )
  console.log(props.channels)
  return (

Communication Channels

      {props.channels.map( (c) => (
        <Channel
          key={c.channel} channel={c}
          updateForm={(data) => props.updateForm(c.channel, data)}
          onEnableChange={(state) => props.updateForm(c.channel+"/active", {is_active: state})}
          />
      ))}

  )
}

export default Notifications
<commit_msg>Some space to notifications at use profile.<commit_after>import React from 'react'
import GenericForm from '../genericform'
import Loading from '../loading'

let Channel=React.createClass({
  getInitialState(){
    console.log(this.props)
    this.props.onEnableChange(this.props.channel.is_active)
    return {
      active: this.props.channel.is_active
    }
  },
  componentDidMount(){
    $(this.refs.enable).checkbox({
      onChecked: () =>{
        this.setState({ active: true })
        this.props.onEnableChange(true)
      },
      onUnchecked: () =>{
        this.setState({ active: false })
        this.props.onEnableChange(false)
      },
      onChange(){ console.log(3) },
    })
  },
  render(){
    const props=this.props
    console.log(this.props)
    console.log(this.state)
    return (

{props.channel.name}

          <input type="checkbox" name="active" defaultChecked={this.state.active}/>
          {this.state.active ? "Active" : "Disabled"}

{props.channel.description}

        <GenericForm
          fields={props.channel.fields}
          updateForm={(data) => props.updateForm(data)}
          />

    )
  }
})

function Notifications(props){
  if (!props.channels)
    return (
      <Loading>Notification channels</Loading>
    )
  console.log(props.channels)
  return (

Communication Channels

      {props.channels.map( (c) => (
        <Channel
          key={c.channel} channel={c}
          updateForm={(data) => props.updateForm(c.channel, data)}
          onEnableChange={(state) => props.updateForm(c.channel+"/active", {is_active: state})}
          />
      ))}

  )
}

export default Notifications
<|endoftext|>


<commit_before>#! /usr/bin/env node
/* eslint-disable camelcase */
console.log(`PR: ${process.env.TRAVIS_PULL_REQUEST}`);
const github = require('octonode');
const normalizeUrl = require('normalize-url');
const spawn = require('cross-spawn');
const travisAfterAll = require('travis-after-all');
const urlRegex = require('url-regex');
const argv = require('yargs').argv;

const nowCli = require.resolve('now/download/dist/now');

if (!process.env.CI || !process.env.TRAVIS) {
  throw new Error('Could not detect Travis CI environment');
}

const githubToken = process.env.GH_TOKEN;
const nowToken = process.env.NOW_TOKEN;

if (!githubToken) {
  throw new Error('Missing required environment variable GH_TOKEN');
}

if (!nowToken) {
  throw new Error('Missing required environment variable NOW_TOKEN');
}

console.log(`PR: ${process.env.TRAVIS_PULL_REQUEST}`);

const client = github.client(githubToken);
const ghRepo = client.repo(process.env.TRAVIS_REPO_SLUG);
let ghPR;

if (process.env.TRAVIS_PULL_REQUEST) {
  ghPR = client.pr(
    process.env.TRAVIS_REPO_SLUG,
    process.env.TRAVIS_PULL_REQUEST,
  );
}

function noop() {}

function getUrl(content) {
  const urls = content.match(urlRegex()) || [];
  console.log(`PR: ${process.env.TRAVIS_PULL_REQUEST}`);
  return urls.map(url => normalizeUrl(url.trim().replace(/\.+$/, '')))[0];
}

function deploy(context, sha) {
  ghRepo.status(
    sha,
    {
      context,
      state: 'pending',
      description: `Δ Now ${context} deployment pending`,
    },
    noop,
  );

  const args = [
    '--token',
    nowToken,
    '--team',
    'coderplex',
    '--no-clipboard',
    '-n',
    'coderplex-app',
  ];
  const alias = context === 'production' && process.env.NOW_ALIAS;
  let stdout = '';

  if (alias) {
    args.push(...['--alias', alias]);
  }

  if (argv.p || argv.public) {
    args.push(...['-p']);
  }

  if (argv.folder) {
    args.push(argv.folder);
  }

  const child = spawn(nowCli, args);

  if (!alias) {
    child.stdout.on('data', data => {
      stdout += data;
    });
  }

  child.on('error', err => {
    console.error(err);
    ghRepo.status(
      sha,
      {
        context,
        state: 'error',
        description: `Δ Now ${context} deployment failed. See Travis logs for details.`,
      },
      noop,
    );
  });

  child.on('close', () => {
    const target_url = alias || getUrl(stdout);
    console.log(`PR: ${process.env.TRAVIS_PULL_REQUEST}`);
    if (ghPR) {
      const comment = `(Note: This is autogenerated through Travis build) New Staging URL : ${target_url}`;
      console.log(comment);
      ghPR.createComment(
        {
          body: comment,
          in_reply_to: 1,
        },
        (err, res) => {
          console.log(err, res);
        },
      );
    } else {
      console.log('No PR found');
    }
    ghRepo.status(
      sha,
      {
        context,
        target_url,
        state: 'success',
        description: `Δ Now ${context} deployment complete`,
      },
      noop,
    );
  });
}

travisAfterAll((code, err) => {
  // Don't do anything if there was an error of if the build returned a failing code
  if (err || code) {
    return;
  }

  switch (process.env.TRAVIS_EVENT_TYPE) {
    case 'pull_request':
      return deploy('staging', process.env.TRAVIS_PULL_REQUEST_SHA);
    case 'push':
      return deploy('production', process.env.TRAVIS_COMMIT);
    default:
      return '';
  }
});
<commit_msg>test again if comment works from travis<commit_after>#! /usr/bin/env node
/* eslint-disable camelcase */
const github = require('octonode');
const normalizeUrl = require('normalize-url');
const spawn = require('cross-spawn');
const travisAfterAll = require('travis-after-all');
const urlRegex = require('url-regex');
const argv = require('yargs').argv;

const nowCli = require.resolve('now/download/dist/now');

if (!process.env.CI || !process.env.TRAVIS) {
  throw new Error('Could not detect Travis CI environment');
}

const githubToken = process.env.GH_TOKEN;
const nowToken = process.env.NOW_TOKEN;

if (!githubToken) {
  throw new Error('Missing required environment variable GH_TOKEN');
}

if (!nowToken) {
  throw new Error('Missing required environment variable NOW_TOKEN');
}

console.log(process.env.TRAVIS_PULL_REQUEST);

const client = github.client(githubToken);
const ghRepo = client.repo(process.env.TRAVIS_REPO_SLUG);
let ghPR;

if (process.env.TRAVIS_PULL_REQUEST) {
  ghPR = client.pr(
    process.env.TRAVIS_REPO_SLUG,
    process.env.TRAVIS_PULL_REQUEST,
  );
}

function noop() {}

function getUrl(content) {
  const urls = content.match(urlRegex()) || [];

  return urls.map(url => normalizeUrl(url.trim().replace(/\.+$/, '')))[0];
}

function deploy(context, sha) {
  ghRepo.status(
    sha,
    {
      context,
      state: 'pending',
      description: `Δ Now ${context} deployment pending`,
    },
    noop,
  );

  const args = [
    '--token',
    nowToken,
    '--team',
    'coderplex',
    '--no-clipboard',
    '-n',
    'coderplex-app',
  ];
  const alias = context === 'production' && process.env.NOW_ALIAS;
  let stdout = '';

  if (alias) {
    args.push(...['--alias', alias]);
  }

  if (argv.p || argv.public) {
    args.push(...['-p']);
  }

  if (argv.folder) {
    args.push(argv.folder);
  }

  const child = spawn(nowCli, args);

  if (!alias) {
    child.stdout.on('data', data => {
      stdout += data;
    });
  }

  child.on('error', err => {
    console.error(err);
    ghRepo.status(
      sha,
      {
        context,
        state: 'error',
        description: `Δ Now ${context} deployment failed. See Travis logs for details.`,
      },
      noop,
    );
  });

  child.on('close', () => {
    const target_url = alias || getUrl(stdout);
    if (ghPR) {
      const comment = `
      ### Δ Now ${context} deployment complete
      - ✅ **Build Passed**
      - 🚀 **Staging URL** : ${target_url}
      ---
      Note: **This is autogenerated through Travis build**
    `;
      ghPR.createComment(
        {
          body: comment,
          in_reply_to: 147402206,
        },
        (err, res) => {
          console.log(err, res);
        },
      );
    } else {
      console.log('No PR found');
    }
    ghRepo.status(
      sha,
      {
        context,
        target_url,
        state: 'success',
        description: `Δ Now ${context} deployment complete`,
      },
      noop,
    );
  });
}

travisAfterAll((code, err) => {
  // Don't do anything if there was an error of if the build returned a failing code
  if (err || code) {
    return;
  }

  switch (process.env.TRAVIS_EVENT_TYPE) {
    case 'pull_request':
      return deploy('staging', process.env.TRAVIS_PULL_REQUEST_SHA);
    case 'push':
      return deploy('production', process.env.TRAVIS_COMMIT);
    default:
      return '';
  }
});
<|endoftext|>