<commit_before>var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.width = canvas.width;
context.height = canvas.height;
context.globalCompositeOperation = "destination-over";

var currentState = null;

var pauseKey = "p";
var canPauseOrResume = true;
var gamePaused = false;

function init() {
  setInterval(tick, 60);
}

function tick() {
  if (gamePaused) {
    currentState.draw();

    if (isDown(pauseKey))
      pauseOrResumeGame();

    // TODO Draw Pause/Play huge icon on top
  } else {
    if (isDown(pauseKey))
      pauseOrResumeGame();

    currentState.update();
    currentState.draw();
  }
}

function pauseOrResumeGame() {
  if (canPauseOrResume) {
    gamePaused = !gamePaused;

    setTimeout(function() {
      canPauseOrResume = true;
    }, 1000);

    canPauseOrResume = false;
  }
}

function switchState(newState) {
  newState.setup();
  return currentState = newState;
}

function drawCircle(x, y, radius) {
  context.beginPath();
  context.arc(x, y, radius, 0, Math.PI * 2, false);
  context.stroke();
}

function drawRectangle(x, y, width, height, color) {
  if (color) {
    context.fillStyle = color;
    context.fillRect(x, y, width, height);
    context.fillStyle = "#FFFFFF";
  } else {
    context.fillRect(x, y, width, height);
  }
}

function clearCanvas() {
  context.clearRect(0, 0, context.width, context.height);
}

/*************************************** SPRITE */
Sprite = (function() {
  function constructor(image, x, y) {
    this.image = new Image();
    this.image.src = image;
    this.x = x;
    this.y = y;
  }

  constructor.prototype = {
    draw: function() {
      context.drawImage(this.image, this.x, this.y);
    }
  }

  return constructor;
})();

SpriteList = (function() {
  function constructor() {
    this.sprites = [];
  }

  constructor.prototype = {
    draw: function() {
      for (var i = 0; i < this.sprites.length; i++) {
        this.sprites[i].draw();
      }
    },

    push: function(newSprite) {
      this.sprites.push(newSprite);
    }
  }

  return constructor;
})();

/*function loadImage(imageName) {
  var image = new Image();
  image.src = imageName;
}*/

/*************************************** INPUT */
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);

var keyCodeToString = [];
keyCodeToString[8] = "backspace";
keyCodeToString[9] = "tab";
keyCodeToString[13] = "enter";
keyCodeToString[16] = "shift";
keyCodeToString[17] = "ctrl";
keyCodeToString[18] = "alt";
keyCodeToString[19] = "pause";
keyCodeToString[20] = "capslock";
keyCodeToString[27] = "esc";
keyCodeToString[32] = "space";
keyCodeToString[33] = "pageup";
keyCodeToString[34] = "pagedown";
keyCodeToString[35] = "end";
keyCodeToString[36] = "home";
keyCodeToString[37] = "left";
keyCodeToString[38] = "up";
keyCodeToString[39] = "right";
keyCodeToString[40] = "down";
keyCodeToString[45] = "insert";
keyCodeToString[46] = "delete";

keyCodeToString[91] = "leftwindowkey";
keyCodeToString[92] = "rightwindowkey";
keyCodeToString[93] = "selectkey";
keyCodeToString[106] = "multiply";
keyCodeToString[107] = "add";
keyCodeToString[109] = "subtract";
keyCodeToString[110] = "decimalpoint";
keyCodeToString[111] = "divide";

keyCodeToString[144] = "numlock";
keyCodeToString[145] = "scrollock";
keyCodeToString[186] = "semicolon";
keyCodeToString[187] = "equalsign";
keyCodeToString[188] = "comma";
keyCodeToString[189] = "dash";
keyCodeToString[190] = "period";
keyCodeToString[191] = "forwardslash";
keyCodeToString[192] = "graveaccent";
keyCodeToString[219] = "openbracket";
keyCodeToString[220] = "backslash";
keyCodeToString[221] = "closebracket";
keyCodeToString[222] = "singlequote";

var numpadKeys = ["numpad1", "numpad2", "numpad3", "numpad4", "numpad5",
                  "numpad6", "numpad7", "numpad8", "numpad9"];

var numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
               "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
               "u", "v", "w", "x", "y", "z"];

for (var i = 0; numbers[i]; i++) { keyCodeToString[48 + i] = numbers[i]; }
for (var i = 0; letters[i]; i++) { keyCodeToString[65 + i] = letters[i]; }
for (var i = 0; numpadKeys[i]; i++) { keyCodeToString[96 + i] = numpadKeys[i]; }

var pressedKeys = [];
var preventedKeys = [];

function preventKeys(keys) {
  preventedKeys = keys;
}

function handleKeyDown(e) {
  var event = (e) ? e : window.event;
  var name = keyCodeToString[event.keyCode];
  pressedKeys[name] = true;

  if (preventedKeys[name])
    e.preventDefault();
}

function handleKeyUp(e) {
  var event = (e) ? e : window.event;
  var name = keyCodeToString[event.keyCode];
  pressedKeys[name] = false;

  if (preventedKeys[name])
    e.preventDefault();
}

function isDown(name) {
  if (pressedKeys[name])
    return true;
}
<commit_msg>set interval to update at 60 fps instead of 16.6 fps<commit_after>var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.width = canvas.width;
context.height = canvas.height;
context.globalCompositeOperation = "destination-over";

var currentState = null;

var pauseKey = "p";
var canPauseOrResume = true;
var gamePaused = false;

function init() {
  setInterval(tick, 16.666666666);
}

function tick() {
  if (gamePaused) {
    currentState.draw();

    if (isDown(pauseKey))
      pauseOrResumeGame();

    // TODO Draw Pause/Play huge icon on top
  } else {
    if (isDown(pauseKey))
      pauseOrResumeGame();

    currentState.update();
    currentState.draw();
  }
}

function pauseOrResumeGame() {
  if (canPauseOrResume) {
    gamePaused = !gamePaused;

    setTimeout(function() {
      canPauseOrResume = true;
    }, 1000);

    canPauseOrResume = false;
  }
}

function switchState(newState) {
  newState.setup();
  return currentState = newState;
}

function drawCircle(x, y, radius) {
  context.beginPath();
  context.arc(x, y, radius, 0, Math.PI * 2, false);
  context.stroke();
}

function drawRectangle(x, y, width, height, color) {
  if (color) {
    context.fillStyle = color;
    context.fillRect(x, y, width, height);
    context.fillStyle = "#FFFFFF";
  } else {
    context.fillRect(x, y, width, height);
  }
}

function clearCanvas() {
  context.clearRect(0, 0, context.width, context.height);
}

/*************************************** SPRITE */
Sprite = (function() {
  function constructor(image, x, y) {
    this.image = new Image();
    this.image.src = image;
    this.x = x;
    this.y = y;
  }

  constructor.prototype = {
    draw: function() {
      context.drawImage(this.image, this.x, this.y);
    }
  }

  return constructor;
})();

SpriteList = (function() {
  function constructor() {
    this.sprites = [];
  }

  constructor.prototype = {
    draw: function() {
      for (var i = 0; i < this.sprites.length; i++) {
        this.sprites[i].draw();
      }
    },

    push: function(newSprite) {
      this.sprites.push(newSprite);
    }
  }

  return constructor;
})();

/*function loadImage(imageName) {
  var image = new Image();
  image.src = imageName;
}*/

/*************************************** INPUT */
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);

var keyCodeToString = [];
keyCodeToString[8] = "backspace";
keyCodeToString[9] = "tab";
keyCodeToString[13] = "enter";
keyCodeToString[16] = "shift";
keyCodeToString[17] = "ctrl";
keyCodeToString[18] = "alt";
keyCodeToString[19] = "pause";
keyCodeToString[20] = "capslock";
keyCodeToString[27] = "esc";
keyCodeToString[32] = "space";
keyCodeToString[33] = "pageup";
keyCodeToString[34] = "pagedown";
keyCodeToString[35] = "end";
keyCodeToString[36] = "home";
keyCodeToString[37] = "left";
keyCodeToString[38] = "up";
keyCodeToString[39] = "right";
keyCodeToString[40] = "down";
keyCodeToString[45] = "insert";
keyCodeToString[46] = "delete";

keyCodeToString[91] = "leftwindowkey";
keyCodeToString[92] = "rightwindowkey";
keyCodeToString[93] = "selectkey";
keyCodeToString[106] = "multiply";
keyCodeToString[107] = "add";
keyCodeToString[109] = "subtract";
keyCodeToString[110] = "decimalpoint";
keyCodeToString[111] = "divide";

keyCodeToString[144] = "numlock";
keyCodeToString[145] = "scrollock";
keyCodeToString[186] = "semicolon";
keyCodeToString[187] = "equalsign";
keyCodeToString[188] = "comma";
keyCodeToString[189] = "dash";
keyCodeToString[190] = "period";
keyCodeToString[191] = "forwardslash";
keyCodeToString[192] = "graveaccent";
keyCodeToString[219] = "openbracket";
keyCodeToString[220] = "backslash";
keyCodeToString[221] = "closebracket";
keyCodeToString[222] = "singlequote";

var numpadKeys = ["numpad1", "numpad2", "numpad3", "numpad4", "numpad5",
                  "numpad6", "numpad7", "numpad8", "numpad9"];

var numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
               "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
               "u", "v", "w", "x", "y", "z"];

for (var i = 0; numbers[i]; i++) { keyCodeToString[48 + i] = numbers[i]; }
for (var i = 0; letters[i]; i++) { keyCodeToString[65 + i] = letters[i]; }
for (var i = 0; numpadKeys[i]; i++) { keyCodeToString[96 + i] = numpadKeys[i]; }

var pressedKeys = [];
var preventedKeys = [];

function preventKeys(keys) {
  preventedKeys = keys;
}

function handleKeyDown(e) {
  var event = (e) ? e : window.event;
  var name = keyCodeToString[event.keyCode];
  pressedKeys[name] = true;

  if (preventedKeys[name])
    e.preventDefault();
}

function handleKeyUp(e) {
  var event = (e) ? e : window.event;
  var name = keyCodeToString[event.keyCode];
  pressedKeys[name] = false;

  if (preventedKeys[name])
    e.preventDefault();
}

function isDown(name) {
  if (pressedKeys[name])
    return true;
}
<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// 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.

/**
 * This application demonstrates how to perform basic operations on files with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

function main(bucketName = 'my-bucket', filename = 'test.txt') {
  // [START storage_generate_post_policy_url_v4]
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const bucketName = 'Name of a bucket, e.g. my-bucket';
  // const filename = 'File to access, e.g. file.txt';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  async function generateV4SignedPolicy() {
    const bucket = storage.bucket(bucketName);
    const file = bucket.file(filename);

    // These options will allow temporary uploading of a file
    // through an HTML form.
    const expires = Date.now() + 10 * 60 * 1000; //  10 minutes
    const options = {
      expires,
      fields: {'x-goog-meta-test': 'data'},
    };

    // Get a v4 signed policy for uploading file
    const [response] = await file.generateSignedPostPolicyV4(options);

    // Create an HTML form with the provided policy
    let output = `<form action='${response.url}' method='POST' enctype="multipart/form-data">\n`;
    // Include all fields returned in the HTML form as they're required
    for (const name of Object.keys(response.fields)) {
      const value = response.fields[name];
      output += `  <input name='${name}' value='${value}' type='hidden'/>\n`;
    }
    output += "  <input type='file' name='file'/>\n";
    output += "  <input type='submit' value='Upload File' name='submit'/>\n";
    output += '</form>';

    console.log(output);
  }

  generateV4SignedPolicy().catch(console.error);
  // [END storage_generate_post_policy_url_v4]
}
main(...process.argv.slice(2));
<commit_msg>fix: add whitespace to generateV4SignedPolicy (#1136)<commit_after>// Copyright 2020 Google LLC
//
// 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.

/**
 * This application demonstrates how to perform basic operations on files with
 * the Google Cloud Storage API.
 *
 * For more information, see the README.md under /storage and the documentation
 * at https://cloud.google.com/storage/docs.
 */

function main(bucketName = 'my-bucket', filename = 'test.txt') {
  // [START storage_generate_post_policy_url_v4]
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const bucketName = 'Name of a bucket, e.g. my-bucket';
  // const filename = 'File to access, e.g. file.txt';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  async function generateV4SignedPolicy() {
    const bucket = storage.bucket(bucketName);
    const file = bucket.file(filename);

    // These options will allow temporary uploading of a file
    // through an HTML form.
    const expires = Date.now() + 10 * 60 * 1000; //  10 minutes
    const options = {
      expires,
      fields: {'x-goog-meta-test': 'data'},
    };

    // Get a v4 signed policy for uploading file
    const [response] = await file.generateSignedPostPolicyV4(options);

    // Create an HTML form with the provided policy
    let output = `<form action='${response.url}' method='POST' enctype="multipart/form-data">\n`;
    // Include all fields returned in the HTML form as they're required
    for (const name of Object.keys(response.fields)) {
      const value = response.fields[name];
      output += `  <input name='${name}' value='${value}' type='hidden'/>\n`;
    }
    output += "  <input type='file' name='file'/>
\n";
    output +=
      "  <input type='submit' value='Upload File' name='submit'/>
\n";
    output += '</form>';

    console.log(output);
  }

  generateV4SignedPolicy().catch(console.error);
  // [END storage_generate_post_policy_url_v4]
}
main(...process.argv.slice(2));
<|endoftext|>


<commit_before>'use strict';

// To run the tests: $ mocha -R spec regtest/bitcoind.js

var path = require('path');
var index = require('..');
var log = index.log;

var chai = require('chai');
var bitcore = require('bitcore-lib');
var BN = bitcore.crypto.BN;
var async = require('async');
var rimraf = require('rimraf');
var bitcoind;

/* jshint unused: false */
var should = chai.should();
var assert = chai.assert;
var sinon = require('sinon');
var BitcoinRPC = require('bitcoind-rpc');
var transactionData = [];
var blockHashes = [];
var utxos;
var client;
var coinbasePrivateKey;
var privateKey = bitcore.PrivateKey();
var destKey = bitcore.PrivateKey();

describe('Bitcoind Functionality', function() {

  before(function(done) {
    this.timeout(30000);

    // Add the regtest network
    bitcore.Networks.enableRegtest();
    var regtestNetwork = bitcore.Networks.get('regtest');

    var datadir = __dirname + '/data';

    rimraf(datadir + '/regtest', function(err) {

      if (err) {
        throw err;
      }

      bitcoind = require('../').services.Bitcoin({
        spawn: {
          datadir: datadir,
          exec: path.resolve(__dirname, '../bin/bitcoind')
        },
        node: {
          network: regtestNetwork,
          getNetworkName: function() {
            return 'regtest';
          }
        }
      });

      bitcoind.on('error', function(err) {
        log.error('error="%s"', err.message);
      });

      log.info('Waiting for Bitcoin Core to initialize...');

      bitcoind.start(function() {
        log.info('Bitcoind started');

        client = new BitcoinRPC({
          protocol: 'http',
          host: '127.0.0.1',
          port: 30331,
          user: 'bitcoin',
          pass: 'local321',
          rejectUnauthorized: false
        });

        log.info('Generating 100 blocks...');

        // Generate enough blocks so that the initial coinbase transactions
        // can be spent.

        setImmediate(function() {
          client.generate(150, function(err, response) {
            if (err) {
              throw err;
            }
            blockHashes = response.result;

            log.info('Preparing test data...');

            // Get all of the unspent outputs
            client.listUnspent(0, 150, function(err, response) {
              utxos = response.result;

              async.mapSeries(utxos, function(utxo, next) {
                async.series([
                  function(finished) {
                    // Load all of the transactions for later testing
                    client.getTransaction(utxo.txid, function(err, txresponse) {
                      if (err) {
                        throw err;
                      }
                      // add to the list of transactions for testing later
                      transactionData.push(txresponse.result.hex);
                      finished();
                    });
                  },
                  function(finished) {
                    // Get the private key for each utxo
                    client.dumpPrivKey(utxo.address, function(err, privresponse) {
                      if (err) {
                        throw err;
                      }
                      utxo.privateKeyWIF = privresponse.result;
                      finished();
                    });
                  }
                ], next);
              }, function(err) {
                if (err) {
                  throw err;
                }
                done();
              });
            });
          });
        });
      });
    });
  });

  after(function(done) {
    this.timeout(20000);
    bitcoind.node.stopping = true;
    bitcoind.stop(function(err, result) {
      done();
    });
  });

  describe('get blocks by hash', function() {

    [0,1,2,3,5,6,7,8,9].forEach(function(i) {
      it('generated block ' + i, function(done) {
        bitcoind.getBlock(blockHashes[i], function(err, block) {
          if (err) {
            throw err;
          }
          should.exist(block);
          block.hash.should.equal(blockHashes[i]);
          done();
        });
      });
    });
  });

  describe('get blocks as buffers', function() {
    [0,1,2,3,5,6,7,8,9].forEach(function(i) {
      it('generated block ' + i, function(done) {
        bitcoind.getRawBlock(blockHashes[i], function(err, block) {
          if (err) {
            throw err;
          }
          should.exist(block);
          (block instanceof Buffer).should.equal(true);
          done();
        });
      });
    });
  });

  describe('get errors as error instances', function() {
    it('will wrap an rpc into a javascript error', function(done) {
      bitcoind.client.getBlock(1000000000, function(err, response) {
        var error = bitcoind._wrapRPCError(err);
        (error instanceof Error).should.equal(true);
        error.message.should.equal(err.message);
        error.code.should.equal(err.code);
        should.exist(error.stack);
        done();
      });
    });
  });

  describe('get blocks by height', function() {

    [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('generated block ' + i, function(done) {
        // add the genesis block
        var height = i + 1;
        bitcoind.getBlock(i + 1, function(err, block) {
          if (err) {
            throw err;
          }
          should.exist(block);
          block.hash.should.equal(blockHashes[i]);
          done();
        });
      });
    });

    it('will get error with number greater than tip', function(done) {
      bitcoind.getBlock(1000000000, function(err, response) {
        should.exist(err);
        err.code.should.equal(-8);
        done();
      });
    });

  });

  describe('get transactions by hash', function() {
    [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('for tx ' + i, function(done) {
        var txhex = transactionData[i];
        var tx = new bitcore.Transaction();
        tx.fromString(txhex);
        bitcoind.getTransaction(tx.hash, function(err, response) {
          if (err) {
            throw err;
          }
          assert(response.toString('hex') === txhex, 'incorrect tx data result');
          done();
        });
      });
    });

    it('will return error if the transaction does not exist', function(done) {
      var txid = '6226c407d0e9705bdd7158e60983e37d0f5d23529086d6672b07d9238d5aa618';
      bitcoind.getTransaction(txid, function(err, response) {
        should.exist(err);
        done();
      });
    });
  });

  describe('get transactions as buffers', function() {
    [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('for tx ' + i, function(done) {
        var txhex = transactionData[i];
        var tx = new bitcore.Transaction();
        tx.fromString(txhex);
        bitcoind.getRawTransaction(tx.hash, function(err, response) {
          if (err) {
            throw err;
          }
          response.should.be.instanceOf(Buffer);
          assert(response.toString('hex') === txhex, 'incorrect tx data result');
          done();
        });
      });
    });

    it('will return error if the transaction does not exist', function(done) {
      var txid = '6226c407d0e9705bdd7158e60983e37d0f5d23529086d6672b07d9238d5aa618';
      bitcoind.getRawTransaction(txid, function(err, response) {
        should.exist(err);
        done();
      });
    });
  });

  describe('get block header', function() {
    var expectedWork = new BN(6);
    [1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('generate block ' + i, function(done) {
        bitcoind.getBlockHeader(blockHashes[i], function(err, blockIndex) {
          if (err) {
            return done(err);
          }
          should.exist(blockIndex);
          should.exist(blockIndex.chainwork);
          var work = new BN(blockIndex.chainwork, 'hex');
          work.cmp(expectedWork).should.equal(0);
          expectedWork = expectedWork.add(new BN(2));
          should.exist(blockIndex.previousblockhash);
          blockIndex.hash.should.equal(blockHashes[i]);
          blockIndex.previousblockhash.should.equal(blockHashes[i - 1]);
          blockIndex.height.should.equal(i + 1);
          done();
        });
      });
    });
    it('will get null prevHash for the genesis block', function(done) {
      bitcoind.getBlockHeader(0, function(err, header) {
        if (err) {
          return done(err);
        }
        should.exist(header);
        should.equal(header.previousblockhash, undefined);
        done();
      });
    });
    it('will get error for block not found', function(done) {
      bitcoind.getBlockHeader('notahash', function(err, header) {
        should.exist(err);
        done();
      });
    });
  });

  describe('get block index by height', function() {
    var expectedWork = new BN(6);
    [2,3,4,5,6,7,8,9].forEach(function(i) {
      it('generate block ' + i, function() {
        bitcoind.getBlockHeader(i, function(err, header) {
          should.exist(header);
          should.exist(header.chainwork);
          var work = new BN(header.chainwork, 'hex');
          work.cmp(expectedWork).should.equal(0);
          expectedWork = expectedWork.add(new BN(2));
          should.exist(header.previousblockhash);
          header.hash.should.equal(blockHashes[i - 1]);
          header.previousblockhash.should.equal(blockHashes[i - 2]);
          header.height.should.equal(i);
        });
      });
    });
    it('will get error with number greater than tip', function(done) {
      bitcoind.getBlockHeader(100000, function(err, header) {
        should.exist(err);
        done();
      });
    });
  });

  describe('send transaction functionality', function() {

    it('will not error and return the transaction hash', function(done) {

      // create and sign the transaction
      var tx = bitcore.Transaction();
      tx.from(utxos[0]);
      tx.change(privateKey.toAddress());
      tx.to(destKey.toAddress(), utxos[0].amount * 1e8 - 1000);
      tx.sign(bitcore.PrivateKey.fromWIF(utxos[0].privateKeyWIF));

      // test sending the transaction
      bitcoind.sendTransaction(tx.serialize(), function(err, hash) {
        if (err) {
          return done(err);
        }
        hash.should.equal(tx.hash);
        done();
      });

    });

    it('will throw an error if an unsigned transaction is sent', function(done) {
      var tx = bitcore.Transaction();
      tx.from(utxos[1]);
      tx.change(privateKey.toAddress());
      tx.to(destKey.toAddress(), utxos[1].amount * 1e8 - 1000);
      bitcoind.sendTransaction(tx.uncheckedSerialize(), function(err, hash) {
        should.exist(err);
        (err instanceof Error).should.equal(true);
        should.not.exist(hash);
        done();
      });
    });

    it('will throw an error for unexpected types (tx decode failed)', function(done) {
      var garbage = new Buffer('abcdef', 'hex');
      bitcoind.sendTransaction(garbage, function(err, hash) {
        should.exist(err);
        should.not.exist(hash);
        var num = 23;
        bitcoind.sendTransaction(num, function(err, hash) {
          should.exist(err);
          (err instanceof Error).should.equal(true);
          should.not.exist(hash);
          done();
        });
      });
    });

    it('will emit "tx" events', function(done) {
      var tx = bitcore.Transaction();
      tx.from(utxos[2]);
      tx.change(privateKey.toAddress());
      tx.to(destKey.toAddress(), utxos[2].amount * 1e8 - 1000);
      tx.sign(bitcore.PrivateKey.fromWIF(utxos[2].privateKeyWIF));

      var serialized = tx.serialize();

      bitcoind.once('tx', function(buffer) {
        buffer.toString('hex').should.equal(serialized);
        done();
      });
      bitcoind.sendTransaction(serialized, function(err, hash) {
        if (err) {
          return done(err);
        }
        should.exist(hash);
      });
    });

  });

  describe('fee estimation', function() {
    it('will estimate fees', function(done) {
      bitcoind.estimateFee(1, function(err, fees) {
        if (err) {
          return done(err);
        }
        fees.should.equal(-1);
        done();
      });
    });
  });

  describe('tip updates', function() {
    it('will get an event when the tip is new', function(done) {
      this.timeout(4000);
      bitcoind.on('tip', function(height) {
        if (height === 151) {
          done();
        }
      });
      client.generate(1, function(err, response) {
        if (err) {
          throw err;
        }
      });
    });
  });

  describe('get transaction with block info', function() {
    it('should include tx with height and timestamp', function(done) {
      bitcoind.getTransactionWithBlockInfo(utxos[0].txid, function(err, tx) {
        if (err) {
          return done(err);
        }
        should.exist(tx.__height);
        tx.__height.should.be.a('number');
        should.exist(tx.__timestamp);
        should.exist(tx.__blockHash);
        done();
      });
    });
  });

  describe('#getInfo', function() {
    it('will get information', function(done) {
      bitcoind.getInfo(function(err, info) {
        if (err) {
          return done(err);
        }
        info.network.should.equal('regtest');
        should.exist(info);
        should.exist(info.version);
        should.exist(info.blocks);
        should.exist(info.timeoffset);
        should.exist(info.connections);
        should.exist(info.difficulty);
        should.exist(info.testnet);
        should.exist(info.relayfee);
        should.exist(info.errors);
        done();
      });
    });
  });

});
<commit_msg>test: bitcoind chainwork test<commit_after>'use strict';

// To run the tests: $ mocha -R spec regtest/bitcoind.js

var path = require('path');
var index = require('..');
var log = index.log;

var chai = require('chai');
var bitcore = require('bitcore-lib');
var BN = bitcore.crypto.BN;
var async = require('async');
var rimraf = require('rimraf');
var bitcoind;

/* jshint unused: false */
var should = chai.should();
var assert = chai.assert;
var sinon = require('sinon');
var BitcoinRPC = require('bitcoind-rpc');
var transactionData = [];
var blockHashes = [];
var utxos;
var client;
var coinbasePrivateKey;
var privateKey = bitcore.PrivateKey();
var destKey = bitcore.PrivateKey();

describe('Bitcoind Functionality', function() {

  before(function(done) {
    this.timeout(30000);

    // Add the regtest network
    bitcore.Networks.enableRegtest();
    var regtestNetwork = bitcore.Networks.get('regtest');

    var datadir = __dirname + '/data';

    rimraf(datadir + '/regtest', function(err) {

      if (err) {
        throw err;
      }

      bitcoind = require('../').services.Bitcoin({
        spawn: {
          datadir: datadir,
          exec: path.resolve(__dirname, '../bin/bitcoind')
        },
        node: {
          network: regtestNetwork,
          getNetworkName: function() {
            return 'regtest';
          }
        }
      });

      bitcoind.on('error', function(err) {
        log.error('error="%s"', err.message);
      });

      log.info('Waiting for Bitcoin Core to initialize...');

      bitcoind.start(function() {
        log.info('Bitcoind started');

        client = new BitcoinRPC({
          protocol: 'http',
          host: '127.0.0.1',
          port: 30331,
          user: 'bitcoin',
          pass: 'local321',
          rejectUnauthorized: false
        });

        log.info('Generating 100 blocks...');

        // Generate enough blocks so that the initial coinbase transactions
        // can be spent.

        setImmediate(function() {
          client.generate(150, function(err, response) {
            if (err) {
              throw err;
            }
            blockHashes = response.result;

            log.info('Preparing test data...');

            // Get all of the unspent outputs
            client.listUnspent(0, 150, function(err, response) {
              utxos = response.result;

              async.mapSeries(utxos, function(utxo, next) {
                async.series([
                  function(finished) {
                    // Load all of the transactions for later testing
                    client.getTransaction(utxo.txid, function(err, txresponse) {
                      if (err) {
                        throw err;
                      }
                      // add to the list of transactions for testing later
                      transactionData.push(txresponse.result.hex);
                      finished();
                    });
                  },
                  function(finished) {
                    // Get the private key for each utxo
                    client.dumpPrivKey(utxo.address, function(err, privresponse) {
                      if (err) {
                        throw err;
                      }
                      utxo.privateKeyWIF = privresponse.result;
                      finished();
                    });
                  }
                ], next);
              }, function(err) {
                if (err) {
                  throw err;
                }
                done();
              });
            });
          });
        });
      });
    });
  });

  after(function(done) {
    this.timeout(20000);
    bitcoind.node.stopping = true;
    bitcoind.stop(function(err, result) {
      done();
    });
  });

  describe('get blocks by hash', function() {

    [0,1,2,3,5,6,7,8,9].forEach(function(i) {
      it('generated block ' + i, function(done) {
        bitcoind.getBlock(blockHashes[i], function(err, block) {
          if (err) {
            throw err;
          }
          should.exist(block);
          block.hash.should.equal(blockHashes[i]);
          done();
        });
      });
    });
  });

  describe('get blocks as buffers', function() {
    [0,1,2,3,5,6,7,8,9].forEach(function(i) {
      it('generated block ' + i, function(done) {
        bitcoind.getRawBlock(blockHashes[i], function(err, block) {
          if (err) {
            throw err;
          }
          should.exist(block);
          (block instanceof Buffer).should.equal(true);
          done();
        });
      });
    });
  });

  describe('get errors as error instances', function() {
    it('will wrap an rpc into a javascript error', function(done) {
      bitcoind.client.getBlock(1000000000, function(err, response) {
        var error = bitcoind._wrapRPCError(err);
        (error instanceof Error).should.equal(true);
        error.message.should.equal(err.message);
        error.code.should.equal(err.code);
        should.exist(error.stack);
        done();
      });
    });
  });

  describe('get blocks by height', function() {

    [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('generated block ' + i, function(done) {
        // add the genesis block
        var height = i + 1;
        bitcoind.getBlock(i + 1, function(err, block) {
          if (err) {
            throw err;
          }
          should.exist(block);
          block.hash.should.equal(blockHashes[i]);
          done();
        });
      });
    });

    it('will get error with number greater than tip', function(done) {
      bitcoind.getBlock(1000000000, function(err, response) {
        should.exist(err);
        err.code.should.equal(-8);
        done();
      });
    });

  });

  describe('get transactions by hash', function() {
    [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('for tx ' + i, function(done) {
        var txhex = transactionData[i];
        var tx = new bitcore.Transaction();
        tx.fromString(txhex);
        bitcoind.getTransaction(tx.hash, function(err, response) {
          if (err) {
            throw err;
          }
          assert(response.toString('hex') === txhex, 'incorrect tx data result');
          done();
        });
      });
    });

    it('will return error if the transaction does not exist', function(done) {
      var txid = '6226c407d0e9705bdd7158e60983e37d0f5d23529086d6672b07d9238d5aa618';
      bitcoind.getTransaction(txid, function(err, response) {
        should.exist(err);
        done();
      });
    });
  });

  describe('get transactions as buffers', function() {
    [0,1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('for tx ' + i, function(done) {
        var txhex = transactionData[i];
        var tx = new bitcore.Transaction();
        tx.fromString(txhex);
        bitcoind.getRawTransaction(tx.hash, function(err, response) {
          if (err) {
            throw err;
          }
          response.should.be.instanceOf(Buffer);
          assert(response.toString('hex') === txhex, 'incorrect tx data result');
          done();
        });
      });
    });

    it('will return error if the transaction does not exist', function(done) {
      var txid = '6226c407d0e9705bdd7158e60983e37d0f5d23529086d6672b07d9238d5aa618';
      bitcoind.getRawTransaction(txid, function(err, response) {
        should.exist(err);
        done();
      });
    });
  });

  describe('get block header', function() {
    var expectedWork = new BN(6);
    [1,2,3,4,5,6,7,8,9].forEach(function(i) {
      it('generate block ' + i, function(done) {
        bitcoind.getBlockHeader(blockHashes[i], function(err, blockIndex) {
          if (err) {
            return done(err);
          }
          should.exist(blockIndex);
          should.exist(blockIndex.chainwork);
          var work = new BN(blockIndex.chainwork, 'hex');
          work.toString(16).should.equal(expectedWork.toString(16));
          expectedWork = expectedWork.add(new BN(2));
          should.exist(blockIndex.previousblockhash);
          blockIndex.hash.should.equal(blockHashes[i]);
          blockIndex.previousblockhash.should.equal(blockHashes[i - 1]);
          blockIndex.height.should.equal(i + 1);
          done();
        });
      });
    });
    it('will get null prevHash for the genesis block', function(done) {
      bitcoind.getBlockHeader(0, function(err, header) {
        if (err) {
          return done(err);
        }
        should.exist(header);
        should.equal(header.previousblockhash, undefined);
        done();
      });
    });
    it('will get error for block not found', function(done) {
      bitcoind.getBlockHeader('notahash', function(err, header) {
        should.exist(err);
        done();
      });
    });
  });

  describe('get block index by height', function() {
    var expectedWork = new BN(6);
    [2,3,4,5,6,7,8,9].forEach(function(i) {
      it('generate block ' + i, function() {
        bitcoind.getBlockHeader(i, function(err, header) {
          should.exist(header);
          should.exist(header.chainwork);
          var work = new BN(header.chainwork, 'hex');
          work.toString(16).should.equal(expectedWork.toString(16));
          expectedWork = expectedWork.add(new BN(2));
          should.exist(header.previousblockhash);
          header.hash.should.equal(blockHashes[i - 1]);
          header.previousblockhash.should.equal(blockHashes[i - 2]);
          header.height.should.equal(i);
        });
      });
    });
    it('will get error with number greater than tip', function(done) {
      bitcoind.getBlockHeader(100000, function(err, header) {
        should.exist(err);
        done();
      });
    });
  });

  describe('send transaction functionality', function() {

    it('will not error and return the transaction hash', function(done) {

      // create and sign the transaction
      var tx = bitcore.Transaction();
      tx.from(utxos[0]);
      tx.change(privateKey.toAddress());
      tx.to(destKey.toAddress(), utxos[0].amount * 1e8 - 1000);
      tx.sign(bitcore.PrivateKey.fromWIF(utxos[0].privateKeyWIF));

      // test sending the transaction
      bitcoind.sendTransaction(tx.serialize(), function(err, hash) {
        if (err) {
          return done(err);
        }
        hash.should.equal(tx.hash);
        done();
      });

    });

    it('will throw an error if an unsigned transaction is sent', function(done) {
      var tx = bitcore.Transaction();
      tx.from(utxos[1]);
      tx.change(privateKey.toAddress());
      tx.to(destKey.toAddress(), utxos[1].amount * 1e8 - 1000);
      bitcoind.sendTransaction(tx.uncheckedSerialize(), function(err, hash) {
        should.exist(err);
        (err instanceof Error).should.equal(true);
        should.not.exist(hash);
        done();
      });
    });

    it('will throw an error for unexpected types (tx decode failed)', function(done) {
      var garbage = new Buffer('abcdef', 'hex');
      bitcoind.sendTransaction(garbage, function(err, hash) {
        should.exist(err);
        should.not.exist(hash);
        var num = 23;
        bitcoind.sendTransaction(num, function(err, hash) {
          should.exist(err);
          (err instanceof Error).should.equal(true);
          should.not.exist(hash);
          done();
        });
      });
    });

    it('will emit "tx" events', function(done) {
      var tx = bitcore.Transaction();
      tx.from(utxos[2]);
      tx.change(privateKey.toAddress());
      tx.to(destKey.toAddress(), utxos[2].amount * 1e8 - 1000);
      tx.sign(bitcore.PrivateKey.fromWIF(utxos[2].privateKeyWIF));

      var serialized = tx.serialize();

      bitcoind.once('tx', function(buffer) {
        buffer.toString('hex').should.equal(serialized);
        done();
      });
      bitcoind.sendTransaction(serialized, function(err, hash) {
        if (err) {
          return done(err);
        }
        should.exist(hash);
      });
    });

  });

  describe('fee estimation', function() {
    it('will estimate fees', function(done) {
      bitcoind.estimateFee(1, function(err, fees) {
        if (err) {
          return done(err);
        }
        fees.should.equal(-1);
        done();
      });
    });
  });

  describe('tip updates', function() {
    it('will get an event when the tip is new', function(done) {
      this.timeout(4000);
      bitcoind.on('tip', function(height) {
        if (height === 151) {
          done();
        }
      });
      client.generate(1, function(err, response) {
        if (err) {
          throw err;
        }
      });
    });
  });

  describe('get transaction with block info', function() {
    it('should include tx with height and timestamp', function(done) {
      bitcoind.getTransactionWithBlockInfo(utxos[0].txid, function(err, tx) {
        if (err) {
          return done(err);
        }
        should.exist(tx.__height);
        tx.__height.should.be.a('number');
        should.exist(tx.__timestamp);
        should.exist(tx.__blockHash);
        done();
      });
    });
  });

  describe('#getInfo', function() {
    it('will get information', function(done) {
      bitcoind.getInfo(function(err, info) {
        if (err) {
          return done(err);
        }
        info.network.should.equal('regtest');
        should.exist(info);
        should.exist(info.version);
        should.exist(info.blocks);
        should.exist(info.timeoffset);
        should.exist(info.connections);
        should.exist(info.difficulty);
        should.exist(info.testnet);
        should.exist(info.relayfee);
        should.exist(info.errors);
        done();
      });
    });
  });

});
<|endoftext|>


<commit_before>'use strict'

import 'babel-polyfill' // For async/await support.
import { graphql } from 'graphql'
import { Schema } from './data/schema'
import {
  createGraphQLContext,
  getUserClaimsFromLambdaEvent,
  isUserAuthorized
} from './utils/authorization-helpers'
import { handleError } from './utils/error-logging'
import logger, {
  loggerContextWrapper
} from './utils/logger'

// Note: we need to use Bluebird until at least Node 8. Using
// native promises breaks Sentry/Raven context:
// https://github.com/getsentry/raven-node/issues/265
global.Promise = require('bluebird')
const Promise = require('bluebird')

const createResponse = function (statusCode, body) {
  return {
    statusCode: statusCode,
    headers: {
      'Access-Control-Allow-Origin': '*' // Required for CORS
    },
    body: JSON.stringify(body)
  }
}

export const handler = function (event) {
  var body
  try {
    body = JSON.parse(event.body)
  } catch (e) {
    return Promise.resolve(createResponse(500, e))
  }

  // Check user authorization.
  const claims = getUserClaimsFromLambdaEvent(event)
  if (!isUserAuthorized(claims)) {
    return Promise.resolve(createResponse(401, 'Request not authorized.'))
  }
  const context = createGraphQLContext(claims)

  // Add context to any logs (e.g. the user and request data).
  return loggerContextWrapper(
    context.user,
    event,
    () => {
      return graphql(Schema, body.query, null, context, body.variables)
        .then(data => {
          // Check if the GraphQL response contains any errors, and
          // if it does, handle them.
          // See how express-graphql handles this:
          // https://github.com/graphql/express-graphql/blob/master/src/index.js#L301
          // If graphql-js gets a logger, we can move logging there:
          // https://github.com/graphql/graphql-js/issues/284
          if (data && data.errors) {
            data.errors = data.errors.map(err => handleError(err))
            return createResponse(500, data)
          }
          return createResponse(200, data)
        })
        .catch(err => {
          handleError(err)
          return createResponse(500, 'Internal Error')
        })
    }
  )
}

export const serverlessHandler = function (event, context, callback) {
  handler(event)
    .then(response => callback(null, response))
}
<commit_msg>Lint fix.<commit_after>'use strict'

import 'babel-polyfill' // For async/await support.
import { graphql } from 'graphql'
import { Schema } from './data/schema'
import {
  createGraphQLContext,
  getUserClaimsFromLambdaEvent,
  isUserAuthorized
} from './utils/authorization-helpers'
import { handleError } from './utils/error-logging'
import {
  loggerContextWrapper
} from './utils/logger'

// Note: we need to use Bluebird until at least Node 8. Using
// native promises breaks Sentry/Raven context:
// https://github.com/getsentry/raven-node/issues/265
global.Promise = require('bluebird')
const Promise = require('bluebird')

const createResponse = function (statusCode, body) {
  return {
    statusCode: statusCode,
    headers: {
      'Access-Control-Allow-Origin': '*' // Required for CORS
    },
    body: JSON.stringify(body)
  }
}

export const handler = function (event) {
  var body
  try {
    body = JSON.parse(event.body)
  } catch (e) {
    return Promise.resolve(createResponse(500, e))
  }

  // Check user authorization.
  const claims = getUserClaimsFromLambdaEvent(event)
  if (!isUserAuthorized(claims)) {
    return Promise.resolve(createResponse(401, 'Request not authorized.'))
  }
  const context = createGraphQLContext(claims)

  // Add context to any logs (e.g. the user and request data).
  return loggerContextWrapper(
    context.user,
    event,
    () => {
      return graphql(Schema, body.query, null, context, body.variables)
        .then(data => {
          // Check if the GraphQL response contains any errors, and
          // if it does, handle them.
          // See how express-graphql handles this:
          // https://github.com/graphql/express-graphql/blob/master/src/index.js#L301
          // If graphql-js gets a logger, we can move logging there:
          // https://github.com/graphql/graphql-js/issues/284
          if (data && data.errors) {
            data.errors = data.errors.map(err => handleError(err))
            return createResponse(500, data)
          }
          return createResponse(200, data)
        })
        .catch(err => {
          handleError(err)
          return createResponse(500, 'Internal Error')
        })
    }
  )
}

export const serverlessHandler = function (event, context, callback) {
  handler(event)
    .then(response => callback(null, response))
}
<|endoftext|>


<commit_before>
/*
 * 这是一个抢票js，
 * 本js只适用有编程基础的人使用。
 * 用法说明：
 * 1,登录上www.12306.cn,到查询车票页(ihttps://kyfw.12306.cn/otn/leftTicket/init),
 * 2,选择自己好自己要买的日期和出发地和目的地,
 * 3,找到自己要购买的车票的那个td的id，类似ticket_5000K28243
 *
 */
(function(window, $){
	var ticketid = 'ticket_550000K15200';
	var queryTicketid = 'query_ticket';
	//乘车人在联系人第几个
	var riderOrder = 2;
	var queryInterval = 1000;
	var preBuyTimeout = 1000;
	var queryTicket = function(){
		$("#" + queryTicketid).click();
		var preBuyTicket = $("#"+ticketid+' td.no-br a');
		if(preBuyTicket.length > 0){
			setTimeout(function(){
				preBuyTicket.click();
			}, queryInterval);
		}
		var rider = $('#normalPassenger_' + riderOrder);
		if(rider.length > 0){
			rider.click();
			$('#randCode').focus();
			//弹出浏览器
		}else{
			setTimeout(queryTicket, preBuyTimeout);
		}
	};
	queryTicket();
})(window, jQuery);
<commit_msg>修改了执行顺序<commit_after>/*
 * 这是一个 JavaScript 代码片段速记器。
 *
 * 输入一些 JavaScript，然后可点击右键或从 执行 菜单中选择：
 * 1. 运行 对选中的文本求值(eval) (Ctrl+R)，
 * 2. 查看 对返回值使用对象查看器 (Ctrl+I)，
 * 3. 显示 在选中内容后面以注释的形式插入返回的结果。 (Ctrl+L)
 */

(function(window, $){
	var ticketid = 'ticket_550000K37671';
	var queryTicketid = 'query_ticket';
	//乘车人在联系人第几个
	var riderOrder = 1;
	var queryInterval = 3000;
	var preBuyTimeout = 500;
	var queryTicketTimes = 20;//脚本执行次数
	var curQueryTicketTimes = 0;//当前执行的次数
	var preBuyTicketTimes = 20;//点击预订总次数
	var queryTicket = function(){
		if(curQueryTicketTimes < queryTicketTimes){
			//console.log('queryTicket');
			$("#" + queryTicketid).click();
			var clickPrebuy = function(){
				//console.log('clickPrebuy');

				var calltimes = 0;
				var clickPrebuy1 = function(){
					//console.log('clickPrebuy1');
					if(calltimes < preBuyTicketTimes){
						var preBuyTicket = $("#"+ticketid+' td.no-br a');
						if(preBuyTicket.length > 0){
							preBuyTicket.click();
						}else{
							setTimeout(clickPrebuy1, 100);
						}
					}else{
						queryTicket();
					}
					calltimes++;
				}
				return clickPrebuy1;
			};
			clickPrebuy()();
		}
		curQueryTicketTimes++;
	};
	queryTicket();
})(window, jQuery);

<|endoftext|>


<commit_before>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.252 2004/03/20 02:30:04 chregu Exp $

var BXE_VERSION = "0.9.4-dev";
var BXE_BUILD = "200403200330"

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/
	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{

		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in (X)HTML - load Mozile JS explicitly in XML files");
		}
	} else {
		alert ("Bitflux Editor only works with Mozilla/Firefox on any platform. \nCurrently we recommend Mozilla 1.6 or Firefox 0.8. \nBut Mozilla >= 1.4 should work as well.");
	}

}

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);
	bxe_context_menu = new Widget_ContextMenu();

}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<commit_msg>automatic BuildDate Update<commit_after>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.253 2004/03/23 02:30:04 chregu Exp $

var BXE_VERSION = "0.9.4-dev";
var BXE_BUILD = "200403230330"

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/
	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{

		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in (X)HTML - load Mozile JS explicitly in XML files");
		}
	} else {
		alert ("Bitflux Editor only works with Mozilla/Firefox on any platform. \nCurrently we recommend Mozilla 1.6 or Firefox 0.8. \nBut Mozilla >= 1.4 should work as well.");
	}

}

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);
	bxe_context_menu = new Widget_ContextMenu();

}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<|endoftext|>


<commit_before>var ver = '4.8.38';<commit_msg>Set new version number<commit_after>var ver = '4.8.39';<|endoftext|>


<commit_before>var db = require('./../db_actions');
var sync = jxcore.utils.cmdSync;
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');

var eopts = {
  encoding: 'utf8',
  timeout: 0,
  maxBuffer: 1e9,
  killSignal: 'SIGTERM'
};

var createBranch = function(branch_name, cb) {
  exec("cd " + process.cwd() + "/reporting;chmod +x ./push_logs.sh;./push_logs.sh " + branch_name,
    eopts, function (err, stdout, stderr) {
      cb(err, stdout + "\n" + stderr);
    });
};

// this needs to be syched!
// why ? we don't want any other test worker write in between
exports.logIntoBranch = function(branch_name, filename, log, cb) {
  createBranch(branch_name, function (err, res) {
    if (err) {
      cb(err, res);
      return;
    }

    var res = sync("cd " + process.cwd() + "/TestResults;git checkout " + branch_name);
    if (res.exitCode) {
      cb("exit code:" + res.exitCode, res.out);
      return;
    }

    fs.writeFileSync(process.cwd() + '/TestResults/' + filename, log);

    var res = sync("cd " + process.cwd() + "/reporting;chmod +x ./commit_logs.sh;./commit_logs.sh " + branch_name);
    if (res.exitCode) {
      cb("exit code:" + res.exitCode, res.out);
      return;
    }

    cb(null);
  });
};<commit_msg>fixes build log issue<commit_after>var db = require('./../db_actions');
var sync = jxcore.utils.cmdSync;
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');

var eopts = {
  encoding: 'utf8',
  timeout: 0,
  maxBuffer: 1e9,
  killSignal: 'SIGTERM'
};

var createBranch = function (branch_name, cb) {
  exec("cd " + process.cwd() + "/reporting;chmod +x ./push_logs.sh;./push_logs.sh " + branch_name,
    eopts, function (err, stdout, stderr) {
      cb(err, stdout + "\n" + stderr);
    });
};

// this needs to be syched!
// why ? we don't want any other test worker write in between
exports.logIntoBranch = function (branch_name, filename, log, cb) {
  createBranch(branch_name, function (err, res) {
    if (err) {
      cb(err, res);
      return;
    }

    var res = sync("cd " + process.cwd() + "/TestResults;git checkout " + branch_name);
    if (res.exitCode) {
      cb("exit code:" + res.exitCode, res.out);
      return;
    }

    fs.writeFileSync(process.cwd() + '/TestResults/' + filename, log);

    exec("cd " + process.cwd()
      + "/reporting;chmod +x ./commit_logs.sh;./commit_logs.sh " + branch_name, eopts,
      function (err, stdout, stderr) {
        if (err) {
          cb(err, stdout + "\n" + stderr);
        } else {
          cb(null);
        }
      });
  });
};<|endoftext|>


<commit_before>/*global THREE*/
(function() {
  'use strict';

  var container;

  var scene, camera, controls, renderer;
  var geometry, material, mesh;

  var skeletonHelper;

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.01 );
    camera.position.set( 0, 0, 2 );
    scene.add( camera );

    controls = new THREE.OrbitControls( camera, renderer.domElement );

    var matrix = new THREE.Matrix4();
    var vector = new THREE.Vector3();

    geometry = new THREE.Geometry();

    var boxGeometry = new THREE.BoxGeometry( 0.25, 1, 0.25 );
    boxGeometry.applyMatrix( matrix.makeTranslation( 0, 0.5, 0 ) );
    geometry.merge( boxGeometry );

    var angle = Math.PI / 6;

    var tempGeometry = boxGeometry.clone();
    tempGeometry.applyMatrix( matrix.makeRotationZ( angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    tempGeometry.applyMatrix( matrix.makeRotationZ( -angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    tempGeometry.applyMatrix( matrix.makeRotationZ( angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    tempGeometry.applyMatrix( matrix.makeRotationZ( angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    tempGeometry.applyMatrix( matrix.makeRotationZ( -angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    tempGeometry.applyMatrix( matrix.makeRotationZ( angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    tempGeometry.applyMatrix( matrix.makeRotationZ( angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    tempGeometry.applyMatrix( matrix.makeRotationZ( angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    tempGeometry.applyMatrix( matrix.makeRotationZ( angle ) );
    tempGeometry.applyMatrix( matrix.makeTranslation( 0, 1, 0 ) );
    geometry.merge( tempGeometry );

    geometry.bones = [
      {
        parent: -1,
        name: 'root',
        pos: [ 0, 0, 0 ],
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 0,
        name: 'bone.0',
        pos: [ 0, 1, 0 ],
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 1,
        name: 'bone.0.0',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 1,
        name: 'bone.0.1',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( -angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 2,
        name: 'bone.0.0.0',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( 2 * angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 2,
        name: 'bone.0.0.1',
        pos: [ 0, 1, 0 ],
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 4,
        name: 'bone.0.0.0.0',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( 3 * angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      }
    ];

    function mapVertices( key ) {
      return function( x, y, z, w ) {
        return function() {
          geometry[ key ].push( new THREE.Vector4( x, y, z, w ) );
        };
      };
    }

    var skinIndices = mapVertices( 'skinIndices' );
    var skinWeights = mapVertices( 'skinWeights' );

    // Skin indices.
    boxGeometry.vertices.forEach( skinIndices( 0, 1, 0, 0 ) );
    boxGeometry.vertices.forEach( skinIndices( 1, 2, 0, 0 ) );
    boxGeometry.vertices.forEach( skinIndices( 1, 3, 0, 0 ) );
    boxGeometry.vertices.forEach( skinIndices( 2, 4, 0, 0 ) );
    boxGeometry.vertices.forEach( skinIndices( 2, 5, 0, 0 ) );
    boxGeometry.vertices.forEach( skinIndices( 4, 6, 0, 0 ) );

    // Skin weights.
    boxGeometry.vertices.forEach( skinWeights( 1, 0, 0, 0 ) );
    boxGeometry.vertices.forEach( skinWeights( 1, 0, 0, 0 ) );
    boxGeometry.vertices.forEach( skinWeights( 1, 0, 0, 0 ) );
    boxGeometry.vertices.forEach( skinWeights( 1, 0, 0, 0 ) );
    boxGeometry.vertices.forEach( skinWeights( 1, 0, 0, 0 ) );
    boxGeometry.vertices.forEach( skinWeights( 1, 0, 0, 0 ) );

    material = new THREE.MeshBasicMaterial({
      skinning: true,
      wireframe: true
    });

    mesh = new THREE.SkinnedMesh( geometry, material );
    scene.add( mesh );

    skeletonHelper = new THREE.SkeletonHelper( mesh );
    skeletonHelper.material.linewidth = 4;
    mesh.add( skeletonHelper );
  }

  var scale = new THREE.Vector3();

  function animate() {
    var time = Date.now() * 1e-3;
    var angle = Math.cos( time );
    var length = 0.5 * ( Math.cos( time ) + 1 );

    mesh.skeleton.bones.forEach(function( bone, index ) {
      scale.setFromMatrixScale( bone.parent.matrixWorld );
      bone.scale.setLength( ( length + 0.25 ) / scale.length() );
      bone.updateMatrixWorld();

      // Set angle if not root.
      if ( index ) {
        bone.rotation.z = angle;
      }
    });

    skeletonHelper.update();
    renderer.render( scene, camera );
    requestAnimationFrame( animate );
  }

  init();
  animate();

})();
<commit_msg>skeleton: Simplify nested transforms and skin creation.<commit_after>/*global THREE*/
(function() {
  'use strict';

  var container;

  var scene, camera, controls, renderer;
  var geometry, material, mesh;

  var skeletonHelper;

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.01 );
    camera.position.set( 0, 0, 2 );
    scene.add( camera );

    controls = new THREE.OrbitControls( camera, renderer.domElement );

    var matrix = new THREE.Matrix4();
    var vector = new THREE.Vector3();

    geometry = new THREE.Geometry();

    var boxGeometry = new THREE.BoxGeometry( 0.25, 1, 0.25 );
    boxGeometry.applyMatrix( matrix.makeTranslation( 0, 0.5, 0 ) );
    geometry.merge( boxGeometry );

    var angle = Math.PI / 6;

    function rotateZ( geometry, angle ) {
      geometry.applyMatrix( matrix.makeRotationZ( angle ) );
    }

    function translate( geometry, x, y, z ) {
      geometry.applyMatrix( matrix.makeTranslation( x, y, z ) );
    }

    var tempGeometry = boxGeometry.clone();
    rotateZ( tempGeometry, angle );
    translate( tempGeometry, 0, 1, 0 );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    rotateZ( tempGeometry, -angle );
    translate( tempGeometry, 0, 1, 0 );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    rotateZ( tempGeometry, angle );
    translate( tempGeometry, 0, 1, 0 );
    rotateZ( tempGeometry, angle );
    translate( tempGeometry, 0, 1, 0 );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    rotateZ( tempGeometry, -angle );
    translate( tempGeometry, 0, 1, 0 );
    rotateZ( tempGeometry, angle );
    translate( tempGeometry, 0, 1, 0 );
    geometry.merge( tempGeometry );

    tempGeometry = boxGeometry.clone();
    rotateZ( tempGeometry, angle );
    translate( tempGeometry, 0, 1, 0 );
    rotateZ( tempGeometry, angle );
    translate( tempGeometry, 0, 1, 0 );
    rotateZ( tempGeometry, angle );
    translate( tempGeometry, 0, 1, 0 );
    geometry.merge( tempGeometry );

    geometry.bones = [
      {
        parent: -1,
        name: 'root',
        pos: [ 0, 0, 0 ],
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 0,
        name: 'bone.0',
        pos: [ 0, 1, 0 ],
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 1,
        name: 'bone.0.0',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 1,
        name: 'bone.0.1',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( -angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 2,
        name: 'bone.0.0.0',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( 2 * angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 2,
        name: 'bone.0.0.1',
        pos: [ 0, 1, 0 ],
        rotq: [ 0, 0, 0, 1 ]
      },
      {
        parent: 4,
        name: 'bone.0.0.0.0',
        pos: vector.set( 0, 1, 0 )
          .applyMatrix4( matrix.makeRotationZ( 3 * angle ) )
          .toArray(),
        rotq: [ 0, 0, 0, 1 ]
      }
    ];

    function mapVertices( key ) {
      return function( x, y, z, w ) {
        return function() {
          geometry[ key ].push( new THREE.Vector4( x, y, z, w || 0 ) );
        };
      };
    }

    var skinIndices = mapVertices( 'skinIndices' );
    var skinWeights = mapVertices( 'skinWeights' );

    // Skin indices.
    boxGeometry.vertices.forEach( skinIndices( 0, 1 ) );
    boxGeometry.vertices.forEach( skinIndices( 1, 2 ) );
    boxGeometry.vertices.forEach( skinIndices( 1, 3 ) );
    boxGeometry.vertices.forEach( skinIndices( 2, 4 ) );
    boxGeometry.vertices.forEach( skinIndices( 2, 5 ) );
    boxGeometry.vertices.forEach( skinIndices( 4, 6 ) );

    // Skin weights.
    boxGeometry.vertices.forEach( skinWeights( 1 ) );
    boxGeometry.vertices.forEach( skinWeights( 1 ) );
    boxGeometry.vertices.forEach( skinWeights( 1 ) );
    boxGeometry.vertices.forEach( skinWeights( 1 ) );
    boxGeometry.vertices.forEach( skinWeights( 1 ) );
    boxGeometry.vertices.forEach( skinWeights( 1 ) );

    material = new THREE.MeshBasicMaterial({
      skinning: true,
      wireframe: true
    });

    mesh = new THREE.SkinnedMesh( geometry, material );
    scene.add( mesh );

    skeletonHelper = new THREE.SkeletonHelper( mesh );
    skeletonHelper.material.linewidth = 4;
    mesh.add( skeletonHelper );
  }

  var scale = new THREE.Vector3();

  function animate() {
    var time = Date.now() * 1e-3;
    var angle = Math.cos( time );
    var length = 0.5 * ( Math.cos( time ) + 1 );

    mesh.skeleton.bones.forEach(function( bone, index ) {
      scale.setFromMatrixScale( bone.parent.matrixWorld );
      bone.scale.setLength( ( length + 0.25 ) / scale.length() );
      bone.updateMatrixWorld();

      // Set angle if not root.
      if ( index ) {
        bone.rotation.z = angle;
      }
    });

    skeletonHelper.update();
    renderer.render( scene, camera );
    requestAnimationFrame( animate );
  }

  init();
  animate();

})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

import translate from '../../i18n/translate';
import FieldTitle from '../../util/FieldTitle';

/**
 * An Input component for a select box, using an array of objects for the options
 *
 * Pass possible options as an array of objects in the 'choices' attribute.
 *
 * By default, the options are built from:
 *  - the 'id' property as the option value,
 *  - the 'name' property an the option text
 * @example
 * const choices = [
 *    { id: 'M', name: 'Male' },
 *    { id: 'F', name: 'Female' },
 * ];
 * <SelectInput source="gender" choices={choices} />
 *
 * You can also customize the properties to use for the option name and value,
 * thanks to the 'optionText' and 'optionValue' attributes.
 * @example
 * const choices = [
 *    { _id: 123, full_name: 'Leo Tolstoi', sex: 'M' },
 *    { _id: 456, full_name: 'Jane Austen', sex: 'F' },
 * ];
 * <SelectInput source="author_id" choices={choices} optionText="full_name" optionValue="_id" />
 *
 * `optionText` also accepts a function, so you can shape the option text at will:
 * @example
 * const choices = [
 *    { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
 *    { id: 456, first_name: 'Jane', last_name: 'Austen' },
 * ];
 * const optionRenderer = choice => `${choice.first_name} ${choice.last_name}`;
 * <SelectInput source="author_id" choices={choices} optionText={optionRenderer} />
 *
 * `optionText` also accepts a React Element, that will be cloned and receive
 * the related choice as the `record` prop. You can use Field components there.
 * @example
 * const choices = [
 *    { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
 *    { id: 456, first_name: 'Jane', last_name: 'Austen' },
 * ];
 * const FullNameField = ({ record }) => {record.first_name} {record.last_name};
 * <SelectInput source="gender" choices={choices} optionText={<FullNameField />}/>
 *
 * The choices are translated by default, so you can use translation identifiers as choices:
 * @example
 * const choices = [
 *    { id: 'M', name: 'myroot.gender.male' },
 *    { id: 'F', name: 'myroot.gender.female' },
 * ];
 *
 * However, in some cases (e.g. inside a `<ReferenceInput>`), you may not want
 * the choice to be translated. In that case, set the `translateChoice` prop to false.
 * @example
 * <SelectInput source="gender" choices={choices} translateChoice={false}/>
 *
 * The object passed as `options` props is passed to the material-ui <SelectField> component
 */
export class SelectInput extends Component {
    state = {
        value: this.props.input.value,
    }

    handleChange = (event, index, value) => {
        this.props.input.onChange(value);
        this.setState({ value });
    }

    renderMenuItem = (choice) => {
        const {
            optionText,
            optionValue,
            translate,
            translateChoice,
        } = this.props;
        const choiceName = React.isValidElement(optionText) ? // eslint-disable-line no-nested-ternary
            React.cloneElement(optionText, { record: choice }) :
            (typeof optionText === 'function' ?
                optionText(choice) :
                choice[optionText]
            );
        return (
            <MenuItem
                key={choice[optionValue]}
                primaryText={translateChoice ? translate(choiceName, { _: choiceName }) : choiceName}
                value={choice[optionValue]}
            />
        );
    }

    render() {
        const {
            allowEmpty,
            choices,
            elStyle,
            input,
            isRequired,
            label,
            meta: { touched, error },
            options,
            resource,
            source,
        } = this.props;
        return (
            <SelectField
                value={this.state.value}
                floatingLabelText={<FieldTitle label={label} source={source} resource={resource} isRequired={isRequired} />}
                onChange={this.handleChange}
                autoWidth
                style={elStyle}
                errorText={touched && error}
                {...options}
            >
                {allowEmpty &&
                    <MenuItem value={null} primaryText="" />
                }
                {choices.map(this.renderMenuItem)}
            </SelectField>
        );
    }
}

SelectInput.propTypes = {
    addField: PropTypes.bool.isRequired,
    allowEmpty: PropTypes.bool.isRequired,
    choices: PropTypes.arrayOf(PropTypes.object),
    elStyle: PropTypes.object,
    input: PropTypes.object,
    isRequired: PropTypes.bool,
    label: PropTypes.string,
    meta: PropTypes.object,
    options: PropTypes.object,
    optionText: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func,
        PropTypes.element,
    ]).isRequired,
    optionValue: PropTypes.string.isRequired,
    resource: PropTypes.string,
    source: PropTypes.string,
    translate: PropTypes.func.isRequired,
    translateChoice: PropTypes.bool.isRequired,
};

SelectInput.defaultProps = {
    addField: true,
    allowEmpty: false,
    choices: [],
    options: {},
    optionText: 'name',
    optionValue: 'id',
    translateChoice: true,
};

export default translate(SelectInput);
<commit_msg>Add comment to explain the code<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';

import translate from '../../i18n/translate';
import FieldTitle from '../../util/FieldTitle';

/**
 * An Input component for a select box, using an array of objects for the options
 *
 * Pass possible options as an array of objects in the 'choices' attribute.
 *
 * By default, the options are built from:
 *  - the 'id' property as the option value,
 *  - the 'name' property an the option text
 * @example
 * const choices = [
 *    { id: 'M', name: 'Male' },
 *    { id: 'F', name: 'Female' },
 * ];
 * <SelectInput source="gender" choices={choices} />
 *
 * You can also customize the properties to use for the option name and value,
 * thanks to the 'optionText' and 'optionValue' attributes.
 * @example
 * const choices = [
 *    { _id: 123, full_name: 'Leo Tolstoi', sex: 'M' },
 *    { _id: 456, full_name: 'Jane Austen', sex: 'F' },
 * ];
 * <SelectInput source="author_id" choices={choices} optionText="full_name" optionValue="_id" />
 *
 * `optionText` also accepts a function, so you can shape the option text at will:
 * @example
 * const choices = [
 *    { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
 *    { id: 456, first_name: 'Jane', last_name: 'Austen' },
 * ];
 * const optionRenderer = choice => `${choice.first_name} ${choice.last_name}`;
 * <SelectInput source="author_id" choices={choices} optionText={optionRenderer} />
 *
 * `optionText` also accepts a React Element, that will be cloned and receive
 * the related choice as the `record` prop. You can use Field components there.
 * @example
 * const choices = [
 *    { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
 *    { id: 456, first_name: 'Jane', last_name: 'Austen' },
 * ];
 * const FullNameField = ({ record }) => {record.first_name} {record.last_name};
 * <SelectInput source="gender" choices={choices} optionText={<FullNameField />}/>
 *
 * The choices are translated by default, so you can use translation identifiers as choices:
 * @example
 * const choices = [
 *    { id: 'M', name: 'myroot.gender.male' },
 *    { id: 'F', name: 'myroot.gender.female' },
 * ];
 *
 * However, in some cases (e.g. inside a `<ReferenceInput>`), you may not want
 * the choice to be translated. In that case, set the `translateChoice` prop to false.
 * @example
 * <SelectInput source="gender" choices={choices} translateChoice={false}/>
 *
 * The object passed as `options` props is passed to the material-ui <SelectField> component
 */
export class SelectInput extends Component {
    /*
     * Using state to bypass a redux-form comparison but which prevents re-rendering
     * @see https://github.com/erikras/redux-form/issues/2456
     */
    state = {
        value: this.props.input.value,
    }

    handleChange = (event, index, value) => {
        this.props.input.onChange(value);
        this.setState({ value });
    }

    renderMenuItem = (choice) => {
        const {
            optionText,
            optionValue,
            translate,
            translateChoice,
        } = this.props;
        const choiceName = React.isValidElement(optionText) ? // eslint-disable-line no-nested-ternary
            React.cloneElement(optionText, { record: choice }) :
            (typeof optionText === 'function' ?
                optionText(choice) :
                choice[optionText]
            );
        return (
            <MenuItem
                key={choice[optionValue]}
                primaryText={translateChoice ? translate(choiceName, { _: choiceName }) : choiceName}
                value={choice[optionValue]}
            />
        );
    }

    render() {
        const {
            allowEmpty,
            choices,
            elStyle,
            input,
            isRequired,
            label,
            meta: { touched, error },
            options,
            resource,
            source,
        } = this.props;
        return (
            <SelectField
                value={this.state.value}
                floatingLabelText={<FieldTitle label={label} source={source} resource={resource} isRequired={isRequired} />}
                onChange={this.handleChange}
                autoWidth
                style={elStyle}
                errorText={touched && error}
                {...options}
            >
                {allowEmpty &&
                    <MenuItem value={null} primaryText="" />
                }
                {choices.map(this.renderMenuItem)}
            </SelectField>
        );
    }
}

SelectInput.propTypes = {
    addField: PropTypes.bool.isRequired,
    allowEmpty: PropTypes.bool.isRequired,
    choices: PropTypes.arrayOf(PropTypes.object),
    elStyle: PropTypes.object,
    input: PropTypes.object,
    isRequired: PropTypes.bool,
    label: PropTypes.string,
    meta: PropTypes.object,
    options: PropTypes.object,
    optionText: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func,
        PropTypes.element,
    ]).isRequired,
    optionValue: PropTypes.string.isRequired,
    resource: PropTypes.string,
    source: PropTypes.string,
    translate: PropTypes.func.isRequired,
    translateChoice: PropTypes.bool.isRequired,
};

SelectInput.defaultProps = {
    addField: true,
    allowEmpty: false,
    choices: [],
    options: {},
    optionText: 'name',
    optionValue: 'id',
    translateChoice: true,
};

export default translate(SelectInput);
<|endoftext|>