<commit_before>var test = require('tape')
var API = require('../lib/index')
var Device = require('ev3-js-device')
var devices = require('ev3-js-devices').devices
var clearDevices = require('ev3-js-devices').clear
var path = require('path')

var defaultPaths = {
  motor: path.join(__dirname, 'fake-sys/class/tacho-motor'),
  sensor: path.join(__dirname, 'fake-sys/class/lego-sensor')
}

API.setPaths(defaultPaths)

test('sensor_mode', function (t) {
  t.plan(2)
  var port = 1
  var sensor = new Device(devices(port, defaultPaths))
  sensor.write('mode', 'IR-PROX', function () {
    t.equals(sensor.read('mode'), 'IR-PROX')
    var sensorModeObj = {
      port: 1,
      command: 'IR-SEEK'
    }
    API['sensor_mode'](sensorModeObj, function (err, val) {
      t.equals(sensor.read('mode'), 'IR-SEEK')
    })
  })
})

test('stop reading on socket close', function (t) {
  var messages = API['messages']
  var data = {
    socketId: 1
  }
  API['sensor_subscribe'](data, function (err, val) {
    console.log(val)
    t.equal(val, true)
    t.equal(API['reading'](), true)
    messages.emit('close', 1)
    setTimeout(function () {
      t.equal(API['reading'](), false)
      t.end()
    }, 100)
  })
})

test('sensor_sub and sensor_unsub', function (t) {
  t.plan(4)
  var data = {
    socketId: 1
  }
  API['sensor_subscribe'](data, function (err, val) {
    t.equal(val, true)
    t.equal(API['reading'](), true)
    setTimeout(function () {
      API['sensor_unsubscribe'](data, function (err, val) {
        t.equal(val, true)
        t.equal(API['reading'](), false)
      })
    }, 1000)

  })
})

test('motor_read', function (t) {
  t.plan(1)
  var port = 'a'
  var motor = new Device(devices(port, defaultPaths))
  var readObj = {
    port: port,
    value: 'state'
  }
  API['motor_read'](readObj, function (err, val) {
    t.equals(motor.read('state'), val)
    resetMotor('a')
  }, defaultPaths)
})

test('motor_write', function (t) {
  t.plan(3)
  var port = 'a'
  var runObj = {
    type: 'motor_write',
    id: 1,
    command: 'run-to-rel-pos',
    port: port,
    opts: {
      'position_sp': '1000',
      'speed_sp': '50'
    }
  }
  var motor = new Device(devices(port, defaultPaths))
  API['motor_write'](runObj, function (err, val) {
    t.equals(motor.read('position_sp'), '1000')
    t.equals(motor.read('speed_sp'), '50')
    t.equals(motor.read('command'), 'run-to-rel-pos')
    resetMotor('a')
    clearDevices()
    t.end()
  }, defaultPaths)
})

function resetMotor (port, cb) {
  cb = cb || function () {}
  port = port || 'a'
  var motor = new Device(devices(port, defaultPaths))
  motor.write('command', 'run-forever')
  motor.write('position_sp', '0')
  motor.write('duty_cycle_sp', '0')
}
<commit_msg>make tests standar<commit_after>var test = require('tape')
var API = require('../lib/index')
var Device = require('ev3-js-device')
var devices = require('ev3-js-devices').devices
var clearDevices = require('ev3-js-devices').clear
var path = require('path')

var defaultPaths = {
  motor: path.join(__dirname, 'fake-sys/class/tacho-motor'),
  sensor: path.join(__dirname, 'fake-sys/class/lego-sensor')
}

API.setPaths(defaultPaths)

test('sensor_mode', function (t) {
  t.plan(2)
  var port = 1
  var sensor = new Device(devices(port, defaultPaths))
  sensor.write('mode', 'IR-PROX', function () {
    t.equals(sensor.read('mode'), 'IR-PROX')
    var sensorModeObj = {
      port: 1,
      command: 'IR-SEEK'
    }
    API['sensor_mode'](sensorModeObj, function (err, val) {
      if (err) {}
      t.equals(sensor.read('mode'), 'IR-SEEK')
    })
  })
})

test('stop reading on socket close', function (t) {
  var messages = API['messages']
  var data = {
    socketId: 1
  }
  API['sensor_subscribe'](data, function (err, val) {
    if (err) {}
    t.equal(val, true)
    t.equal(API['reading'](), true)
    messages.emit('close', 1)
    setTimeout(function () {
      t.equal(API['reading'](), false)
      t.end()
    }, 100)
  })
})

test('sensor_sub and sensor_unsub', function (t) {
  t.plan(4)
  var data = {
    socketId: 1
  }
  API['sensor_subscribe'](data, function (err, val) {
    if (err) {}
    t.equal(val, true)
    t.equal(API['reading'](), true)
    setTimeout(function () {
      API['sensor_unsubscribe'](data, function (err, val) {
        if (err) {}
        t.equal(val, true)
        t.equal(API['reading'](), false)
      })
    }, 1000)
  })
})

test('motor_read', function (t) {
  t.plan(1)
  var port = 'a'
  var motor = new Device(devices(port, defaultPaths))
  var readObj = {
    port: port,
    value: 'state'
  }
  API['motor_read'](readObj, function (err, val) {
    if (err) {}
    t.equals(motor.read('state'), val)
    resetMotor('a')
  }, defaultPaths)
})

test('motor_write', function (t) {
  t.plan(3)
  var port = 'a'
  var runObj = {
    type: 'motor_write',
    id: 1,
    command: 'run-to-rel-pos',
    port: port,
    opts: {
      'position_sp': '1000',
      'speed_sp': '50'
    }
  }
  var motor = new Device(devices(port, defaultPaths))
  API['motor_write'](runObj, function (err, val) {
    if (err) {}
    t.equals(motor.read('position_sp'), '1000')
    t.equals(motor.read('speed_sp'), '50')
    t.equals(motor.read('command'), 'run-to-rel-pos')
    resetMotor('a')
    clearDevices()
    t.end()
  }, defaultPaths)
})

function resetMotor (port, cb) {
  cb = cb || function () {}
  port = port || 'a'
  var motor = new Device(devices(port, defaultPaths))
  motor.write('command', 'run-forever')
  motor.write('position_sp', '0')
  motor.write('duty_cycle_sp', '0')
}
<|endoftext|>


<commit_before>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(false).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<commit_msg>"Changed false to true"<commit_after>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(true).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>const fs = require('fs');
const util = require('util');
const _ = require('lodash');

const Client = require('./client');

const readFile = util.promisify(fs.readFile);

function addRefIdAsLabel(issueDescription) {
  return Object.assign(
    {},
    {
      fields: Object.assign({}, issueDescription.fields, {
        labels: _.compact([
          issueDescription.refId,
          ..._.get(issueDescription, 'fields.labels', []),
        ]),
      }),
    }
  );
}

function addProjectToIssue(project, issueDescription) {
  return Object.assign(
    {},
    {
      fields: Object.assign({}, issueDescription.fields, {
        project: { key: project },
        labels: _.compact([
          issueDescription.refId,
          ..._.get(issueDescription, 'fields.labels', []),
        ]),
      }),
    }
  );
}

const enhanceIssue = _.flow([addProjectToIssue, addRefIdAsLabel]);

async function processNewTemplatedIssue(
  client,
  issueTypeMeta,
  epicMap,
  project,
  issueDescription
) {
  const parentIssue = enhanceIssue(project, issueDescription);

  if (issueDescription.epicId) {
    const issueType = issueDescription.fields.issuetype.name;

    const propMeta = _.find(
      issueTypeMeta[issueType].fields,
      description =>
        description.schema.custom === 'com.pyxis.greenhopper.jira:gh-epic-link'
    );

    parentIssue.fields[propMeta.key] = epicMap.get(issueDescription.epicId);
  }

  const createdIssue = await client.createIssue(parentIssue);

  const subTasks = issueDescription.subTasks;

  let createdSubTasks = [];
  if (Array.isArray(subTasks) && subTasks.length > 0) {
    createdSubTasks = await Promise.all(
      subTasks.map(subTask => {
        const newSubIssue = enhanceIssue(project, subTask);
        newSubIssue.fields.parent = { id: createdIssue.id };

        return client
          .createIssue(newSubIssue)
          .then(createdSubTask => Object.assign({}, subTask, createdSubTask));
      })
    );
  }

  if (createdSubTasks.length > 0) {
    return Object.assign({}, issueDescription, createdIssue, {
      subTasks: createdSubTasks,
    });
  }

  return Object.assign({}, issueDescription, createdIssue);
}

async function execute(options) {
  const { template, project, jiraConfig } = options;

  const blob = await readFile(template);
  let contents = {};

  try {
    contents = JSON.parse(blob);
  } catch (e) {
    return Promise.reject(new Error('Invalid formatted template file'));
  }

  const client = new Client(jiraConfig);

  const issueTypeMeta = await client.getProjectIssueTypeMeta(project);

  const createdEpics = await Promise.all(
    contents.epics.map(epicDescription => {
      const epicIssue = enhanceIssue(project, epicDescription);
      const propMeta = _.find(
        issueTypeMeta[epicIssue.fields.issuetype.name].fields,
        description =>
          description.schema.custom ===
          'com.pyxis.greenhopper.jira:gh-epic-label'
      );

      epicIssue.fields[propMeta.key] = epicIssue.fields.epicName;
      delete epicIssue.fields.epicName;

      return client
        .createIssue(epicIssue)
        .then(result => Object.assign({}, epicDescription, result));
    })
  );

  const epicMap = new Map();
  createdEpics.forEach(epic => epicMap.set(epic.refId, epic.key));

  const createdIssues = await Promise.all(
    contents.issues.map(issueDescription =>
      processNewTemplatedIssue(
        client,
        issueTypeMeta,
        epicMap,
        project,
        issueDescription
      )
    )
  );

  const issueMap = createdIssues.reduce((map, issue) => {
    map.set(issue.refId, issue.key);

    if (Array.isArray(issue.subTasks)) {
      issue.subTasks.forEach(subTask => map.set(subTask.refId, subTask.key));
    }

    return map;
  }, new Map());

  const createdLinks = await Promise.all(
    contents.links.map(link => {
      const newLink = {
        type: link.type,
        comment: link.comment,
        inwardIssue: { key: issueMap.get(link.inwardIssue) },
        outwardIssue: { key: issueMap.get(link.outwardIssue) },
      };

      return client.createIssueLink(newLink).then(() => newLink);
    })
  );

  return {
    epics: createdEpics,
    issues: createdIssues,
    links: createdLinks,
  };
}

module.exports = execute;
<commit_msg>JIRAISSUER-12 Run role processing during the execution of the tool<commit_after>const fs = require('fs');
const util = require('util');
const _ = require('lodash');

const runRoleProcessing = require('./runRoleProcessing');
const Client = require('./client');

const readFile = util.promisify(fs.readFile);

function addRefIdAsLabel(issueDescription) {
  return Object.assign(
    {},
    {
      fields: Object.assign({}, issueDescription.fields, {
        labels: _.compact([
          issueDescription.refId,
          ..._.get(issueDescription, 'fields.labels', []),
        ]),
      }),
    }
  );
}

function addProjectToIssue(project, issueDescription) {
  return Object.assign(
    {},
    {
      fields: Object.assign({}, issueDescription.fields, {
        project: { key: project },
        labels: _.compact([
          issueDescription.refId,
          ..._.get(issueDescription, 'fields.labels', []),
        ]),
      }),
    }
  );
}

const enhanceIssue = _.flow([addProjectToIssue, addRefIdAsLabel]);

async function processNewTemplatedIssue(
  client,
  issueTypeMeta,
  epicMap,
  project,
  issueDescription
) {
  const parentIssue = enhanceIssue(project, issueDescription);

  if (issueDescription.epicId) {
    const issueType = issueDescription.fields.issuetype.name;

    const propMeta = _.find(
      issueTypeMeta[issueType].fields,
      description =>
        description.schema.custom === 'com.pyxis.greenhopper.jira:gh-epic-link'
    );

    parentIssue.fields[propMeta.key] = epicMap.get(issueDescription.epicId);
  }

  const createdIssue = await client.createIssue(parentIssue);

  const subTasks = issueDescription.subTasks;

  let createdSubTasks = [];
  if (Array.isArray(subTasks) && subTasks.length > 0) {
    createdSubTasks = await Promise.all(
      subTasks.map(subTask => {
        const newSubIssue = enhanceIssue(project, subTask);
        newSubIssue.fields.parent = { id: createdIssue.id };

        return client
          .createIssue(newSubIssue)
          .then(createdSubTask => Object.assign({}, subTask, createdSubTask));
      })
    );
  }

  if (createdSubTasks.length > 0) {
    return Object.assign({}, issueDescription, createdIssue, {
      subTasks: createdSubTasks,
    });
  }

  return Object.assign({}, issueDescription, createdIssue);
}

async function execute(options) {
  const { template, project, jiraConfig } = options;

  const blob = await readFile(template);
  let contents = {};

  try {
    contents = JSON.parse(blob);
  } catch (e) {
    return Promise.reject(new Error('Invalid formatted template file'));
  }

  contents = runRoleProcessing(contents);

  const client = new Client(jiraConfig);

  const issueTypeMeta = await client.getProjectIssueTypeMeta(project);

  const createdEpics = await Promise.all(
    contents.epics.map(epicDescription => {
      const epicIssue = enhanceIssue(project, epicDescription);
      const propMeta = _.find(
        issueTypeMeta[epicIssue.fields.issuetype.name].fields,
        description =>
          description.schema.custom ===
          'com.pyxis.greenhopper.jira:gh-epic-label'
      );

      epicIssue.fields[propMeta.key] = epicIssue.fields.epicName;
      delete epicIssue.fields.epicName;

      return client
        .createIssue(epicIssue)
        .then(result => Object.assign({}, epicDescription, result));
    })
  );

  const epicMap = new Map();
  createdEpics.forEach(epic => epicMap.set(epic.refId, epic.key));

  const createdIssues = await Promise.all(
    contents.issues.map(issueDescription =>
      processNewTemplatedIssue(
        client,
        issueTypeMeta,
        epicMap,
        project,
        issueDescription
      )
    )
  );

  const issueMap = createdIssues.reduce((map, issue) => {
    map.set(issue.refId, issue.key);

    if (Array.isArray(issue.subTasks)) {
      issue.subTasks.forEach(subTask => map.set(subTask.refId, subTask.key));
    }

    return map;
  }, new Map());

  const createdLinks = await Promise.all(
    contents.links.map(link => {
      const newLink = {
        type: link.type,
        comment: link.comment,
        inwardIssue: { key: issueMap.get(link.inwardIssue) },
        outwardIssue: { key: issueMap.get(link.outwardIssue) },
      };

      return client.createIssueLink(newLink).then(() => newLink);
    })
  );

  return {
    epics: createdEpics,
    issues: createdIssues,
    links: createdLinks,
  };
}

module.exports = execute;
<|endoftext|>


<commit_before>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(true).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = 2;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = 1 + 1;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = "2";
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Worked Koan 5 (Finished AboutExpects)<commit_after>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(true).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = 2;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = 1 + 1;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = "2";
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(2);
  });
});
<|endoftext|>


<commit_before>'use strict';
var log = require('debug')('coinbase'),
  microtime = require('microtime'),
  request = require('request'),
  util = require('util'),
  cryptoJS = require('crypto-js');

function CoinbaseError (error) {
  Error.captureStackTrace(this, CoinbaseError);
  this.error = error;
}

util.inherits(CoinbaseError, Error);

CoinbaseError.prototype.toString = function toString () {
  return "CoinbaseError: " + this.error;
}

var counter = 0, last = '';
function getNonce() {
  counter++;
  var nonce = microtime.now() + '' + (100 + counter % 100);
  if (nonce < last) {
    console.log('REPEAT')
    nonce = getNonce();
    last = nonce;
  }
  return nonce;
}

function Coinbase (options) {
  if (!options || !options.APIKey || !options.APISecret)
    throw new CoinbaseError('Must provide an APIKey and APISecret in order to interact with the coinbase api');
  this.apiKey = options.APIKey;
  this.apiSecret = options.APISecret;
  this.baseUrl = 'https://coinbase.com/api/v1/';

  var self = this;

  this.account = {};

  function get (url, callback) {
    var nonce = getNonce();
    var message = nonce + url;
    var signature = cryptoJS.HmacSHA256(message, self.apiSecret);
    var reqObject = {
      url: url,
      headers: {
        'ACCESS_KEY': self.apiKey,
        'ACCESS_SIGNATURE': signature,
        'ACCESS_NONCE': nonce
      }
    }

    request.get(reqObject, function (err, res, data) {
      if (err) {
        callback(err);
      } else {
        try {
          data = JSON.parse(data);
          if (data.success === false || data.errors || data.error) {
            callback(new CoinbaseError(data.errors || data.error))
          } else {
            callback(null, data);
          }
        } catch (err) {
          callback(err);
        }
      }
    });
  }

  function post (url, param, callback) {
    var nonce = getNonce();
    var body = JSON.stringify(param);
    var message = nonce + url + body;
    var signature = cryptoJS.HmacSHA256(message, self.apiSecret);
    var reqObject = {
      headers: {
        'ACCESS_KEY': self.apiKey,
        'ACCESS_SIGNATURE': signature,
        'ACCESS_NONCE': nonce,
        'content-type': 'application/json'
      },
      url: url,
      body: body
    };

    request.post(reqObject, function (err, res, data) {
      if (err) {
        callback(err);
      } else if (res.statusCode !== 200) {
        callback(new CoinbaseError(res.headers.status));
      } else{
        try {
          data = JSON.parse(data);
          if (data.success === false) {
            callback(new CoinbaseError(data.errors || data.error));
          } else {
            callback(null, data);
          }
        } catch (err) {
          if (data.errors) {
            callback(new CoinbaseError(data.errors));
          } else {
            callback(data);
          }
        }
      }
    });
  }

  /* GET /api/v1/account/balance */
  this.account.balance = function (callback) {
    var url = self.baseUrl + 'account/balance';

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/account/receive_address */
  this.account.receiveAddress = function (callback) {
    var url = self.baseUrl + 'account/receive_address';

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/account/generate_receive_address */
  this.account.generateReceiveAddress = function (callbackUrl, label, callback) {
    if (!callback) {
      if (!label) {
        if (typeof callbackUrl === 'function') {
          callback = callbackUrl;
          callbackUrl = null;
        } else {
          throw new CoinbaseError("couldn't resolve callback function")
        }
      } else if (typeof label === 'function') {
        callback = label;
        label = null;
      } else {
        throw new CoinbaseError("couldn't resolve callback function");
      }
    }

    var url = self.baseUrl + 'account/generate_receive_address';
    var options = { api_key: self.apiKey };

    if (callbackUrl) options.address = { 'callback_url': callbackUrl, 'label': label };

    log('post ' + url + ' with options ' + util.inspect(options));

    post(url, options, callback);
  };

  this.buttons = {};
  /* POST https://coinbase.com/api/v1/buttons */
  this.buttons.create = function (param, callback) {
    var url = self.baseUrl + 'buttons';

    log('post ' + url);

    post(url, param, function (err, data) {
      if (err) {
        callback(err);
      } else {
        callback(null, data);
      }
    });
  };

  /* POST https://coinbase.com/api/v1/buys */
  this.buy = function (param, callback) {

    var url = self.baseUrl + 'buttons';

    log('post ' + url);

    post(url, param, callback);
  };

  /* /api/v1/contacts */
  this.contacts = function (callback) {
    var url = self.baseUrl + 'contacts';

    log('get ' + url);

    get(url, callback);
  };

  this.currencies = {};

  /* GET /api/v1/currencies */
  this.currencies.list = function (callback) {
    var url = self.baseUrl + 'currencies';

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/currencies/exchange_rates */
  this.currencies.exchangeRates = function (callback) {
    var url = self.baseUrl + 'currencies/exchange_rates';

    log('get ' + url);

    get(url, callback);
  };

  this.orders = {};

  /* GET /api/v1/orders */
  this.orders.list = function (callback) {
    var url = self.baseUrl + 'orders';

    log('get ' + url);

    get(url, callback);
  }

  /* GET /api/v1/orders/:id */
  this.orders.get = function (id, callback) {
    var url = self.baseUrl + 'orders/' + id;

    log('get ' + url);

    get(url, callback);
  }

  this.prices = {};

  /* GET /api/v1/prices/buy */
  this.prices.buy = function (options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }

    var url = self.baseUrl + 'prices/buy';
    var delim = '?';
    if (options.qty) {
      url = url + '?qty=' + options.qty;
      delim = '&';
    }
    if (options.currency) url = url + delim + 'currency=' + options.currency;

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/prices/sell */
  this.prices.sell = function (options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }

    var url = self.baseUrl + 'prices/sell';
    var delim = '?';
    if (options.qty) {
      url = url + '?qty=' + options.qty;
      delim = '&';
    }
    if (options.currency) url = url + delim + 'currency=' + options.currency;

    log('get ' + url);

    get(url, callback);
  };

  this.transactions = {};
  /* GET /api/v1/transactions */
  this.transactions.list = function (page, callback) {
    if (typeof page === 'function') {
      callback = page;
      page = 1;
    }

    var url = self.baseUrl + 'transactions' + '?page=' + page;

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/transactions/:id */
  this.transactions.get = function (id, callback) {
    var url = self.baseUrl + 'transactions/' + id;

    log('get ' + url);

    get(url, callback);
  };

  this.transfers = {};

  /* GET /api/v1/transfers */
  this.transfers.list = function (callback) {
    var url = self.baseUrl + 'transfers';

    log('get ' + url);

    get(url, callback);
  }

}

module.exports = Coinbase;<commit_msg>removing console stmt<commit_after>'use strict';
var log = require('debug')('coinbase'),
  microtime = require('microtime'),
  request = require('request'),
  util = require('util'),
  cryptoJS = require('crypto-js');

function CoinbaseError (error) {
  Error.captureStackTrace(this, CoinbaseError);
  this.error = error;
}

util.inherits(CoinbaseError, Error);

CoinbaseError.prototype.toString = function toString () {
  return "CoinbaseError: " + this.error;
}

var counter = 0, last = '';
function getNonce() {
  counter++;
  var nonce = microtime.now() + '' + (100 + counter % 100);
  if (nonce < last) {
    nonce = getNonce();
    last = nonce;
  }
  return nonce;
}

function Coinbase (options) {
  if (!options || !options.APIKey || !options.APISecret)
    throw new CoinbaseError('Must provide an APIKey and APISecret in order to interact with the coinbase api');
  this.apiKey = options.APIKey;
  this.apiSecret = options.APISecret;
  this.baseUrl = 'https://coinbase.com/api/v1/';

  var self = this;

  this.account = {};

  function get (url, callback) {
    var nonce = getNonce();
    var message = nonce + url;
    var signature = cryptoJS.HmacSHA256(message, self.apiSecret);
    var reqObject = {
      url: url,
      headers: {
        'ACCESS_KEY': self.apiKey,
        'ACCESS_SIGNATURE': signature,
        'ACCESS_NONCE': nonce
      }
    }

    request.get(reqObject, function (err, res, data) {
      if (err) {
        callback(err);
      } else {
        try {
          data = JSON.parse(data);
          if (data.success === false || data.errors || data.error) {
            callback(new CoinbaseError(data.errors || data.error))
          } else {
            callback(null, data);
          }
        } catch (err) {
          callback(err);
        }
      }
    });
  }

  function post (url, param, callback) {
    var nonce = getNonce();
    var body = JSON.stringify(param);
    var message = nonce + url + body;
    var signature = cryptoJS.HmacSHA256(message, self.apiSecret);
    var reqObject = {
      headers: {
        'ACCESS_KEY': self.apiKey,
        'ACCESS_SIGNATURE': signature,
        'ACCESS_NONCE': nonce,
        'content-type': 'application/json'
      },
      url: url,
      body: body
    };

    request.post(reqObject, function (err, res, data) {
      if (err) {
        callback(err);
      } else if (res.statusCode !== 200) {
        callback(new CoinbaseError(res.headers.status));
      } else{
        try {
          data = JSON.parse(data);
          if (data.success === false) {
            callback(new CoinbaseError(data.errors || data.error));
          } else {
            callback(null, data);
          }
        } catch (err) {
          if (data.errors) {
            callback(new CoinbaseError(data.errors));
          } else {
            callback(data);
          }
        }
      }
    });
  }

  /* GET /api/v1/account/balance */
  this.account.balance = function (callback) {
    var url = self.baseUrl + 'account/balance';

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/account/receive_address */
  this.account.receiveAddress = function (callback) {
    var url = self.baseUrl + 'account/receive_address';

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/account/generate_receive_address */
  this.account.generateReceiveAddress = function (callbackUrl, label, callback) {
    if (!callback) {
      if (!label) {
        if (typeof callbackUrl === 'function') {
          callback = callbackUrl;
          callbackUrl = null;
        } else {
          throw new CoinbaseError("couldn't resolve callback function")
        }
      } else if (typeof label === 'function') {
        callback = label;
        label = null;
      } else {
        throw new CoinbaseError("couldn't resolve callback function");
      }
    }

    var url = self.baseUrl + 'account/generate_receive_address';
    var options = { api_key: self.apiKey };

    if (callbackUrl) options.address = { 'callback_url': callbackUrl, 'label': label };

    log('post ' + url + ' with options ' + util.inspect(options));

    post(url, options, callback);
  };

  this.buttons = {};
  /* POST https://coinbase.com/api/v1/buttons */
  this.buttons.create = function (param, callback) {
    var url = self.baseUrl + 'buttons';

    log('post ' + url);

    post(url, param, function (err, data) {
      if (err) {
        callback(err);
      } else {
        callback(null, data);
      }
    });
  };

  /* POST https://coinbase.com/api/v1/buys */
  this.buy = function (param, callback) {

    var url = self.baseUrl + 'buttons';

    log('post ' + url);

    post(url, param, callback);
  };

  /* /api/v1/contacts */
  this.contacts = function (callback) {
    var url = self.baseUrl + 'contacts';

    log('get ' + url);

    get(url, callback);
  };

  this.currencies = {};

  /* GET /api/v1/currencies */
  this.currencies.list = function (callback) {
    var url = self.baseUrl + 'currencies';

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/currencies/exchange_rates */
  this.currencies.exchangeRates = function (callback) {
    var url = self.baseUrl + 'currencies/exchange_rates';

    log('get ' + url);

    get(url, callback);
  };

  this.orders = {};

  /* GET /api/v1/orders */
  this.orders.list = function (callback) {
    var url = self.baseUrl + 'orders';

    log('get ' + url);

    get(url, callback);
  }

  /* GET /api/v1/orders/:id */
  this.orders.get = function (id, callback) {
    var url = self.baseUrl + 'orders/' + id;

    log('get ' + url);

    get(url, callback);
  }

  this.prices = {};

  /* GET /api/v1/prices/buy */
  this.prices.buy = function (options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }

    var url = self.baseUrl + 'prices/buy';
    var delim = '?';
    if (options.qty) {
      url = url + '?qty=' + options.qty;
      delim = '&';
    }
    if (options.currency) url = url + delim + 'currency=' + options.currency;

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/prices/sell */
  this.prices.sell = function (options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }

    var url = self.baseUrl + 'prices/sell';
    var delim = '?';
    if (options.qty) {
      url = url + '?qty=' + options.qty;
      delim = '&';
    }
    if (options.currency) url = url + delim + 'currency=' + options.currency;

    log('get ' + url);

    get(url, callback);
  };

  this.transactions = {};
  /* GET /api/v1/transactions */
  this.transactions.list = function (page, callback) {
    if (typeof page === 'function') {
      callback = page;
      page = 1;
    }

    var url = self.baseUrl + 'transactions' + '?page=' + page;

    log('get ' + url);

    get(url, callback);
  };

  /* GET /api/v1/transactions/:id */
  this.transactions.get = function (id, callback) {
    var url = self.baseUrl + 'transactions/' + id;

    log('get ' + url);

    get(url, callback);
  };

  this.transfers = {};

  /* GET /api/v1/transfers */
  this.transfers.list = function (callback) {
    var url = self.baseUrl + 'transfers';

    log('get ' + url);

    get(url, callback);
  }

}

module.exports = Coinbase;<|endoftext|>


<commit_before>// Copyright (c) 2016 Junichi Kajiwara
// Released under the MIT license
// https://github.com/kjunichi/glsl2hls/blob/master/LICENSE

const fs = require('fs')
const assert = require('assert')
const Nightmare = require('nightmare')

describe('GLSL start page.', () => {
  let nightmare;

  beforeEach(()=> {
    // runs before each test in this block
    nightmare = Nightmare({
          show: false,
          switches: {'ignore-certificate-errors': 'true' }
    })
    nightmare.viewport(1024, 768)
        .on('console',(type,args) =>{
          console.log(args)
        })
        .goto('http://localhost:8000/static/index.html')
  });
  describe('index.html', () => {
    it('should index.html', (done) => {
        nightmare.evaluate(()=>{
          return document.body.innerHTML
        })
        .end()
        .then((result) => {
          console.log(`result = ${result}`)
          assert.notEqual(-1,result.indexOf('button '))
          done()
        })
        .catch((error) => {
          console.error('index.htlm failed:', error)
          done()
        })
    })
    it('should render GLSL', (done) => {
      nightmare.click('#btnRun')
        .wait(9000)
        .evaluate(()=>{
            return document.getElementById('out')
        })
        .end()
        .then(function (result) {
          console.log(`resulst = ${result}`)
          assert.notEqual(0, result.src.length)
          console.log(`result.src = ${result.src}`)
          done()
        })
        .catch(function (error) {
          console.error('render GLSL failed:', error);
          done()
        })
    })
  })
})

<commit_msg>Update test.js<commit_after>// Copyright (c) 2016 Junichi Kajiwara
// Released under the MIT license
// https://github.com/kjunichi/glsl2hls/blob/master/LICENSE

const fs = require('fs')
const assert = require('assert')
const Nightmare = require('nightmare')

describe('GLSL start page.', () => {
  let nightmare;

  beforeEach(()=> {
    // runs before each test in this block
    nightmare = Nightmare({
          show: false,
          switches: {'ignore-certificate-errors': 'true' }
    })
    nightmare.viewport(1024, 768)
        .on('console',(type,args) =>{
          console.log(args)
        })
        .goto('http://localhost:8000/static/index.html')
  });
  describe('index.html', () => {
    it('should index.html', (done) => {
        nightmare.evaluate(()=>{
          return document.body.innerHTML
        })
        .end()
        .then((result) => {
          console.log(`result = ${result}`)
          assert.notEqual(-1,result.indexOf('button '))
          done()
        })
        .catch((error) => {
          console.error('index.htlm failed:', error)
          done()
        })
    })
    it('should render GLSL', (done) => {
      nightmare.click('#btnRun')
        .wait(9000)
        .evaluate(()=>{
            return document.getElementById('out')
        })
        .end()
        .then(function (result) {
          console.dir(result)
          console.log(result.src)
          assert.notEqual(0, result.src.length)
          console.log(`result.src = ${result.src}`)
          done()
        })
        .catch(function (error) {
          console.error('render GLSL failed:', error);
          done()
        })
    })
  })
})

<|endoftext|>


<commit_before>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(false).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Finished editing "About Expects" koans<commit_after>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(true).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = 2;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = 2;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = '2';
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(2);
  });
});
<|endoftext|>


<commit_before>/*********************************************************************************
 1. Dependencies
 *********************************************************************************/

const Hoek = require('hoek');
const Raven = require('raven');
const Get = require('lodash/get');
const Trace = require('./trace');
const PluginPack = require('../package.json');

/*********************************************************************************
 2. Internals
 *********************************************************************************/

const internals = {};

internals.getRequestLevel = (request) => {

    return (Get(request, 'response.output.statusCode', '').toString().substr(0, 1) === '5') ? 'error' : 'info';
};

internals.getRequestData = (server, options, request, level) => {

    const requestInfo = Get(request, 'info', {});
    const serverInfo = Get(server, 'info', {});
    const url = requestInfo.uri ||
        requestInfo.host && `${serverInfo.protocol}://${requestInfo.host}` ||
        serverInfo.uri;

    return {
        request: {
            method: request.method,
            query_string: request.query,
            headers: request.headers,
            cookies: request.state,
            url: url + request.path
        },
        extra: {
            timestamp: requestInfo.received,
            id: request.id,
            remoteAddress: Trace(request),
            remotePort: requestInfo.remotePort
        },
        tags: options.tags,
        level,
    };
};

internals.onPreResponse = (server, options) => {

    return (request, reply) => {

        const requestResponse = Get(request, 'response', {});

        /* istanbul ignore else */
        if (requestResponse.isBoom === true) {

            let captureType;
            let captureDescription;
            const level = internals.getRequestLevel(request);

            if (level === 'error') {
                captureType = 'captureException';
                captureDescription = requestResponse;
            } else {
                captureType = 'captureMessage';
                captureDescription = requestResponse.message;
            }

            Raven[captureType](captureDescription, internals.getRequestData(server, options, request, level));
        }

        reply.continue();
    };
};

/*********************************************************************************
 3. Exports
 *********************************************************************************/

exports.register = (server, options, next) => {

    Hoek.assert(options, 'Missing `options` object');
    Hoek.assert(options.dsn, 'Missing `dsn` property');

    Raven.config(options.dsn, options.settings).install();

    server.ext('onPreResponse', internals.onPreResponse(server, options));
    server.expose('client', Raven);

    return next();
};

exports.register.attributes = {
    pkg: PluginPack
};
<commit_msg>chore(eslint): fixes<commit_after>/*********************************************************************************
 1. Dependencies
 *********************************************************************************/

const Hoek = require('hoek');
const Raven = require('raven');
const Get = require('lodash/get');
const Trace = require('./trace');
const PluginPack = require('../package.json');

/*********************************************************************************
 2. Internals
 *********************************************************************************/

const internals = {};

internals.getRequestLevel = (request) => {

    return (Get(request, 'response.output.statusCode', '').toString().substr(0, 1) === '5') ? 'error' : 'info';
};

internals.getRequestData = (server, options, request, level) => {

    const requestInfo = Get(request, 'info', {});
    const serverInfo = Get(server, 'info', {});
    const url = requestInfo.uri ||
        requestInfo.host && `${serverInfo.protocol}://${requestInfo.host}` ||
        serverInfo.uri;

    return {
        request: {
            method: request.method,
            query_string: request.query,
            headers: request.headers,
            cookies: request.state,
            url: url + request.path
        },
        extra: {
            timestamp: requestInfo.received,
            id: request.id,
            remoteAddress: Trace(request),
            remotePort: requestInfo.remotePort
        },
        tags: options.tags,
        level
    };
};

internals.onPreResponse = (server, options) => {

    return (request, reply) => {

        const requestResponse = Get(request, 'response', {});

        /* istanbul ignore else */
        if (requestResponse.isBoom === true) {
            let captureType;
            let captureDescription;
            const level = internals.getRequestLevel(request);

            if (level === 'error') {
                captureType = 'captureException';
                captureDescription = requestResponse;
            }
            else {
                captureType = 'captureMessage';
                captureDescription = requestResponse.message;
            }

            Raven[captureType](captureDescription, internals.getRequestData(server, options, request, level));
        }

        reply.continue();
    };
};

/*********************************************************************************
 3. Exports
 *********************************************************************************/

exports.register = (server, options, next) => {

    Hoek.assert(options.hasOwnProperty('dsn'), 'Missing `dsn` property');

    Raven.config(options.dsn, options.settings).install();

    server.ext('onPreResponse', internals.onPreResponse(server, options));
    server.expose('client', Raven);

    return next();
};

exports.register.attributes = {
    pkg: PluginPack
};
<|endoftext|>


<commit_before>var gulp = require('gulp')
var assert = require('assert')
var fs = require('fs')
var File = require('vinyl')
var rm = require('rimraf')

var cordova = require('../')

describe('gulp-cordovacli', function() {
  this.timeout(8000)

  describe('using a configuration file', function() {
    var CONFIG_FILE = '../fixtures.json'

    beforeEach(function(done) {
      gulp.src('.')
        .pipe(cordova(['create', 'test/test', 'test.test.test', 'Test'], { silent: true }))
        .on('close', function() {
          process.chdir('test/test')
          done()
        })
    })

    afterEach(function(done) {
      process.chdir('../../')
      rm('test/test', function() {
        done()
      })
    })

    it('should run the commands from the configuration file', function(done) {
      gulp.src(CONFIG_FILE)
        .pipe(cordova(false, { silent: true }))
        .on('close', function() {
          assert.equal(true, fs.existsSync(__dirname + '/test/platforms/browser'))

          done()
        })
    })

    it('should not use the config file if commands are passed', function(done) {
      gulp.src(CONFIG_FILE)
        .pipe(cordova(['plugins', 'add', 'org.apache.cordova.device'], { silent: true }))
        .on('close', function() {
          assert.equal(false, fs.existsSync(__dirname + '/test/platforms/browser'))

          done()
        })
    })
  })
})
<commit_msg>increase timeout<commit_after>var gulp = require('gulp')
var assert = require('assert')
var fs = require('fs')
var File = require('vinyl')
var rm = require('rimraf')

var cordova = require('../')

describe('gulp-cordovacli', function() {
  this.timeout(10000)

  describe('using a configuration file', function() {
    var CONFIG_FILE = '../fixtures.json'

    beforeEach(function(done) {
      gulp.src('.')
        .pipe(cordova(['create', 'test/test', 'test.test.test', 'Test'], { silent: true }))
        .on('close', function() {
          process.chdir('test/test')
          done()
        })
    })

    afterEach(function(done) {
      process.chdir('../../')
      rm('test/test', function() {
        done()
      })
    })

    it('should run the commands from the configuration file', function(done) {
      gulp.src(CONFIG_FILE)
        .pipe(cordova(false, { silent: true }))
        .on('close', function() {
          assert.equal(true, fs.existsSync(__dirname + '/test/platforms/browser'))

          done()
        })
    })

    it('should not use the config file if commands are passed', function(done) {
      gulp.src(CONFIG_FILE)
        .pipe(cordova(['plugins', 'add', 'org.apache.cordova.device'], { silent: true }))
        .on('close', function() {
          assert.equal(false, fs.existsSync(__dirname + '/test/platforms/browser'))

          done()
        })
    })
  })
})
<|endoftext|>


<commit_before>describe("About Expects", function() {

  // We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(false).toBeTruthy(); // This should be true
  });

  // To understand reality, we must compare our expectations against reality.
  it("should expect equality", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  // Some ways of asserting equality are better than others.
  it("should assert equality a better way", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  // Sometimes you need to be precise about what you "type".
  it("should assert equality with ===", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  // Sometimes we will ask you to fill in the values.
  it("should have filled in values", function() {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<commit_msg>AboutExpects filled in<commit_after>describe("About Expects", function() {

  // We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(false).toBeTruthy(); // This should be true
  });

  // To understand reality, we must compare our expectations against reality.
  it("should expect equality", function() {
	  var expectedValue = 2;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  // Some ways of asserting equality are better than others.
  it("should assert equality a better way", function() {
	  var expectedValue = "two";
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  // Sometimes you need to be precise about what you "type".
  it("should assert equality with ===", function() {
	  var expectedValue = "two";
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  // Sometimes we will ask you to fill in the values.
  it("should have filled in values", function() {
	  expect(1 + 1).toEqual(2);
  });
});
<|endoftext|>


<commit_before>'use strict';

const createTemplateKey = require('./createTemplateKey');
const addTemplateToModule = require('./addTemplateToModule');
const isComponent = require('./helpers/is-component');
const shortnames = require('./shortnames');

const VNodeFlags = {
	Text: 1,
	HtmlElement: 1 << 1,

	ComponentClass: 1 << 2,
	ComponentFunction: 1 << 3,

	HasKeyedChildren: 1 << 4,
	HasNonKeyedChildren: 1 << 5,

	SvgElement: 1 << 6,
	MediaElement: 1 << 7,
	InputElement: 1 << 8,
	TextareaElement: 1 << 9,
	SelectElement: 1 << 10,
	Fragment: 1 << 11,
	Void: 1 << 12,
};

function handleWhiteSpace(str) {
	str = str.replace(/\t/g, '');
	str = str.replace(/(\s*[\r\n]\s*)/g, '');
	return str;
}

function hasHyphenOrColon(attr) {
	return attr.indexOf('-') !== -1 || attr.indexOf(':') !== -1;
}

function getVNodeType(t, type) {
	const astType = type.type;
	let component = false;
	let flags = null;

	if (astType === 'JSXIdentifier') {
		if (isComponent(type.name)) {
			component = true;
		} else {
			const tag = type.name;

			type = t.StringLiteral(tag);
			switch (tag) {
				case 'svg':
					flags = VNodeFlags.SvgElement;
					break;
				case 'input':
					flags = VNodeFlags.InputElement;
					break;
				case 'textarea':
					flags = VNodeFlags.TextareaElement;
					break;
				case 'select':
					flags = VNodeFlags.SelectElement;
					break;
				case 'media':
					flags = VNodeFlags.MediaElement;
					break;
				default:
					flags = VNodeFlags.HtmlElement;
			}
		}
	} else if (astType === 'JSXMemberExpression') {
		component = true;
	}
	return {
		type,
		isComponent: component,
		flags: flags ? t.NumericLiteral(flags) : t.identifier('null')
	};
}

function getVNodeChildren(t, astChildren) {
	let children = [];

	for (let i = 0; i < astChildren.length; i++) {
		const child = astChildren[i];
		const vNode = createVNode(t, child);

		if (vNode != null) {
			children.push(vNode);
		}
	}
	return children.length === 1 ? children[0] : t.arrayExpression(children);
}

function getValue(t, value) {
	if (!value) {
		return t.BooleanLiteral(true);
	}
	const type = value.type;

	switch (type) {
		case 'JSXExpressionContainer':
			return value.expression;
		default:
			return value;
	}
}

function getName(t, name) {
	if (name.indexOf('-') !== 0) {
		return t.StringLiteral(name);
	} else {
		return t.identifier(name);
	}
}

function getVNodeProps(t, astProps, isComponent) {
	let props = null;
	let key = null;
	let ref = null;

	for (let i = 0; i < astProps.length; i++) {
		const astProp = astProps[i];

		if (!props) {
			props = [];
		}
		if (astProp.type === 'JSXSpreadAttribute') {
			props.push({
				astName: null,
				astValue: null,
				astSpread: astProp.argument
			});
		} else {
			const propName = astProp.name.name;

			if (propName.substr(0, 11) === 'onComponent' && isComponent) {
				if (!ref) {
					ref = t.ObjectExpression([]);
				}
				ref.properties.push(
					t.ObjectProperty(getName(t, propName), getValue(t, astProp.value))
				);
			} else {
				switch (propName) {
					case 'children':
						break;
					case 'ref':
						ref = getValue(t, astProp.value);
						break;
					case 'key':
						key = getValue(t, astProp.value);
						break;
					default:
						props.push({
							astName: getName(t, propName),
							astValue: getValue(t, astProp.value),
							astSpread: null
						});
				}
			}
		}
	}
	return {
		props: props == null ? t.identifier('null') : props = t.ObjectExpression(
			props.map(({ astName, astValue, astSpread }) =>
				!astSpread ?
					t.ObjectProperty(
						astName,
						astValue
					) :
					t.SpreadProperty(
						astSpread
					)
			)
		),
		key: key == null ? t.identifier('null') : key,
		ref: ref == null ? t.identifier('null') : ref
	};
}

function isAstNull(ast) {
	return !ast || ast.name === 'null';
}

function createVNodeArgs(t, flags, type, props, children, key, ref) {
	const args = [];

	if (!isAstNull(ref)) {
		args.unshift(ref);
	}
	if (!isAstNull(key)) {
		args.unshift(key);
	} else if (!isAstNull(ref)) {
		args.unshift(t.identifier('null'));
	}
	if (!isAstNull(children)) {
		if (children.type === 'ArrayExpression') {
			if (children.elements.length > 0) {
				args.unshift(children);
			} else {
				children = null;
			}
		} else {
			args.unshift(children);
		}
	} else if (!isAstNull(key)) {
		args.unshift(t.identifier('null'));
	}
	if (props.properties && props.properties.length > 0) {
		args.unshift(props);
	} else if (!isAstNull(children)) {
		args.unshift(t.identifier('null'));
	}
	args.unshift(type);
	args.unshift(flags);
	return args;
}

function createVNode(t, astNode) {
	const type = astNode.type;

	switch (type) {
		case 'JSXElement':
			const openingElement = astNode.openingElement;
			const { type, isComponent, flags } = getVNodeType(t, openingElement.name);
			let { props, key, ref } = getVNodeProps(t, openingElement.attributes, isComponent);
			let children = getVNodeChildren(t, astNode.children);

			if (isComponent && children) {
				let addChildrenToProps = true;

				if (children.type === 'ArrayExpression' && children.elements.length === 0) {
					addChildrenToProps = false;
				}
				if (addChildrenToProps) {
					if (props.properties) {
						props.properties.push(
							t.ObjectProperty(
								t.identifier('children'),
								children
							)
						);
					} else {
						props = t.ObjectExpression([
							t.ObjectProperty(
								t.identifier('children'),
								children
							)
						]);
					}
				}
				children = t.identifier('null');
			}

			return t.callExpression(
				t.memberExpression(t.identifier('Inferno'), t.identifier('createVNode')),
				createVNodeArgs(
					t,
					flags,
					type,
					props,
					children,
					key,
					ref
				)
			);
		case 'JSXText':
			const text = handleWhiteSpace(astNode.value);

			if (text !== '') {
				return t.StringLiteral(text);
			}
			break;
		case 'JSXExpressionContainer':
			return astNode.expression;
		default:
			// TODO
	}
}

module.exports = function (options) {
	const t = options.types;

	return {
		visitor: {
			JSXElement: {
				enter(path, state) {
					const opts = state.opts;
					const node = createVNode(t, path.node);

					path.replaceWith(node);
				}
			}
		},
		inherits: require('babel-plugin-syntax-jsx')
	};
};

<commit_msg>fixes wrong argument placement on vnodes<commit_after>'use strict';

const createTemplateKey = require('./createTemplateKey');
const addTemplateToModule = require('./addTemplateToModule');
const isComponent = require('./helpers/is-component');
const shortnames = require('./shortnames');

const VNodeFlags = {
	Text: 1,
	HtmlElement: 1 << 1,

	ComponentClass: 1 << 2,
	ComponentFunction: 1 << 3,

	HasKeyedChildren: 1 << 4,
	HasNonKeyedChildren: 1 << 5,

	SvgElement: 1 << 6,
	MediaElement: 1 << 7,
	InputElement: 1 << 8,
	TextareaElement: 1 << 9,
	SelectElement: 1 << 10,
	Fragment: 1 << 11,
	Void: 1 << 12,
};

function handleWhiteSpace(str) {
	str = str.replace(/\t/g, '');
	str = str.replace(/(\s*[\r\n]\s*)/g, '');
	return str;
}

function hasHyphenOrColon(attr) {
	return attr.indexOf('-') !== -1 || attr.indexOf(':') !== -1;
}

function getVNodeType(t, type) {
	const astType = type.type;
	let component = false;
	let flags = null;

	if (astType === 'JSXIdentifier') {
		if (isComponent(type.name)) {
			component = true;
		} else {
			const tag = type.name;

			type = t.StringLiteral(tag);
			switch (tag) {
				case 'svg':
					flags = VNodeFlags.SvgElement;
					break;
				case 'input':
					flags = VNodeFlags.InputElement;
					break;
				case 'textarea':
					flags = VNodeFlags.TextareaElement;
					break;
				case 'select':
					flags = VNodeFlags.SelectElement;
					break;
				case 'media':
					flags = VNodeFlags.MediaElement;
					break;
				default:
					flags = VNodeFlags.HtmlElement;
			}
		}
	} else if (astType === 'JSXMemberExpression') {
		component = true;
	}
	return {
		type,
		isComponent: component,
		flags: flags ? t.NumericLiteral(flags) : t.identifier('null')
	};
}

function getVNodeChildren(t, astChildren) {
	let children = [];

	for (let i = 0; i < astChildren.length; i++) {
		const child = astChildren[i];
		const vNode = createVNode(t, child);

		if (vNode != null) {
			children.push(vNode);
		}
	}
	return children.length === 1 ? children[0] : t.arrayExpression(children);
}

function getValue(t, value) {
	if (!value) {
		return t.BooleanLiteral(true);
	}
	const type = value.type;

	switch (type) {
		case 'JSXExpressionContainer':
			return value.expression;
		default:
			return value;
	}
}

function getName(t, name) {
	if (name.indexOf('-') !== 0) {
		return t.StringLiteral(name);
	} else {
		return t.identifier(name);
	}
}

function getVNodeProps(t, astProps, isComponent) {
	let props = null;
	let key = null;
	let ref = null;

	for (let i = 0; i < astProps.length; i++) {
		const astProp = astProps[i];

		if (!props) {
			props = [];
		}
		if (astProp.type === 'JSXSpreadAttribute') {
			props.push({
				astName: null,
				astValue: null,
				astSpread: astProp.argument
			});
		} else {
			const propName = astProp.name.name;

			if (propName.substr(0, 11) === 'onComponent' && isComponent) {
				if (!ref) {
					ref = t.ObjectExpression([]);
				}
				ref.properties.push(
					t.ObjectProperty(getName(t, propName), getValue(t, astProp.value))
				);
			} else {
				switch (propName) {
					case 'children':
						break;
					case 'ref':
						ref = getValue(t, astProp.value);
						break;
					case 'key':
						key = getValue(t, astProp.value);
						break;
					default:
						props.push({
							astName: getName(t, propName),
							astValue: getValue(t, astProp.value),
							astSpread: null
						});
				}
			}
		}
	}
	return {
		props: props == null ? t.identifier('null') : props = t.ObjectExpression(
			props.map(({ astName, astValue, astSpread }) =>
				!astSpread ?
					t.ObjectProperty(
						astName,
						astValue
					) :
					t.SpreadProperty(
						astSpread
					)
			)
		),
		key: key == null ? t.identifier('null') : key,
		ref: ref == null ? t.identifier('null') : ref
	};
}

function isAstNull(ast) {
	return !ast || ast.name === 'null';
}

function createVNodeArgs(t, flags, type, props, children, key, ref) {
	const args = [];

	if (!isAstNull(ref)) {
		args.unshift(ref);
	}
	if (!isAstNull(key)) {
		args.unshift(key);
	} else if (!isAstNull(ref)) {
		args.unshift(t.identifier('null'));
	}
	if (!isAstNull(children)) {
		if (children.type === 'ArrayExpression') {
			if (children.elements.length > 0) {
				args.unshift(children);
			} else {
				children = null;
			}
		} else {
			args.unshift(children);
		}
	} else if (!isAstNull(key)) {
		args.unshift(t.identifier('null'));
	} else if (!isAstNull(ref)) {
		args.unshift(t.identifier('null'));
	}
	if (props.properties && props.properties.length > 0) {
		args.unshift(props);
	} else if (!isAstNull(children)) {
		args.unshift(t.identifier('null'));
	} else if (!isAstNull(key)) {
		args.unshift(t.identifier('null'));
	} else if (!isAstNull(ref)) {
		args.unshift(t.identifier('null'));
	}
	args.unshift(type);
	args.unshift(flags);
	return args;
}

function createVNode(t, astNode) {
	const type = astNode.type;

	switch (type) {
		case 'JSXElement':
			const openingElement = astNode.openingElement;
			const { type, isComponent, flags } = getVNodeType(t, openingElement.name);
			let { props, key, ref } = getVNodeProps(t, openingElement.attributes, isComponent);
			let children = getVNodeChildren(t, astNode.children);

			if (isComponent && children) {
				let addChildrenToProps = true;

				if (children.type === 'ArrayExpression' && children.elements.length === 0) {
					addChildrenToProps = false;
				}
				if (addChildrenToProps) {
					if (props.properties) {
						props.properties.push(
							t.ObjectProperty(
								t.identifier('children'),
								children
							)
						);
					} else {
						props = t.ObjectExpression([
							t.ObjectProperty(
								t.identifier('children'),
								children
							)
						]);
					}
				}
				children = t.identifier('null');
			}

			return t.callExpression(
				t.memberExpression(t.identifier('Inferno'), t.identifier('createVNode')),
				createVNodeArgs(
					t,
					flags,
					type,
					props,
					children,
					key,
					ref
				)
			);
		case 'JSXText':
			const text = handleWhiteSpace(astNode.value);

			if (text !== '') {
				return t.StringLiteral(text);
			}
			break;
		case 'JSXExpressionContainer':
			return astNode.expression;
		default:
			// TODO
	}
}

module.exports = function (options) {
	const t = options.types;

	return {
		visitor: {
			JSXElement: {
				enter(path, state) {
					const opts = state.opts;
					const node = createVNode(t, path.node);

					path.replaceWith(node);
				}
			}
		},
		inherits: require('babel-plugin-syntax-jsx')
	};
};

<|endoftext|>


<commit_before>function traverseDOM(node){
  var childLen=node.childNodes.length;
  console.log(childLen);
  if(childLen==0){
  }else{
    for(var i=0;i<childLen;i++){
      var childTmp=node.childNodes[i];
      console.log(childTmp);
      if(childTmp.nodeName=="DIV"){
        if(childTmp.style){
          var obj=window.getComputedStyle(childTmp);
          if(obj.hasOwnProperty("position")){
            if(obj["position"]=="fixed"){
              console.log("the fixed element");
              console.log(childTmp);
              childTmp.style.display="none";
               return;
            }
          }
        }
      }
      traverseDOM(childTmp);
    }
  }
}
console.log(document.body);
traverseDOM(document.body);

<commit_msg>Update test.js<commit_after>function traverseDOM(node){
  var childLen=node.childNodes.length;
  if(childLen==0){
  }else{
    for(var i=0;i<childLen;i++){
      var childTmp=node.childNodes[i];
      if(childTmp.nodeName=="DIV"){
        if(childTmp.style){
          var obj=window.getComputedStyle(childTmp);
          if(obj.hasOwnProperty("position")){
            if(obj["position"]=="fixed"){
              console.log("the fixed element");
              console.log(childTmp);
              childTmp.style.display="none";
               return;
            }
          }
        }
      }
      traverseDOM(childTmp);
    }
  }
}
console.log(document.body);
traverseDOM(document.body);

<|endoftext|>


<commit_before>/*
   Implements different sort methods and displays the sorting steps
   to the user.
   Main source: Levitin A., Mukherje S. and Bhattacharjee AK. 2012.
   Introduction to the Design and Analysis of Algorithms.
   Third Edition. Pearson.

   Copyright (c) 2012 Nathan Geffen

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
   LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
   OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
   WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

"use strict";

/* TO DO: Drive the program from a JSON object that includes
   information on each sort.
var sortInfo = {
    "selectionSort": {
        "Name": "Selection sort",
        "Time efficiency": "θ (n2)"
    }

}

*/

var measurements = { "comparisons":0,
                     "swaps":0,
                     "moves":0,
                     "insertions":0,
                     "copies":0
                   }

var showsteps = true;
var outputHTML = "";

var generate = function() {
    var number_elements = document.
        getElementById("number-elements-edit").value;
    var list = [];

    if (document.getElementById("random-order").checked)
        for (var i = 0; i < number_elements; i++)
            list.push(Math.floor((Math.random() * number_elements)));
    else if (document.getElementById("ascending-order").checked)
        for (var i = 0; i < number_elements; i++)
            list.push(i);
    else
        for (var i = number_elements-1; i >= 0; i--)
            list.push(i);

    document.getElementById("list-to-sort").innerHTML = list.join(" ");
}

var sort = function() {

    var totalTime = 0;
    var basicOps = 0;

    document.getElementById("sort-button").disabled = true;
    var listToSort = document.getElementById("list-to-sort").
        value.rtrim().split(/\s+/);

    if(document.getElementById("numeric-choice").checked) {
        for (var i in listToSort)
            listToSort[i] = +listToSort[i];
    };

    var outputDiv = document.getElementById("output");
    outputDiv.innerHTML = "
List at start:
";
    output(listToSort);
    outputDiv.innerHTML += outputHTML;
    outputDiv.innerHTML += "
List length: " +
        listToSort.length + "
";

    outputHTML = "";
    showsteps = document.getElementById("show-steps").checked;
    if (showsteps && listToSort.length > 80) {
        outputDiv.innerHTML +=
        "
List too large to show steps.
"
        showsteps = false;
    }
    for (var op in measurements) measurements[op] = 0;
    basicOps = 0;

    if (listToSort.length) {
        var e = document.getElementById("sort-algorithm");
        var sortSelect = e.options[e.selectedIndex].value;

        var timeStart =  new Date().getTime();

        if (sortSelect == "selectionsort-choice")
            selectionsort(listToSort)
        else if (sortSelect == "insertionsort-choice")
            insertionsort(listToSort);
        else if (sortSelect == "bubblesort-choice")
            bubblesort(listToSort);
        else if (sortSelect == "mergesort-choice")
            mergesort(listToSort);
        else if (sortSelect == "quicksort-choice")
            quicksort(listToSort);
        else if (sortSelect == "heapsort-choice")
            heapsort(listToSort);
        else
            shellsort(listToSort);

        var timeEnd = new Date().getTime();
        totalTime = timeEnd - timeStart;
    }
    showsteps = true;
    outputDiv.innerHTML += outputHTML;
    outputHTML = "";
    outputDiv.innerHTML += "
List at end:
";
    output(listToSort);
    outputDiv.innerHTML += outputHTML;
    outputHTML = "";

    for (op in measurements) {
        if (measurements[op] > 0) {
            outputHTML += "
Number of " + op + ": "
                + measurements[op] + "
";
            basicOps += measurements[op];
        }
    }
    outputDiv.innerHTML += outputHTML;
    outputHTML = "";
    outputDiv.innerHTML += "
Basic operations: " + basicOps + "
";
    outputDiv.innerHTML += "
Sort time in milliseconds: " + totalTime + "
";
    document.getElementById("sort-button").disabled = false;
}

var output = function(list, index1, index2, operation, truncate) {
    if (!showsteps) return 1;
    var text = "
";
    var to = null != truncate ? truncate : list.length;
    for (var i=0; i<to; i++)  {
        if ( (null != index1 && i == index1) ||
             (null != index2 && i == index2) ) {
            text += "";
            text += list[i] + "\t";
            text += "";
        } else {
            text += list[i] + "\t";
        }
    }
    if (null != operation)
        text += "  " +
        operation + "";
    text += "
";
    outputHTML += text;
    return 1;
}

var selectionsort = function(list) {
    for (var i = 0; i < list.length-1; i++) {
        var min = i;
        for (var j = i+1; j<list.length; j++) {
            if (++measurements["comparisons"] &&
                output(list, j, min, "Comparing") &&
                list[j] < list[min])
                min = j;
        }
        ++measurements["swaps"];
        swap(list, i, min);
        output(list, i, min, "Swapped "+list[i]+" and "+ list[min]);
    }
}

var insertionsort = function(list) {
    for (var i = 1; i<list.length; i++) {
        var v = list[i];
        var j = i - 1;

        while(j>=0 &&
              output(list, j, -1, ("finding place to left for " + v)) &&
              ++measurements["comparisons"] &&
              list[j] > v) {
            ++measurements["moves"];
            list[j+1] = list[j];
            output(list, j, j+1, (list[j+1] + " > " + v + " so move it") );
            --j;
        }

        ++measurements["insertions"];
        list[j+1] = v;

        if (i != j+1)
            output(list, i, j+1,
                   (v + " > than everything to left, so insert it"));
    }
};

var bubblesort = function(list) {
    var sorted;
    for (var i = 0; i<list.length - 1; i++) {
        for (var j = 0; j<list.length-1-i; j++) {
            sorted = true;
            if (++measurements["comparisons"] &&
                output(list, j+1, j, "Comparing "+list[j]+" to "+list[j+1]) &&
                list[j+1] < list[j]) {
                sorted = false;
                ++measurements["swaps"];
                swap(list, j, j+1);
                output(list, j, j+1, "Swapped");
            }
        }
        if (sorted) {
            output(list, -1, -1, "List is sorted. Finishing early.");
            break;
        }
    }
}

var copy = function(A, from, to, C, insertpoint) {
    var j = insertpoint;
    for (var i=from; i<to; i++) {
        ++measurements["copies"];
        C[j] = A[i];
        j++;
    }
}

var merge = function(B, C, A) {

    var i=0, j=0, k=0;
    var p = B.length, q = C.length;

    output((B+","+"|,"+C).split(","), -1, -1,
           "Merging these two lists.");

    while(i<p && j<q) {
        if (++measurements["comparisons"] && B[i] <= C[j]) {
            output((B+","+"|,"+C).split(","), i, B.length+j+1,
                   (B[i] + " <= ") + C[j]);
            ++measurements["moves"];
            A[k] = B[i];
            output(A, k, -1, "Moving " + A[k] + " into merged list.",
                  k+1);
            ++i;
        }
        else {
            output((B+","+"|,"+C).split(","), i, B.length+j+1,
                   (B[i] + " > ") + C[j], k);
            ++measurements["moves"];
            A[k] = C[j];
            output(A, k, -1, "Moving " + A[k] + " into merged list.",
                   k+1);
            ++j;
        }
        ++k;
    }
    if (i == p)
        copy(C, j, C.length, A, k);
    else
        copy(B, i, B.length, A, k);
    output(A, -1, -1, "Merge completed");
}

var mergesort = function(A) {

    if (A.length > 1) {
        var B = new Array();
        var C = new Array();
        copy(A, 0, Math.floor(A.length/2), B, 0);
        copy(A, Math.floor(A.length/2), A.length, C, 0);
        output(B, -1, -1, "Divide");
        mergesort(B);
        output(C, -1, -1, "Divide");
        mergesort(C);
        merge(B, C, A);
    }
}

var swap = function(A, i1, i2) {
  var t = A[i1];
  A[i1] = A[i2];
  A[i2] = t;
}

var hoarePartition = function(A, l, r) {

    var p = A[l];
    var i = l;
    var j = r + 1;

    do {
        do {
            ++i;
        } while (++measurements["comparisons"] &&
                 output(A, l, i, "Moving forward and comparing to pivot") &&
                 A[i]
 p);
        output(A, i, j, "Swapping");
        ++measurements["swaps"];
        swap(A, i, j);
    } while( i < j);
    output(A, i, j, "Undoing extra swap");
    swap(A, i, j);
    output(A, l, j, "Swapping pivot into correct position");
    swap(A, l, j);
    return j;
}

var qsort = function(A, l, r) {
    if (l < r) {
        var s = hoarePartition(A, l, r);
        qsort(A, l, s-1);
        qsort(A, s+1, r);
    }
}

var quicksort = function(A) {
    qsort(A, 0, A.length-1);
}

/*
   Implementation of heap sort.
   Code adapted from
   http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/heap/heapen.htm
 */

var downheap = function(A, v, n, desc) {
    var w=2*v+1;    // first descendant of v
    while (w<n) {
        if (w+1<n)    // is there a second descendant?
            if (output(A, w+1, v, desc + "Looking for 2nd descendent of " + A[v]) &&
                ++measurements["comparisons"] &&
                A[w+1]>A[w])
                w++;
        // w is the descendant of v with maximum label

        if (output(A, v, w, desc + "Checking for heap property.") &&
            ++measurements["comparisons"] &&
            A[v]>=A[w])
            return;  // v has heap property
        // otherwise
        ++measurements["swaps"];
        swap(A, v, w);  // exchange labels of v and w
        output(A, v, w, desc + "Swapping to satisfy heap property.")
        v=w;        // continue
        w=2*v+1;
    }
}

var buildheap = function(A, n) {
    for (var v=Math.floor(n/2)-1; v>=0; v--)
        downheap(A, v, n, "In heap construction. ");
}

var heapsort = function(A) {
    var n=A.length;
    buildheap(A, n);
    while (n>1) {
        n--;
        output(A, 0, n, "Before swap during maximum deletions.");
        swap(A, 0, n);
        output(A, 0, n, "After swap during maximum deletions.");
        downheap(A, 0, n, "Rebuilding heap in maximum deletions. ");
    }
}

/*
  Based on the pseudo-code for Shellsort at
  http://en.wikipedia.org/wiki/Shellsort
*/

var shellsort = function(list) {
    var gaps = [701, 301, 132, 57, 23, 10, 4, 1];

    for(var gap in gaps) {
        for (var i = gap; i < list.length; ++i) {
            var temp = list[i];
            for (var j = i; j >= gap &&
                 ++measurements["comparisons"] &&
                 list[j - gap] > temp; j -= gap) {
                list[j] = list[j - gap]
            }
            list[j] = temp
        }
    }
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

<commit_msg>Corrected swap count in qsort.<commit_after>/*
   Implements different sort methods and displays the sorting steps
   to the user.
   Main source: Levitin A., Mukherje S. and Bhattacharjee AK. 2012.
   Introduction to the Design and Analysis of Algorithms.
   Third Edition. Pearson.

   Copyright (c) 2012 Nathan Geffen

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
   LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
   OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
   WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

"use strict";

/* TO DO: Drive the program from a JSON object that includes
   information on each sort.
var sortInfo = {
    "selectionSort": {
        "Name": "Selection sort",
        "Time efficiency": "θ (n2)"
    }

}

*/

var measurements = { "comparisons":0,
                     "swaps":0,
                     "moves":0,
                     "insertions":0,
                     "copies":0
                   }

var showsteps = true;
var outputHTML = "";

var generate = function() {
    var number_elements = document.
        getElementById("number-elements-edit").value;
    var list = [];

    if (document.getElementById("random-order").checked)
        for (var i = 0; i < number_elements; i++)
            list.push(Math.floor((Math.random() * number_elements)));
    else if (document.getElementById("ascending-order").checked)
        for (var i = 0; i < number_elements; i++)
            list.push(i);
    else
        for (var i = number_elements-1; i >= 0; i--)
            list.push(i);

    document.getElementById("list-to-sort").innerHTML = list.join(" ");
}

var sort = function() {

    var totalTime = 0;
    var basicOps = 0;

    document.getElementById("sort-button").disabled = true;
    var listToSort = document.getElementById("list-to-sort").
        value.rtrim().split(/\s+/);

    if(document.getElementById("numeric-choice").checked) {
        for (var i in listToSort)
            listToSort[i] = +listToSort[i];
    };

    var outputDiv = document.getElementById("output");
    outputDiv.innerHTML = "
List at start:
";
    output(listToSort);
    outputDiv.innerHTML += outputHTML;
    outputDiv.innerHTML += "
List length: " +
        listToSort.length + "
";

    outputHTML = "";
    showsteps = document.getElementById("show-steps").checked;
    if (showsteps && listToSort.length > 80) {
        outputDiv.innerHTML +=
        "
List too large to show steps.
"
        showsteps = false;
    }
    for (var op in measurements) measurements[op] = 0;
    basicOps = 0;

    if (listToSort.length) {
        var e = document.getElementById("sort-algorithm");
        var sortSelect = e.options[e.selectedIndex].value;

        var timeStart =  new Date().getTime();

        if (sortSelect == "selectionsort-choice")
            selectionsort(listToSort)
        else if (sortSelect == "insertionsort-choice")
            insertionsort(listToSort);
        else if (sortSelect == "bubblesort-choice")
            bubblesort(listToSort);
        else if (sortSelect == "mergesort-choice")
            mergesort(listToSort);
        else if (sortSelect == "quicksort-choice")
            quicksort(listToSort);
        else if (sortSelect == "heapsort-choice")
            heapsort(listToSort);
        else
            shellsort(listToSort);

        var timeEnd = new Date().getTime();
        totalTime = timeEnd - timeStart;
    }
    showsteps = true;
    outputDiv.innerHTML += outputHTML;
    outputHTML = "";
    outputDiv.innerHTML += "
List at end:
";
    output(listToSort);
    outputDiv.innerHTML += outputHTML;
    outputHTML = "";

    for (op in measurements) {
        if (measurements[op] > 0) {
            outputHTML += "
Number of " + op + ": "
                + measurements[op] + "
";
            basicOps += measurements[op];
        }
    }
    outputDiv.innerHTML += outputHTML;
    outputHTML = "";
    outputDiv.innerHTML += "
Basic operations: " + basicOps + "
";
    outputDiv.innerHTML += "
Sort time in milliseconds: " + totalTime + "
";
    document.getElementById("sort-button").disabled = false;
}

var output = function(list, index1, index2, operation, truncate) {
    if (!showsteps) return 1;
    var text = "
";
    var to = null != truncate ? truncate : list.length;
    for (var i=0; i<to; i++)  {
        if ( (null != index1 && i == index1) ||
             (null != index2 && i == index2) ) {
            text += "";
            text += list[i] + "\t";
            text += "";
        } else {
            text += list[i] + "\t";
        }
    }
    if (null != operation)
        text += "  " +
        operation + "";
    text += "
";
    outputHTML += text;
    return 1;
}

var selectionsort = function(list) {
    for (var i = 0; i < list.length-1; i++) {
        var min = i;
        for (var j = i+1; j<list.length; j++) {
            if (++measurements["comparisons"] &&
                output(list, j, min, "Comparing") &&
                list[j] < list[min])
                min = j;
        }
        ++measurements["swaps"];
        swap(list, i, min);
        output(list, i, min, "Swapped "+list[i]+" and "+ list[min]);
    }
}

var insertionsort = function(list) {
    for (var i = 1; i<list.length; i++) {
        var v = list[i];
        var j = i - 1;

        while(j>=0 &&
              output(list, j, -1, ("finding place to left for " + v)) &&
              ++measurements["comparisons"] &&
              list[j] > v) {
            ++measurements["moves"];
            list[j+1] = list[j];
            output(list, j, j+1, (list[j+1] + " > " + v + " so move it") );
            --j;
        }

        ++measurements["insertions"];
        list[j+1] = v;

        if (i != j+1)
            output(list, i, j+1,
                   (v + " > than everything to left, so insert it"));
    }
};

var bubblesort = function(list) {
    var sorted;
    for (var i = 0; i<list.length - 1; i++) {
        for (var j = 0; j<list.length-1-i; j++) {
            sorted = true;
            if (++measurements["comparisons"] &&
                output(list, j+1, j, "Comparing "+list[j]+" to "+list[j+1]) &&
                list[j+1] < list[j]) {
                sorted = false;
                ++measurements["swaps"];
                swap(list, j, j+1);
                output(list, j, j+1, "Swapped");
            }
        }
        if (sorted) {
            output(list, -1, -1, "List is sorted. Finishing early.");
            break;
        }
    }
}

var copy = function(A, from, to, C, insertpoint) {
    var j = insertpoint;
    for (var i=from; i<to; i++) {
        ++measurements["copies"];
        C[j] = A[i];
        j++;
    }
}

var merge = function(B, C, A) {

    var i=0, j=0, k=0;
    var p = B.length, q = C.length;

    output((B+","+"|,"+C).split(","), -1, -1,
           "Merging these two lists.");

    while(i<p && j<q) {
        if (++measurements["comparisons"] && B[i] <= C[j]) {
            output((B+","+"|,"+C).split(","), i, B.length+j+1,
                   (B[i] + " <= ") + C[j]);
            ++measurements["moves"];
            A[k] = B[i];
            output(A, k, -1, "Moving " + A[k] + " into merged list.",
                  k+1);
            ++i;
        }
        else {
            output((B+","+"|,"+C).split(","), i, B.length+j+1,
                   (B[i] + " > ") + C[j], k);
            ++measurements["moves"];
            A[k] = C[j];
            output(A, k, -1, "Moving " + A[k] + " into merged list.",
                   k+1);
            ++j;
        }
        ++k;
    }
    if (i == p)
        copy(C, j, C.length, A, k);
    else
        copy(B, i, B.length, A, k);
    output(A, -1, -1, "Merge completed");
}

var mergesort = function(A) {

    if (A.length > 1) {
        var B = new Array();
        var C = new Array();
        copy(A, 0, Math.floor(A.length/2), B, 0);
        copy(A, Math.floor(A.length/2), A.length, C, 0);
        output(B, -1, -1, "Divide");
        mergesort(B);
        output(C, -1, -1, "Divide");
        mergesort(C);
        merge(B, C, A);
    }
}

var swap = function(A, i1, i2) {
  var t = A[i1];
  A[i1] = A[i2];
  A[i2] = t;
}

var hoarePartition = function(A, l, r) {

    var p = A[l];
    var i = l;
    var j = r + 1;

    do {
        do {
            ++i;
        } while (++measurements["comparisons"] &&
                 output(A, l, i, "Moving forward and comparing to pivot") &&
                 A[i]
 p);
        output(A, i, j, "Swapping");
        ++measurements["swaps"];
        swap(A, i, j);
    } while( i < j);
    ++measurements["swaps"];
    output(A, i, j, "Undoing extra swap");
    swap(A, i, j);
    ++measurements["swaps"];
    output(A, l, j, "Swapping pivot into correct position");
    swap(A, l, j);
    return j;
}

var qsort = function(A, l, r) {
    if (l < r) {
        var s = hoarePartition(A, l, r);
        qsort(A, l, s-1);
        qsort(A, s+1, r);
    }
}

var quicksort = function(A) {
    qsort(A, 0, A.length-1);
}

/*
   Implementation of heap sort.
   Code adapted from
   http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/heap/heapen.htm
 */

var downheap = function(A, v, n, desc) {
    var w=2*v+1;    // first descendant of v
    while (w<n) {
        if (w+1<n)    // is there a second descendant?
            if (output(A, w+1, v, desc + "Looking for 2nd descendent of " + A[v]) &&
                ++measurements["comparisons"] &&
                A[w+1]>A[w])
                w++;
        // w is the descendant of v with maximum label

        if (output(A, v, w, desc + "Checking for heap property.") &&
            ++measurements["comparisons"] &&
            A[v]>=A[w])
            return;  // v has heap property
        // otherwise
        ++measurements["swaps"];
        swap(A, v, w);  // exchange labels of v and w
        output(A, v, w, desc + "Swapping to satisfy heap property.")
        v=w;        // continue
        w=2*v+1;
    }
}

var buildheap = function(A, n) {
    for (var v=Math.floor(n/2)-1; v>=0; v--)
        downheap(A, v, n, "In heap construction. ");
}

var heapsort = function(A) {
    var n=A.length;
    buildheap(A, n);
    while (n>1) {
        n--;
        output(A, 0, n, "Before swap during maximum deletions.");
        swap(A, 0, n);
        output(A, 0, n, "After swap during maximum deletions.");
        downheap(A, 0, n, "Rebuilding heap in maximum deletions. ");
    }
}

/*
  Based on the pseudo-code for Shellsort at
  http://en.wikipedia.org/wiki/Shellsort
*/

var shellsort = function(list) {
    var gaps = [701, 301, 132, 57, 23, 10, 4, 1];

    for(var gap in gaps) {
        for (var i = gap; i < list.length; ++i) {
            var temp = list[i];
            for (var j = i; j >= gap &&
                 ++measurements["comparisons"] &&
                 list[j - gap] > temp; j -= gap) {
                list[j] = list[j - gap]
            }
            list[j] = temp
        }
    }
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

<|endoftext|>


<commit_before>describe("About Objects", function () {

  describe("Properties", function () {
    var meglomaniac;

    beforeEach(function () {
       meglomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(meglomaniac.mastermind).toBe(FILL_ME_IN);
    });

    it("should confirm that properties are case sensitive", function () {
      expect(meglomaniac.henchwoman).toBe(FILL_ME_IN);
      expect(meglomaniac.henchWoman).toBe(FILL_ME_IN);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var meglomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect(FILL_ME_IN).toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date()
    var currentYear = (currentDate.getFullYear());
    var meglomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(FILL_ME_IN);
    expect(meglomaniac.calculateAge()).toBe(FILL_ME_IN);
  });

  describe("'in' keyword", function () {
    var meglomaniac;
    beforeEach(function () {
      meglomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in meglomaniac;

      expect(hasBomb).toBe(FILL_ME_IN);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in meglomaniac;

      expect(hasDetonator).toBe(FILL_ME_IN);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in meglomaniac).toBe(FILL_ME_IN);

    meglomaniac.secretary = "Agent Smith";
    expect("secretary" in meglomaniac).toBe(FILL_ME_IN);

    delete meglomaniac.henchman;
    expect("henchman" in meglomaniac).toBe(FILL_ME_IN);
  });

  it("should use prototype to add to all objects", function () {
    function Circle(radius)
    {
      this.radius = radius;
    }

    var simpleCircle = new Circle(10);
    var colouredCircle = new Circle(5);
    colouredCircle.colour = "red";

    expect(simpleCircle.colour).toBe(FILL_ME_IN);
    expect(colouredCircle.colour).toBe(FILL_ME_IN);

    Circle.prototype.describe = function () {
      return "This circle has a radius of: " + this.radius;
    };

    expect(simpleCircle.describe()).toBe(FILL_ME_IN);
    expect(colouredCircle.describe()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Added AboutObjects<commit_after>describe("About Objects", function () {

  describe("Properties", function () {
    var meglomaniac;

    beforeEach(function () {
       meglomaniac = {  mastermind: "Joker", henchwoman: "Harley" };
    });

    it("should confirm objects are collections of properties", function () {
      expect(meglomaniac.mastermind).toBe("Joker");
    });

    it("should confirm that properties are case sensitive", function () {
      expect(meglomaniac.henchwoman).toBe("Harley");
      expect(meglomaniac.henchWoman).toBe(undefined);
    });
  });

  it("should know properties that are functions act like methods", function () {
    var meglomaniac = {
      mastermind : "Brain",
      henchman: "Pinky",
      battleCry: function (noOfBrains) {
        return "They are " + this.henchman + " and the" +
          Array(noOfBrains + 1).join(" " + this.mastermind);
      }
    };

    var battleCry = meglomaniac.battleCry(4);
    expect("They are Pinky and the Brain Brain Brain Brain Brain").toMatch(battleCry);
  });

  it("should confirm that when a function is attached to an object, 'this' refers to the object", function () {
    var currentDate = new Date()
    var currentYear = (currentDate.getFullYear());
    var meglomaniac = {
      mastermind: "James Wood",
      henchman: "Adam West",
      birthYear: 1970,
      calculateAge: function () {
        return currentYear - this.birthYear;
      }
    };

    expect(currentYear).toBe(2013);
    expect(meglomaniac.calculateAge()).toBe(43);
  });

  describe("'in' keyword", function () {
    var meglomaniac;
    beforeEach(function () {
      meglomaniac = {
        mastermind: "The Monarch",
        henchwoman: "Dr Girlfriend",
        theBomb: true
      };
    });

    it("should have the bomb", function () {

      var hasBomb = "theBomb" in meglomaniac;

      expect(hasBomb).toBe(true);
    });

    it("should not have the detonator however", function () {

      var hasDetonator = "theDetonator" in meglomaniac;

      expect(hasDetonator).toBe(false);
    });
  });

  it("should know that properties can be added and deleted", function () {
    var meglomaniac = { mastermind : "Agent Smith", henchman: "Agent Smith" };

    expect("secretary" in meglomaniac).toBe(false);

    meglomaniac.secretary = "Agent Smith";
    expect("secretary" in meglomaniac).toBe(true);

    delete meglomaniac.henchman;
    expect("henchman" in meglomaniac).toBe(false);
  });

  it("should use prototype to add to all objects", function () {
    function Circle(radius)
    {
      this.radius = radius;
    }

    var simpleCircle = new Circle(10);
    var colouredCircle = new Circle(5);
    colouredCircle.colour = "red";

    expect(simpleCircle.colour).toBe(undefined);
    expect(colouredCircle.colour).toBe("red");

    Circle.prototype.describe = function () {
      return "This circle has a radius of: " + this.radius;
    };

    expect(simpleCircle.describe()).toBe("This circle has a radius of: 10");
    expect(colouredCircle.describe()).toBe("This circle has a radius of: 5");
  });
});
<|endoftext|>