text:
require 'spec_helper'

RSpec.describe Embryo::Operations::People::UpdatePerson do
  subject(:update_person) { described_class.new }

  describe '#call' do
    context 'when the person exists' do
      let!(:person) { create :person, name: 'Big Brother', born_at: '04/04/1984' }

      context 'and the person attributes are valid' do
        let(:valid_attributes) { { name: 'Dr. Big Brother' } }

        it 'updates a person' do
          update_person.(person.id, valid_attributes)

          expect(person.reload.name).to eq('Dr. Big Brother')
        end

        it 'returns a person' do
          result = update_person.(person.id, valid_attributes)

          expect(result.value).to be_an_instance_of(Embryo::Person)
        end

        it 'is a success' do
          result = update_person.(person.id, valid_attributes)

          expect(result).to be_success
        end
      end

      context 'when the person attributes are invalid' do
        let(:invalid_attributes) { { naame: 'Boris' } }

        it 'does not update a person' do
          update_person.(person.id, invalid_attributes)

          expect(person.reload.name).to eq('Big Brother')
        end

        it 'returns an error code and an error message' do
          result = update_person.(person.id, invalid_attributes)

          expect(result.code).to eq(:not_updated)
          expect(result.value).to contain_exactly('name is missing')
        end

        it 'is a failure' do
          result = update_person.(person.id, invalid_attributes)

          expect(result).to be_failure
        end
      end
    end

    context 'when the person does not exist' do
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
git-up(1) -- fetch and rebase all locally-tracked remote branches
=================================================================

[![Code Climate](https://codeclimate.com/github/aanand/git-up.png)](https://codeclimate.com/github/aanand/git-up)

WARNING
-------

This project is no longer maintained, for several reasons:

- I've stopped using the workflow that made it relevant to me.
- Git 2.0 updated the default behaviour to remove the main problem it was solving (by changing the default behaviour of `git push` so it acts only on the current branch, instead of all branches).
- As of Git 2.9, `git pull --rebase --autostash` does basically the same thing.

Accordingly, if you update to Git 2.9 or later, you can use this alias instead of installing `git-up`:

    git config --global alias.up 'pull --rebase --autostash'

If you'd rather this happened on every `git pull`, then you can do this:

    git config --global pull.rebase true
    git config --global rebase.autoStash true

SYNOPSIS
--------

`git pull` has two problems:

* It merges upstream changes by default, when it's really more polite to [rebase over them](http://gitready.com/advanced/2009/02/11/pull-with-rebase.html), unless your collaborators enjoy a commit graph that looks like bedhead.
* It only updates the branch you're currently on, which means `git push` will shout at you for being behind on branches you don't particularly care about right now.

Solve them once and for all.

INSTALL
-------

    $ gem install git-up

Windows support is predictably absent. Try the [Python port](https://github.com/msiemens/PyGitUp), which was started for that reason.

USE
---

![$ git up](http://dl.dropbox.com/u/166030/git-up/screenshot.png)

ALTHOUGH
--------

`git-up` is working well for a lot of people, but a rigorous proof has yet to be formulated that it will definitely not mess with your git setup, delete data or post inane drivel to Hacker News on your behalf. Best practice is to delete your Hacker News account before installing.

DIFFICULTIES
------------

### Windows
Windows support is an ongoing pain. Have a look at [this ticket](https://github.com/aanand/git-up/issues/34) if you really need it, or if you're bored.

### spawn.rb:187:in `_pspawn': Invalid command name (ArgumentError)

If you're using RVM and you get this error, [read this](https://github.com/aanand/git-up/blob/master/RVM.md).

CONFIGURATION
-------------

`git-up` has a few configuration options, which use git's configuration system. Each can be set either globally or per-project. To set an option globally, append the `--global` flag to `git config`, which you can run anywhere:

    git config --global git-up.bundler.check true

To set it within a project, run the command inside that project's directory and omit the `--global` flag:

    cd myproject
    git config git-up.bundler.check true

### git-up.bundler.check [true|false]

Default: **false**. If **true**, git-up will check your app for any new bundled gems and suggest a `bundle install` if necessary.

### git-up.bundler.autoinstall [true|false]

Default: **false**. If **true**, and if `git-up.bundler.check` is also set to **true**, git-up will run `bundle install` for you if it finds missing gems.

### git-up.fetch.prune [true|false]

Default: **true**. Append the `--prune` flag when running `git fetch`, if your git version supports it (1.6.6 or greater), telling it to [remove any remote tracking branches which no longer exist on the remote](http://linux.die.net/man/1/git-fetch).

### git-up.fetch.all [true|false]

Default: **false**. Normally, git-up will only fetch remotes for which there is at least one local tracking branch. Setting this option to **true** will make git-up always fetch from all remotes, which is useful if e.g. you use a remote to push to your CI system but never check those branches out.

### git-up.rebase.arguments [string]

Default: **unset**. Additional arguments to pass to `git rebase`. For example, setting this to `--preserve-merges` will recreate your merge commits in the rebased branch.

### git-up.rebase.auto [true|false]

Default: **true**. If this option is set to **false**, git-up will not rebase branches for you. Instead, it will print a message saying they are diverged and let you handle rebasing them later. This can be useful if you have a lot of in-progress work that you don't want to deal with at once, but still want to update other branches.

### git-up.rebase.log-hook "COMMAND"

Default: **unset**. Runs **COMMAND** every time a branch is rebased or fast-forwarded, with the old head as **$1** and the new head as **$2**. This can be used to view logs or diffs of incoming changes. For example: `'echo "changes on $1:"; git log --oneline --decorate $1..$2'`


text:
'use strict';

var Network = require('../protocol/network');
var AsyncObject = require('../utils/async');
var RPCClient = require('./rpcclient');
var Amount = require('../btc/amount');
var util = require('../utils/util');
var co = require('../utils/co');
var request = require('./request').promise;

/**
 * Decentraland HTTP client.
 * @exports HTTPClient
 * @constructor
 * @param {String} uri
 * @param {Object?} options
 */

function HTTPClient(options) {
  if (!(this instanceof HTTPClient))
    return new HTTPClient(options);

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { uri: options };

  AsyncObject.call(this);

  this.options = options;
  this.network = Network.get(options.network);

  this.uri = options.uri || 'http://localhost:' + this.network.rpcPort;
  this.socket = null;
  this.apiKey = options.apiKey;
  this.auth = options.auth;
  this.rpc = new RPCClient(options);
}

util.inherits(HTTPClient, AsyncObject);

/**
 * Open the client, wait for socket to connect.
 * @alias HTTPClient#open
 * @returns {Promise}
 */

HTTPClient.prototype._open = co(function* _open() {
  var self = this;
  var IOClient;

  try {
    IOClient = require('socket.io-client');
  } catch (e) {
    ;
  }

  if (!IOClient)
    return;

  this.socket = new IOClient(this.uri, {
    transports: ['websocket'],
    forceNew: true
  });

  this.socket.on('error', function(err) {
    self.emit('error', err);
  });

  this.socket.on('version', function(info) {
    if (info.network !== self.network.type)
      self.emit('error', new Error('Wrong network.'));
  });

  this.socket.on('wallet tx', function(details) {
    self.emit('tx', details);
  });

  this.socket.on('wallet confirmed', function(details) {
    self.emit('confirmed', details);
  });

  this.socket.on('wallet unconfirmed', function(details) {
    self.emit('unconfirmed', details);
  });

  this.socket.on('wallet conflict', function(details) {
    self.emit('conflict', details);
  });

  this.socket.on('wallet updated', function(details) {
    self.emit('updated', details);
  });

  this.socket.on('wallet address', function(receive) {
    self.emit('address', receive);
  });

  this.socket.on('wallet balance', function(balance) {
    self.emit('balance', balance);
  });

  yield this._onConnect();
  yield this._sendAuth();
});

/**
 * Close the client, wait for the socket to close.
 * @alias HTTPClient#close
 * @returns {Promise}
 */

HTTPClient.prototype._close = function close() {
  if (!this.socket)
    return Promise.resolve();

  this.socket.disconnect();
  this.socket = null;

  return Promise.resolve();
};

/**
 * Wait for websocket connection.
 * @private
 * @returns {Promise}
 */

HTTPClient.prototype._onConnect = function _onConnect() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.socket.once('connect', resolve);
  });
};

/**
 * Wait for websocket auth.
 * @private
 * @returns {Promise}
 */

HTTPClient.prototype._sendAuth = function _sendAuth() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.socket.emit('auth', self.apiKey, function(err) {
      if (err)
        return reject(new Error(err.error));
      resolve();
    });
  });
};

/**
 * Wait for websocket disconnection.
 * @private
 * @returns {Promise}
 */

HTTPClient.prototype.onDisconnect = function onDisconnect() {
  var self = this;
  return new Promise(function(resolve, reject) {
    self.socket.once('disconnect', resolve);
  });
};

/**
 * Make an http request to endpoint.
 * @private
 * @param {String} method
 * @param {String} endpoint - Path.
 * @param {Object} json - Body or query depending on method.
 * @returns {Promise} - Returns Object?.
 */

HTTPClient.prototype._request = co(function* _request(method, endpoint, json) {
  var query, network, res;

  if (this.token) {
    if (!json)
      json = {};
    json.token = this.token;
  }

  if (json && method === 'get') {
    query = json;
    json = null;
  }

  res = yield request({
    method: method,
    uri: this.uri + endpoint,
    pool: true,
    query: query,
    json: json,
    auth: {
      username: 'bitcoinrpc',
      password: this.apiKey || ''
    },
    expect: 'json'
  });

  network = res.headers['x-decentraland-network'];

  if (network && network !== this.network.type)
    throw new Error('Wrong network.');

  if (res.statusCode === 404)
    return;

  if (!res.body)
    throw new Error('No body.');

  if (res.statusCode !== 200) {
    if (res.body.error) {
      console.log(res.body.error)
      throw new Error(res.body.error);
    }
    throw new Error('Status code: ' + res.statusCode);
  }

  return res.body;
});

/**
 * Make a GET http request to endpoint.
 * @private
 * @param {String} endpoint - Path.
 * @param {Object} json - Querystring.
 * @returns {Promise} - Returns Object?.
 */

HTTPClient.prototype._get = function _get(endpoint, json) {
  return this._request('get', endpoint, json);
};

/**
 * Make a POST http request to endpoint.
 * @private
 * @param {String} endpoint - Path.
 * @param {Object} json - Body.
 * @returns {Promise} - Returns Object?.
 */

HTTPClient.prototype._post = function _post(endpoint, json) {
  return this._request('post', endpoint, json);
};

/**
 * Make a PUT http request to endpoint.
 * @private
 * @param {String} endpoint - Path.
 * @param {Object} json - Body.
 * @returns {Promise} - Returns Object?.
 */

HTTPClient.prototype._put = function _put(endpoint, json) {
  return this._request('put', endpoint, json);
};

/**
 * Make a DELETE http request to endpoint.
 * @private
 * @param {String} endpoint - Path.
 * @param {Object} json - Body.
 * @returns {Promise} - Returns Object?.
 */

HTTPClient.prototype._del = function _del(endpoint, json) {
  return this._request('delete', endpoint, json);
};

/**
 * Get a mempool snapshot.
 * @returns {Promise} - Returns {@link TX}[].
 */

HTTPClient.prototype.getMempool = function getMempool() {
  return this._get('/mempool');
};

/**
 * Get some info about the server (network and version).
 * @returns {Promise} - Returns Object.
 */

HTTPClient.prototype.getInfo = function getInfo() {
  return this._get('/');
};

/**
 * Get coins that pertain to an address from the mempool or chain database.
 * Takes into account spent coins in the mempool.
 * @param {Base58Address|Base58Address[]} addresses
 * @returns {Promise} - Returns {@link Coin}[].
 */

HTTPClient.prototype.getCoinsByAddress = function getCoinsByAddress(address) {
  var body = { address: address };
  return this._post('/coin/address', body);
};

/**
 * Retrieve a coin from the mempool or chain database.
 * Takes into account spent coins in the mempool.
 * @param {Hash} hash
 * @param {Number} index
 * @returns {Promise} - Returns {@link Coin}.
 */

HTTPClient.prototype.getCoin = function getCoin(hash, index) {
  return this._get('/coin/' + hash + '/' + index);
};

/**
 * Retrieve transactions pertaining to an
 * address from the mempool or chain database.
 * @param {Base58Address|Base58Address[]} addresses
 * @returns {Promise} - Returns {@link TX}[].
 */

HTTPClient.prototype.getTXByAddress = function getTXByAddress(address) {
  var body = { address: address };
  return this._post('/tx/address', body);
};

/**
 * Retrieve a transaction from the mempool or chain database.
 * @param {Hash} hash
 * @returns {Promise} - Returns {@link TX}.
 */

HTTPClient.prototype.getTX = function getTX(hash) {
  return this._get('/tx/' + hash);
};

/**
 * Retrieve a block from the chain database.
 * @param {Hash|Number} block
 * @returns {Promise} - Returns {@link Block}.
 */

HTTPClient.prototype.getBlock = function getBlock(block) {
  return this._get('/block/' + block);
};

/**
 * Add a transaction to the mempool and broadcast it.
 * @param {TX} tx
 * @returns {Promise}
 */

HTTPClient.prototype.broadcast = function broadcast(tx) {
  var body = { tx: toHex(tx) };

  return this._post('/broadcast', body);
};

/**
 * Rescan the chain.
 * @param {Number} height
 * @returns {Promise}
 */

HTTPClient.prototype.rescan = function rescan(height) {
  var options = { height: height };
  return this._post('/rescan', options);
};

/**
 * Reset the chain.
 * @param {Hash|Number} block
 * @returns {Promise}
 */

HTTPClient.prototype.reset = function reset(block) {
  var options = { block: block };
  return this._post('/reset', options);
};

/**
 * Resend pending transactions.
 * @returns {Promise}
 */

HTTPClient.prototype.resend = function resend() {
  return this._post('/resend', {});
};

/**
 * Backup the walletdb.
 * @param {String} path
 * @returns {Promise}
 */

HTTPClient.prototype.backup = function backup(path) {
  var options = { path: path };
  return this._post('/backup', options);
};

/**
 * Listen for events on wallet id.
 * @param {WalletID} id
 */

HTTPClient.prototype.join = function join(id, token) {
  var self = this;

  if (!this.socket)
    return Promise.resolve();

  return new Promise(function(resolve, reject) {
    self.socket.emit('wallet join', id, token, function(err) {
      if (err)
        return reject(new Error(err.error));
      resolve();
    });
  });
};

/**
 * Unlisten for events on wallet id.
 * @param {WalletID} id
 */

HTTPClient.prototype.leave = function leave(id) {
  var self = this;

  if (!this.socket)
    return Promise.resolve();

  return new Promise(function(resolve, reject) {
    self.socket.emit('wallet leave', id, function(err) {
      if (err)
        return reject(new Error(err.error));
      resolve();
    });
  });
};

/**
 * Listen for events on all wallets.
 */

HTTPClient.prototype.all = function all(token) {
  return this.join('!all', token);
};

/**
 * Unlisten for events on all wallets.
 */

HTTPClient.prototype.none = function none() {
  return this.leave('!all');
};

/**
 * Get list of all wallet IDs.
 * @returns {Promise}
 */

HTTPClient.prototype.getWallets = function getWallets() {
  return this._get('/wallets');
};

/**
 * Create a wallet.
 * @param {Object} options - See {@link Wallet}.
 * @returns {Promise}
 */

HTTPClient.prototype.createWallet = function createWallet(options) {
  return this._post('/wallet', options);
};

/**
 * Get the raw wallet JSON.
 * @param {WalletID} id
 * @returns {Promise}
 */

HTTPClient.prototype.getWallet = function getWallet(id) {
  return this._get('/wallet/' + id);
};

/**
 * Get wallet transaction history.
 * @param {WalletID} id
 * @returns {Promise}
 */

HTTPClient.prototype.getHistory = function getHistory(id, account) {
  var options = { account: account };
  return this._get('/wallet/' + id + '/tx/history', options);
};

/**
 * Get wallet coins.
 * @param {WalletID} id
 * @returns {Promise}
 */

HTTPClient.prototype.getCoins = function getCoins(id, account) {
  var options = { account: account };
  return this._get('/wallet/' + id + '/coin', options);
};

/**
 * Get all unconfirmed transactions.
 * @param {WalletID} id
 * @returns {Promise}
 */

HTTPClient.prototype.getPending = function getPending(id, account) {
  var options = { account: account };
  return this._get('/wallet/' + id + '/tx/unconfirmed', options);
};

/**
 * Calculate wallet balance.
 * @param {WalletID} id
 * @returns {Promise}
 */

HTTPClient.prototype.getBalance = function getBalance(id, account) {
  var options = { account: account };
  return this._get('/wallet/' + id + '/balance', options);
};

/**
 * Get last N wallet transactions.
 * @param {WalletID} id
 * @param {Number} limit - Max number of transactions.
 * @returns {Promise}
 */

HTTPClient.prototype.getLast = function getLast(id, account, limit) {
  var options = { account: account, limit: limit };
  return this._get('/wallet/' + id + '/tx/last', options);
};

/**
 * Get wallet transactions by timestamp range.
 * @param {WalletID} id
 * @param {Object} options
 * @param {Number} options.start - Start time.
 * @param {Number} options.end - End time.
 * @param {Number?} options.limit - Max number of records.
 * @param {Boolean?} options.reverse - Reverse order.
 * @returns {Promise}
 */

HTTPClient.prototype.getRange = function getRange(id, account, options) {
  options = {
    account: account,
    start: options.start,
    end: options.end ,
    limit: options.limit,
    reverse: options.reverse
  };
  return this._get('/wallet/' + id + '/tx/range', options);
};

/**
 * Get transaction (only possible if the transaction
 * is available in the wallet history).
 * @param {WalletID} id
 * @param {Hash} hash
 * @returns {Promise}
 */

HTTPClient.prototype.getWalletTX = function getWalletTX(id, hash) {
  return this._get('/wallet/' + id + '/tx/' + hash);
};

/**
 * Get wallet blocks.
 * @param {WalletID} id
 * @param {Number} height
 * @returns {Promise}
 */

HTTPClient.prototype.getWalletBlocks = function getWalletBlocks(id) {
  return this._get('/wallet/' + id + '/block');
};

/**
 * Get wallet block.
 * @param {WalletID} id
 * @param {Number} height
 * @returns {Promise}
 */

HTTPClient.prototype.getWalletBlock = function getWalletBlock(id, height) {
  return this._get('/wallet/' + id + '/block/' + height);
};

/**
 * Get unspent coin (only possible if the transaction
 * is available in the wallet history).
 * @param {WalletID} id
 * @param {Hash} hash
 * @param {Number} index
 * @returns {Promise}
 */

HTTPClient.prototype.getWalletCoin = function getWalletCoin(id, account, hash, index) {
  var path = '/wallet/' + id + '/coin/' + hash + '/' + index;
  var options = { account: account };
  return this._get(path, options);
};

/**
 * Create a transaction, fill, sign, and broadcast.
 * @param {WalletID} id
 * @param {Object} options
 * @param {Base58Address} options.address
 * @param {Amount} options.value
 * @returns {Promise}
 */

HTTPClient.prototype.send = function send(id, options) {
  options = util.merge({}, options);
  options.outputs = options.outputs || [];

  if (options.rate)
    options.rate = Amount.btc(options.rate);

  options.outputs = options.outputs.map(function(output) {
    return {
      value: Amount.btc(output.value),
      address: output.address,
      script: toHex(output.script)
    };
  });

  return this._post('/wallet/' + id + '/send', options);
};

/**
 * Generate a new token.
 * @param {(String|Buffer)?} passphrase
 * @returns {Promise}
 */

HTTPClient.prototype.retoken = co(function* retoken(id, passphrase) {
  var options = { passphrase: passphrase };
  var body = yield this._post('/wallet/' + id + '/retoken', options);
  return body.token;
});

/**
 * Change or set master key's passphrase.
 * @param {(String|Buffer)?} old
 * @param {String|Buffer} new_
 * @returns {Promise}
 */

HTTPClient.prototype.setPassphrase = function setPassphrase(id, old, new_) {
  var options = { old: old, passphrase: new_ };
  return this._post('/wallet/' + id + '/passphrase', options);
};

/**
 * Create a transaction, fill.
 * @param {WalletID} id
 * @param {Object} options
 * @returns {Promise}
 */

HTTPClient.prototype.createTX = function createTX(id, options) {
  options = util.merge({}, options);

  if (options.rate)
    options.rate = Amount.btc(options.rate);

  options.outputs = options.outputs.map(function(output) {
    return {
      value: Amount.btc(output.value),
      address: output.address,
      script: toHex(output.script)
    };
  });

  return this._post('/wallet/' + id + '/create', options);
};

/**
 * Sign a transaction.
 * @param {WalletID} id
 * @param {TX} tx
 * @param {Object} options
 * @returns {Promise}
 */

HTTPClient.prototype.sign = function sign(id, tx, options) {
  var body;

  if (!options)
    options = {};

  body = util.merge({}, options);
  body.tx = toHex(tx);

  return this._post('/wallet/' + id + '/sign', body);
};

/**
 * @param {WalletID} id
 * @param {Number} now - Current time.
 * @param {Number} age - Age delta (delete transactions older than `now - age`).
 * @returns {Promise}
 */

HTTPClient.prototype.zapWallet = function zapWallet(id, account, age) {
  var body = {
    account: account,
    age: age
  };
  return this._post('/wallet/' + id + '/zap', body);
};

/**
 * Get wallet key.
 * @param {WalletID} id
 * @param {Base58Address} address
 * @returns {Promise}
 */

HTTPClient.prototype.getKey = function getKey(id, address) {
  return this._get('/wallet/' + id + '/key/' + address);
};

/**
 * Get wallet key WIF dump.
 * @param {WalletID} id
 * @param {Base58Address} address
 * @param {String?} passphrase
 * @returns {Promise}
 */

HTTPClient.prototype.getWIF = function getWIF(id, address, passphrase) {
  var options = { passphrase: passphrase };
  return this._get('/wallet/' + id + '/wif/' + address, options);
};

/**
 * Add a public account/purpose key to the wallet for multisig.
 * @param {WalletID} id
 * @param {(String|Number)?} account
 * @param {Base58String} key - Account (bip44) or
 * Purpose (bip45) key (can be in base58 form).
 * @returns {Promise}
 */

HTTPClient.prototype.addSharedKey = function addSharedKey(id, account, key) {
  var options = { account: account, accountKey: key };
  return this._put('/wallet/' + id + '/shared-key', options);
};

/**
 * Remove a public account/purpose key to the wallet for multisig.
 * @param {WalletID} id
 * @param {(String|Number)?} account
 * @param {Base58String} key - Account (bip44) or Purpose
 * (bip45) key (can be in base58 form).
 * @returns {Promise}
 */

HTTPClient.prototype.removeSharedKey = function removeSharedKey(id, account, key) {
  var options = { account: account, accountKey: key };
  return this._del('/wallet/' + id + '/shared-key', options);
};

/**
 * Import private key.
 * @param {String} id
 * @param {Number|String} account
 * @param {String} key
 * @returns {Promise}
 */

HTTPClient.prototype.importPrivate = function importPrivate(id, account, key) {
  var options = { account: account, privateKey: key };
  return this._post('/wallet/' + id + '/import', options);
};

/**
 * Import public key.
 * @param {String} id
 * @param {Number|String} account
 * @param {String} key
 * @returns {Promise}
 */

HTTPClient.prototype.importPublic = function importPublic(id, account, key) {
  var options = { account: account, publicKey: key };
  return this._post('/wallet/' + id + '/import', options);
};

/**
 * Import address.
 * @param {String} id
 * @param {Number|String} account
 * @param {String} address
 * @returns {Promise}
 */

HTTPClient.prototype.importAddress = function importAddress(id, account, address) {
  var options = { account: account, address: address };
  return this._post('/wallet/' + id + '/import', options);
};

/**
 * Lock a coin.
 * @param {String} id
 * @param {String} hash
 * @param {Number} index
 * @returns {Promise}
 */

HTTPClient.prototype.lockCoin = function lockCoin(id, hash, index) {
  var options = { hash: hash, index: index };
  return this._put('/wallet/' + id + '/coin/locked', options);
};

/**
 * Unlock a coin.
 * @param {String} id
 * @param {String} hash
 * @param {Number} index
 * @returns {Promise}
 */

HTTPClient.prototype.unlockCoin = function unlockCoin(id, hash, index) {
  var options = { hash: hash, index: index };
  return this._del('/wallet/' + id + '/coin/locked', options);
};

/**
 * Get locked coins.
 * @param {String} id
 * @returns {Promise}
 */

HTTPClient.prototype.getLocked = function getLocked(id) {
  return this._get('/wallet/' + id + '/coin/locked');
};

/**
 * Lock wallet.
 * @param {String} id
 * @returns {Promise}
 */

HTTPClient.prototype.lock = function lock(id) {
  return this._post('/wallet/' + id + '/lock', {});
};

/**
 * Unlock wallet.
 * @param {String} id
 * @param {String} passphrase
 * @param {Number} timeout
 * @returns {Promise}
 */

HTTPClient.prototype.unlock = function unlock(id, passphrase, timeout) {
  var options = { passphrase: passphrase, timeout: timeout };
  return this._post('/wallet/' + id + '/unlock', options);
};

/**
 * Resend pending wallet transactions.
 * @returns {Promise}
 */

HTTPClient.prototype.resendWallet = function resendWallet(id) {
  return this._post('/wallet/' + id + '/resend', {});
};

/**
 * Get wallet accounts.
 * @param {WalletID} id
 * @returns {Promise} - Returns Array.
 */

HTTPClient.prototype.getAccounts = function getAccounts(id) {
  var path = '/wallet/' + id + '/account';
  return this._get(path);
};

/**
 * Get wallet master key.
 * @param {WalletID} id
 * @returns {Promise}
 */

HTTPClient.prototype.getMaster = function getMaster(id) {
  var path = '/wallet/' + id + '/master';
  return this._get(path);
};

/**
 * Get wallet account.
 * @param {WalletID} id
 * @param {String} account
 * @returns {Promise} - Returns Array.
 */

HTTPClient.prototype.getAccount = function getAccount(id, account) {
  var path = '/wallet/' + id + '/account/' + account;
  return this._get(path);
};

/**
 * Create account.
 * @param {WalletID} id
 * @param {Object} options
 * @returns {Promise} - Returns Array.
 */

HTTPClient.prototype.createAccount = function createAccount(id, options) {
  var path;

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { account: options };

  path = '/wallet/' + id + '/account';

  return this._post(path, options);
};

/**
 * Create address.
 * @param {WalletID} id
 * @param {Object} options
 * @returns {Promise}
 */

HTTPClient.prototype.createAddress = function createAddress(id, options) {
  var path;

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { account: options };

  path = '/wallet/' + id + '/address';

  return this._post(path, options);
};

/**
 * Create change address.
 * @param {WalletID} id
 * @param {Object} options
 * @returns {Promise}
 */

HTTPClient.prototype.createChange = function createChange(id, options) {
  var path;

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { account: options };

  path = '/wallet/' + id + '/change';

  return this._post(path, options);
};

/**
 * Create nested address.
 * @param {WalletID} id
 * @param {Object} options
 * @returns {Promise}
 */

HTTPClient.prototype.createNested = function createNested(id, options) {
  var path;

  if (!options)
    options = {};

  if (typeof options === 'string')
    options = { account: options };

  path = '/wallet/' + id + '/nested';

  return this._post(path, options);
};

/*
 * Helpers
 */

function toHex(obj) {
  if (!obj)
    return;

  if (obj.toRaw)
    obj = obj.toRaw();

  if (Buffer.isBuffer(obj))
    obj = obj.toString('hex');

  return obj;
}

/*
 * Expose
 */

module.exports = HTTPClient;


text:
package email

import (
	"fmt"
	"time"
)

//FastDetector detecte speed and unique analyze
type FastDetector struct {
	lastSec            int64
	sameSecCnt         int
	sameSecThreshold   int
	overspeedCnt       int
	overspeedThreshold int
	uniqueSpeed        map[int64]int
	fastUnique         int64
}

//NewFastDetector new
func NewFastDetector(speedThreshold, overspeedThreshold int) *FastDetector {
	return &FastDetector{
		lastSec:            time.Now().Unix(),
		sameSecCnt:         0,
		sameSecThreshold:   speedThreshold,
		overspeedCnt:       0,
		overspeedThreshold: overspeedThreshold,
		uniqueSpeed:        map[int64]int{},
	}
}

//String string info
func (fd *FastDetector) String() string {
	return fmt.Sprintf("same_sec_cnt=%d,overspeed_cnt=%d,fast_unique=%d,unique_speed=%v",
		fd.sameSecCnt, fd.overspeedCnt, fd.fastUnique, fd.uniqueSpeed)
}

//Detect 快慢探查, 超限名单只能被慢速/下一个超速名单/间隔5s后空名单代替,超限名单只有在(overspeedthreshold+1) * samesecthreshold时才确定,此时返回true
func (fd *FastDetector) Detect(unique int64) (fast bool) {
	now := time.Now().Unix()
	//连续n次超限
	if now == fd.lastSec {
		fd.sameSecCnt++
		if fd.sameSecCnt == fd.sameSecThreshold {
			fd.overspeedCnt++
		}
	} else {
		if fd.sameSecCnt < fd.sameSecThreshold || (now-fd.lastSec > 5) {
			fd.overspeedCnt = 0
			fd.fastUnique = 0
			fd.uniqueSpeed = map[int64]int{}
		}
		fd.sameSecCnt = 1
		fd.lastSec = now
	}

	//连续超限后,最先超限的unique指定为超限名单
	if fd.overspeedCnt == fd.overspeedThreshold && fd.sameSecCnt == fd.sameSecThreshold {
		fd.uniqueSpeed[unique] = 0
	}
	if (fd.overspeedCnt == fd.overspeedThreshold && fd.sameSecCnt != fd.sameSecThreshold) || (fd.overspeedCnt > fd.overspeedThreshold) {
		fd.uniqueSpeed[unique]++
		if fd.uniqueSpeed[unique] >= fd.sameSecThreshold {
			fast = true
			fd.fastUnique = unique //指定超限名单
			fd.uniqueSpeed = map[int64]int{}
			fd.overspeedCnt = 0
		}
	}

	return
}

//IsFastUnique 是否为超限名单
func (fd *FastDetector) IsFastUnique(unique int64) bool {
	return fd.fastUnique == unique
}


text:
import Ember from 'ember';

export default Ember.Component.extend({
  tagName: 'table',
  classNames: ['table','table-striped','table-bordered','dataTable'],
  initDataTable: function() {

    this.$().dataTable({});

  }.on('didInsertElement')
});


text:
package cn.wizzer.modules.models.sys;

import cn.wizzer.common.base.Model;
import org.nutz.dao.DB;
import org.nutz.dao.entity.annotation.*;

import java.io.Serializable;
import java.util.List;

/**
 * Created by wizzer on 2016/6/21.
 */
@Table("sys_menu")
@TableIndexes({@Index(name = "INDEX_SYS_MENU_PATH", fields = {"path"}, unique = true), @Index(name = "INDEX_SYS_MENU_PREM", fields = {"permission"}, unique = true)})
public class Sys_menu extends Model implements Serializable {
    private static final long serialVersionUID = 1L;
    @Column
    @Name
    @Comment("ID")
    @ColDefine(type = ColType.VARCHAR, width = 32)
    @Prev(els = {@EL("uuid()")})
    private String id;

    @Column
    @Comment("父级ID")
    @ColDefine(type = ColType.VARCHAR, width = 32)
    private String parentId;

    @Column
    @Comment("树路径")
    @ColDefine(type = ColType.VARCHAR, width = 100)
    private String path;

    @Column
    @Comment("菜单名称")
    @ColDefine(type = ColType.VARCHAR, width = 100)
    private String name;

    @Column
    @Comment("菜单别名")
    @ColDefine(type = ColType.VARCHAR, width = 100)
    private String aliasName;

    @Column
    @Comment("资源类型")
    @ColDefine(type = ColType.VARCHAR, width = 10)
    private String type;

    @Column
    @Comment("菜单链接")
    @ColDefine(type = ColType.VARCHAR, width = 255)
    private String href;

    @Column
    @Comment("打开方式")
    @ColDefine(type = ColType.VARCHAR, width = 50)
    private String target;

    @Column
    @Comment("菜单图标")
    @ColDefine(type = ColType.VARCHAR, width = 50)
    private String icon;

    @Column
    @Comment("是否显示")
    @ColDefine(type = ColType.BOOLEAN)
    private boolean isShow;

    @Column
    @Comment("是否禁用")
    @ColDefine(type = ColType.BOOLEAN)
    private boolean disabled;

    @Column
    @Comment("权限标识")
    @ColDefine(type = ColType.VARCHAR, width = 255)
    private String permission;

    @Column
    @Comment("菜单介绍")
    @ColDefine(type = ColType.VARCHAR, width = 255)
    private String note;

    @Column
    @Comment("排序字段")
    @Prev({
            @SQL(db= DB.MYSQL,value = "SELECT IFNULL(MAX(location),0)+1 FROM sys_menu"),
            @SQL(db= DB.ORACLE,value = "SELECT COALESCE(MAX(location),0)+1 FROM sys_menu")
    })
    private Integer location;

    @Column
    @Comment("有子节点")
    private boolean hasChildren;

    private List<Sys_menu> buttons;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAliasName() {
        return aliasName;
    }

    public void setAliasName(String aliasName) {
        this.aliasName = aliasName;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getHref() {
        return href;
    }

    public void setHref(String href) {
        this.href = href;
    }

    public String getTarget() {
        return target;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public boolean isShow() {
        return isShow;
    }

    public void setIsShow(boolean isShow) {
        this.isShow = isShow;
    }

    public boolean isDisabled() {
        return disabled;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }

    public String getPermission() {
        return permission;
    }

    public void setPermission(String permission) {
        this.permission = permission;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public Integer getLocation() {
        return location;
    }

    public void setLocation(Integer location) {
        this.location = location;
    }

    public boolean isHasChildren() {
        return hasChildren;
    }

    public void setHasChildren(boolean hasChildren) {
        this.hasChildren = hasChildren;
    }

    public List<Sys_menu> getButtons() {
        return buttons;
    }

    public void setButtons(List<Sys_menu> buttons) {
        this.buttons = buttons;
    }
}


text:
package org.daisy.dotify.formatter.impl.row;

import org.daisy.dotify.api.formatter.FormatterConfiguration;
import org.daisy.dotify.api.formatter.TextProperties;
import org.daisy.dotify.api.translator.BrailleTranslatorFactoryMaker;
import org.daisy.dotify.api.translator.BrailleTranslatorFactoryMakerService;
import org.daisy.dotify.api.translator.TranslatorConfigurationException;
import org.daisy.dotify.common.text.IdentityFilter;
import org.daisy.dotify.formatter.impl.core.FormatterContext;
import org.daisy.dotify.formatter.impl.search.CrossReferenceHandler;
import org.daisy.dotify.formatter.impl.segment.AnchorSegment;
import org.daisy.dotify.formatter.impl.segment.Segment;
import org.daisy.dotify.formatter.impl.segment.Style;
import org.daisy.dotify.formatter.impl.segment.TextSegment;
import org.daisy.dotify.translator.DefaultBrailleFilter;
import org.daisy.dotify.translator.DefaultMarkerProcessor;
import org.daisy.dotify.translator.Marker;
import org.daisy.dotify.translator.SimpleBrailleTranslator;
import org.daisy.dotify.translator.impl.DefaultBrailleFinalizer;
import org.junit.Test;
import org.mockito.Mockito;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import static org.junit.Assert.assertEquals;

/**
 * TODO: Write java doc.
 */
@SuppressWarnings("javadoc")
public class SegmentProcessorTest {
    private static final Logger logger = Logger.getLogger(SegmentProcessorTest.class.getCanonicalName());

    final String loc = "und";
    final String mode = "bypass";
    final RowDataProperties rdp = new RowDataProperties.Builder().build();
    final FormatterConfiguration conf = new FormatterConfiguration.Builder(loc, mode).build();
    final DefaultMarkerProcessor mp = new DefaultMarkerProcessor.Builder()
            .addDictionary("em", (str, ta) -> new Marker("x", "y"))
            .addDictionary("strong", (str, ta) -> new Marker("6", "7"))
            .build();
    final SimpleBrailleTranslator trr = new SimpleBrailleTranslator(
            new DefaultBrailleFilter(new IdentityFilter(), loc, mp, null),
            new DefaultBrailleFinalizer(), mode);

    @Test
    public void testTextNoProcessor() {
        Segment t;
        TextProperties tp = new TextProperties.Builder("und").hyphenate(false).build();
        List<Segment> segments = new ArrayList<>();
        List<Segment> expecteds = new ArrayList<>();
        t = new TextSegment("abc", tp, true);
        segments.add(t);
        expecteds.add(t);
        Style s = new Style("em");
        segments.add(s);
        t = new TextSegment("def", tp, true);
        s.add(t);
        expecteds.add(t);
        t = new TextSegment("ghi", tp, true);
        segments.add(t);
        expecteds.add(t);
        FormatterContext fc = new FormatterContext(BrailleTranslatorFactoryMaker.newInstance(), null, conf);

        SegmentProcessor sp = new SegmentProcessor(
            "",
            segments,
            100,
            new CrossReferenceHandler(),
            null,
            100,
            rdp.getMargins(),
            fc,
            rdp
        );
        logger.info(sp.getNext(LineProperties.DEFAULT).get().getChars());
    }

    @Test
    public void testTextWithProcessor_01() throws TranslatorConfigurationException {
        Segment t;
        TextProperties tp = new TextProperties.Builder("und").hyphenate(false).build();
        List<Segment> segments = new ArrayList<>();
        t = new TextSegment("abc", tp, true);
        segments.add(t);
        Style s = new Style("em");
        segments.add(s);
        t = new TextSegment("def", tp, true);
        s.add(t);
        t = new TextSegment("ghi", tp, true);
        segments.add(t);

        BrailleTranslatorFactoryMakerService sr = Mockito.mock(BrailleTranslatorFactoryMakerService.class);
        Mockito.when(sr.newTranslator(loc, mode)).thenReturn(trr);
        FormatterContext fc = new FormatterContext(sr, null, conf);
        SegmentProcessor sp = new SegmentProcessor(
            "",
            segments,
            100,
            new CrossReferenceHandler(),
            null,
            100,
            rdp.getMargins(),
            fc,
            rdp
        );
        assertEquals("abcxdefyghi", sp.getNext(LineProperties.DEFAULT).get().getChars());
    }

    @Test
    public void testTextWithProcessor_02() throws TranslatorConfigurationException {

        Segment t;
        TextProperties tp = new TextProperties.Builder("und").hyphenate(false).build();
        List<Segment> segments = new ArrayList<>();
        List<Segment> expecteds = new ArrayList<>();
        t = new TextSegment("abc", tp, true);
        segments.add(t);
        expecteds.add(new TextSegment("abcxdefy", tp, true));
        Style s = new Style("em");
        segments.add(s);
        t = new TextSegment("def", tp, true);
        s.add(t);
        t = new AnchorSegment("ref-id");
        s.add(t);
        expecteds.add(t);

        BrailleTranslatorFactoryMakerService sr = Mockito.mock(BrailleTranslatorFactoryMakerService.class);
        Mockito.when(sr.newTranslator(loc, mode)).thenReturn(trr);
        FormatterContext fc = new FormatterContext(sr, null, conf);
        SegmentProcessor sp = new SegmentProcessor(
            "",
            segments,
            100,
            new CrossReferenceHandler(),
            null,
            100,
            rdp.getMargins(),
            fc,
            rdp
        );
        assertEquals("abcxdefy", sp.getNext(LineProperties.DEFAULT).get().getChars());
    }

}


text:
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<metamorph xmlns="http://www.culturegraph.org/metamorph" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" entityMarker="" version="1" xsi:schemaLocation="http://www.culturegraph.org/metamorph metamorph.xsd">
    <meta>
        <name>mapping-1402051926041</name>
    </meta>
    <rules>
        <combine flushWith="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feld" includeSubEntities="true" name="@feld_value__1__" reset="true" sameEntity="true" value="${feld_value__1__.filtered}">
            <if>
                <all flushWith="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.ddb.de/professionell/mabxml/mabxml-1.xsd#ind" includeSubEntities="true" name="CONDITION_ALL" reset="true">
                    <data source="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.ddb.de/professionell/mabxml/mabxml-1.xsd#nr">
                        <regexp match="332"/>
                    </data>
                    <data source="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.ddb.de/professionell/mabxml/mabxml-1.xsd#ind">
                        <regexp match=" "/>
                    </data>
                </all>
            </if>
            <data name="feld_value__1__.filtered" source="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.w3.org/1999/02/22-rdf-syntax-ns#value"/>
        </combine>
        <combine flushWith="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feld" includeSubEntities="true" name="@feld_value__0__" reset="true" sameEntity="true" value="${feld_value__0__.filtered}">
            <if>
                <all flushWith="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.ddb.de/professionell/mabxml/mabxml-1.xsd#ind" includeSubEntities="true" name="CONDITION_ALL" reset="true">
                    <data source="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.ddb.de/professionell/mabxml/mabxml-1.xsd#nr">
                        <regexp match="002"/>
                    </data>
                    <data source="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.ddb.de/professionell/mabxml/mabxml-1.xsd#ind">
                        <regexp match="a"/>
                    </data>
                </all>
            </if>
            <data name="feld_value__0__.filtered" source="http://www.ddb.de/professionell/mabxml/mabxml-1.xsd#feldhttp://www.w3.org/1999/02/22-rdf-syntax-ns#value">
                <equals string="19981028"/>
            </data>
        </combine>
        <choose name="@__TRANSFORMATION_OUTPUT_VARIABLE__1">
            <data name="ifelse-component_-1402409200649_if-branch" source="@feld_value__0__"/>
            <data name="ifelse-component_-1402409200649_else-branch" source="@feld_value__1__"/>
        </choose>
        <data name="http://purl.org/dc/elements/1.1/title" source="@__TRANSFORMATION_OUTPUT_VARIABLE__1"/>
    </rules>
    <maps/>
</metamorph>


text:
using MixedRealityToolkit.Utilities.Inspectors.EditorScript;
using MixedRealityToolkit.UX.Lines;

namespace MixedRealityToolkit.UX.EditorScript
{
    [UnityEditor.CustomEditor(typeof(LineMeshes))]
        public class LineMeshesEditor : MRTKEditor { }
}


text:
package dev.jeka.core.api.function;

import java.util.function.Consumer;

/**
 * A mutable container for {@link Consumer}. From this object you can replace the underlying {@link Runnable} or
 * chain it with other ones.
 */
public class JkConsumers<T, P> implements Consumer<T> {

    private Consumer<T> consumer;

    /**
     * For parent chaining
     */
    public final P __;

    private JkConsumers(P parent, Consumer<T> consumer) {
        this.consumer= consumer;
        this.__ = parent;
    }

    /**
     * Creates a {@link JkConsumers} delegating to the single specified {@link Consumer}.
     */
    public static <T> JkConsumers<T, Void> of() {
        return ofParent(null);
    }

    /**
     * Same as {@link #of()} but providing a parent chaining.
     */
    public static <T, P> JkConsumers<T, P> ofParent(P parent) {
        return new JkConsumers<T, P>(parent, o -> {});
    }

    /**
     * Set the specified {@link Consumer} as the unique underlying element for this container.
     */
    public JkConsumers<T, P> set(Consumer<T> consumer) {
        this.consumer = consumer;
        return this;
    }

    /**
     * Chains this underlying {@link Consumer} with the specified one. The specified element will
     * be executed at the end.
     */
    public JkConsumers<T, P> append(Consumer<T> appendedConsumer) {
        consumer = consumer.andThen(appendedConsumer);
        return this;
    }

    /**
     * Chains this underlying {@link Consumer} with the specified one. The specified element will
     * be executed at the beginning.
     */
    public JkConsumers<T, P> prepend(Consumer<T> appendedConsumer) {
        consumer = appendedConsumer.andThen(consumer);
        return this;
    }

    @Override
    public void accept(T t) {
        consumer.accept(t);
    }
}


text:
using System;
using Azure.Core;

namespace Azure.ResourceManager.DeploymentManager.Models
{
    /// <summary> The properties that make up a REST request. </summary>
    public partial class RestRequest
    {
        /// <summary> Initializes a new instance of RestRequest. </summary>
        /// <param name="method"> The HTTP method to use for the request. </param>
        /// <param name="uri"> The HTTP URI to use for the request. </param>
        /// <param name="authentication">
        /// The authentication information required in the request to the health provider.
        /// Please note <see cref="RestRequestAuthentication"/> is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.
        /// The available derived classes include <see cref="ApiKeyAuthentication"/> and <see cref="RolloutIdentityAuthentication"/>.
        /// </param>
        /// <exception cref="ArgumentNullException"> <paramref name="uri"/> or <paramref name="authentication"/> is null. </exception>
        public RestRequest(RestRequestMethod method, Uri uri, RestRequestAuthentication authentication)
        {
            Argument.AssertNotNull(uri, nameof(uri));
            Argument.AssertNotNull(authentication, nameof(authentication));

            Method = method;
            Uri = uri;
            Authentication = authentication;
        }

        /// <summary> The HTTP method to use for the request. </summary>
        public RestRequestMethod Method { get; set; }
        /// <summary> The HTTP URI to use for the request. </summary>
        public Uri Uri { get; set; }
        /// <summary>
        /// The authentication information required in the request to the health provider.
        /// Please note <see cref="RestRequestAuthentication"/> is the base class. According to the scenario, a derived class of the base class might need to be assigned here, or this property needs to be casted to one of the possible derived classes.
        /// The available derived classes include <see cref="ApiKeyAuthentication"/> and <see cref="RolloutIdentityAuthentication"/>.
        /// </summary>
        public RestRequestAuthentication Authentication { get; set; }
    }
}


text:
module Alchemy
  class NodeSerializer < ActiveModel::Serializer
    attributes :id,
      :name,
      :lft,
      :rgt,
      :url,
      :parent_id

    has_many :ancestors, record_type: :node, serializer: self
  end
end


text:
package nxt.http;

import java.nio.ByteBuffer;

import javax.servlet.http.HttpServletRequest;

import nxt.Account;
import nxt.Block;
import nxt.Generator;
import nxt.Nxt;
import nxt.crypto.Crypto;
import nxt.util.Convert;
import fr.cryptohash.Shabal256;

import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;

public final class SubmitNonce extends APIServlet.APIRequestHandler {
	static final SubmitNonce instance = new SubmitNonce();

	private SubmitNonce() {
		super(new APITag[] {APITag.MINING}, "secretPhrase", "nonce", "accountId");
	}

	@Override
	JSONStreamAware processRequest(HttpServletRequest req) {
		String secret = req.getParameter("secretPhrase");
		Long nonce = Convert.parseUnsignedLong(req.getParameter("nonce"));

		String accountId = req.getParameter("accountId");

		JSONObject response = new JSONObject();

		if(secret == null) {
			response.put("result", "Missing Passphrase");
			return response;
		}

		if(nonce == null) {
			response.put("result", "Missing Nonce");
			return response;
		}

		byte[] secretPublicKey = Crypto.getPublicKey(secret);
		Account secretAccount = Account.getAccount(secretPublicKey);
		if(secretAccount != null) {
			Account genAccount;
			if(accountId != null) {
				genAccount = Account.getAccount(Convert.parseAccountId(accountId));
			}
			else {
				genAccount = secretAccount;
			}

			if(genAccount != null) {
				Account.RewardRecipientAssignment assignment = genAccount.getRewardRecipientAssignment();
				Long rewardId;
				if(assignment == null) {
					rewardId = genAccount.getId();
				}
				else if(assignment.getFromHeight() > Nxt.getBlockchain().getLastBlock().getHeight() + 1) {
					rewardId = assignment.getPrevRecipientId();
				}
				else {
					rewardId = assignment.getRecipientId();
				}
				if(rewardId != secretAccount.getId()) {
					response.put("result", "Passphrase does not match reward recipient");
					return response;
				}
			}
			else {
				response.put("result", "Passphrase is for a different account");
				return response;
			}
		}

		Generator generator;
		if(accountId == null || secretAccount == null) {
			generator = Generator.addNonce(secret, nonce);
		}
		else {
			Account genAccount = Account.getAccount(Convert.parseUnsignedLong(accountId));
			if(genAccount == null ||
			   genAccount.getPublicKey() == null) {
				response.put("result", "Passthrough mining requires public key in blockchain");
			}
			byte[] publicKey = genAccount.getPublicKey();
			generator = Generator.addNonce(secret, nonce, publicKey);
		}

		if(generator == null) {
			response.put("result", "failed to create generator");
			return response;
		}

		//response.put("result", "deadline: " + generator.getDeadline());
		response.put("result", "success");
		response.put("deadline", generator.getDeadline());

		return response;
	}

	@Override
    boolean requirePost() {
        return true;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
FM2AlloyConversor
</TITLE>

<META NAME="date" CONTENT="2010-02-08">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

splar.core.util.alloy

Class FM2AlloyConversor

java.lang.Object
  splar.core.util.alloy.FM2AlloyConversor

public class FM2AlloyConversor
extends java.lang.Object

Constructor Summary

FM2AlloyConversor()

Method Summary

static java.lang.String
convert(FeatureModel fm,
        boolean includeHeader)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

FM2AlloyConversor

public FM2AlloyConversor()

Method Detail

convert

public static java.lang.String convert(FeatureModel fm,
                                       boolean includeHeader)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
module.exports.func = function (bot, msg) {
    var cmd = "$$";
          let params = msg.content.replace(cmd + "ban ", "").split(" ");

      if (!msg.guild.member(msg.author).hasPermission("BAN_MEMBERS")) {
        msg.reply('```An error has occured\nReason: You do not have the BAN_MEMBERS permission```')
        return;
      }

      let user = msg.mentions.users.first();

      if (user == null) {
        msg.reply("User does not exist. (Make sure you mention the user)");
        return;
      }

      let reason = msg.content.replace(params[0] + " ", "").replace(cmd + "ban ", "");
      if (reason == null || reason == "" || params[0] == null || params[1] == null) {
        msg.reply("Command syntax: ** " + cmd + "ban @User Reason**");
        return;
      }

      if (!msg.channel.guild.member(user).bannable) {
        msg.reply("I can not ban them!");
        return;
      }

      let banner = "";
      let banned = "";

      if (msg.channel.guild.member(msg.author).nickname == null) {
        banner = msg.author.username;
      } else {
        banner = msg.channel.guild.member(msg.author).nickname;
      }

      if (msg.channel.guild.member(user).nickname == null) {
        banned = user.username;
      } else {
        banned = msg.channel.guild.member(user).nickname;
      }

      user.sendMessage(msg.author.username + "#" + msg.author.discriminator + " has banned you from " + msg.guild.name + "! Reason: **" + reason + "**.");

      setTimeout(function () {
        msg.channel.guild.member(user).ban()
          .then(() => {
            msg.channel.sendMessage(":ok_hand:");
          })
          .catch(err => {
            msg.reply(`\`${err}\``);
            return;
          });
      }, 1000);
};


text:
using System;
using HyperIoC.Lifetime;

namespace HyperIoC
{
    /// <summary>
    /// Defines the details of an IoC item.
    /// </summary>
    public class ItemDetail
    {
        internal ItemDetail(Type type)
        {
            Type = type;
            LifetimeManager = new TransientLifetimeManager();
        }

        internal Type Type { get; private set; }
        internal ILifetimeManager LifetimeManager { get; set; }
    }
}


text:
layout: default
---

# Mobility Toolbox V 0.0.1

---

### **Description**

This toolbox is a set of classes for generation and analysis of mobility data on Matlab. The aim o the toolbox is to provide easy generation and analysis of mobility data.

### **Current operations supported**

Here is a list of current operations supported by the tool:

* Generation:
 1. Random Waypoint Mobility Model

---

* Analysis:
 1. RSRP (Reference Signal Received Power)
 2. RSSI (Received Signal Strength Indicator)
 3. SINR (Signal to Interference plus Noise Ratio )
 4. RSRQ (Reference Signal Received Quality)

---

* Compute:
 1. Handover A3 event
 2. Handover Opportunistic
 3. Handover Fuzzy (with Matlab Fuzzy toolbox)
 4. Handover TOPSIS

---

## Usage
> Note: Each class or function has **doc** or **help** methods built-in. To use, just type **doc** or **help** and [name of class or function].
* Example 1: doc MobilityGenerator
* Example 2: help MobilityGenerator

## Author Notes:

1. For convention a **cell** refers to a HENB or ENB while **Cell** refers to the Matlab Cell data type.

###  Generate Mobility data
```matlab
% Generate data

generator = MobilityGenerator;  % constructor of class

config = struct( 'POSITION_X_INTERVAL', [0 1000] ,... % Interval x axis on meters
                 'POSITION_Y_INTERVAL', [0 1000],... % Interval y axis on meters
                 'SPEED_INTERVAL', [0 2.78],... % Speed interval for user in m/s
                 'PAUSE_INTERVAL', [0 0] ,... % After some distance user pauses on location
                 'WALK_INTERVAL', [30 90] ,... % Time interval user spends on place
                 'DIRECTION_INTERVAL', [0 360] ,... % Angle direction allowed for user
                 'SIMULATION_TIME', 900 ,...      % Time in seconds
                 'NUMBER_OF_USERS', 100); % Number of users

mobility_model = generator.randomWaypointMobility( config );
```

> Note: Case configuration struct not given, returns mobility data with default values.

### Configuring Mobility Network Class
The network class exposes a series of properties that can be configured and accessed in two ways.

1. Using Getters and Setters.
2. Setting directly the value to a property. (In this case some properties require the use of setters because they need to be evaluted)

#### Class Properties

Here is a list of the public properties of the MobilityNetwork class:

```matlab
    TYPE = 'OO'; % type of communication
    CITY_SIZE = 'M'; %Size of city- Medium
    OPERATIONAL_FREQUENCY = 2000; %Operational frequency 2Ghz
    HEIGHT_BS = 30; %height of BS
    HEIGHT_MS = 1.5; %height of MS
    WALL_WINDOW_LOSS = 10; %Wall/Window loss
    %Pathloss- Parameters of femto
    TYPE_OF_BUILDING = 'R'; %type of building
    OP_FREQUENCY = 2000; %Operational frequency 2000Mhz
    NUMBER_OF_FLOORS_BUILDING = 1;
    %Parameters of eNB
    RESOURCE_BLOCK = 25;%5mhz-25;resource block
    POWER_TX_ENB_DBm = 43;%27/46; DBm Transmitting Power of eNB
    GAIN_TX = 12; %16dBi Antenna Gain
    CABLELOSS = 3; %dB Cable Loss
    NOISE = 0; %w noise

    %Parameters of HenB
    POWER_TX_FEMTO =20; %15/23;DBm Transmitting Power of HeNB
    GAIN_TX_FEMTO=2; %2%dBi Antenna Gain
    BW = 25; % Bandwidth, number of RBs => 5 MHz = 25 PRBs  %20Mhz-100RBs
    NOISE_FEMTO = 0; %w Noise

```

#### Class Getters

```matlab

  net = MobilityNetwork; % Constructor of class

  net.getPowerHenbFemtoWatts(); % Returns Power of HENB in Watts

  net.getPowerHenbFemtoDBm(); % Returns Power of HENB in DBm

  net.getPowerEnbWatts(); % Returns Power of ENB in Watts

  net.getPowerEnbDBm(); % Returns Power of ENB in DBm

  net.getNumberSubcarriers() % Returns number of subcarriers

  net.getPowerTxWattsFemto() % Returns Power Tx of HENB  in Watts

  net.getPowerTxWatts() % Returns Power Tx of ENB in Watts

```

#### Class Setters

```matlab

  net = MobilityNetwork; % Constructor of class

  net.setPowerHenbFemtoWatts(POWER_TX_WATTS , NUMBER_SUBCARRIERS); % Set Power of Henb in Watts

  net.setPowerHenbFemtoDBm(POWER_HENB_FEMTO_WATTS); % Set Power of HENB in DBm

  net.setPowerEnbWatts(NUMBER_SUBCARRIERS, POWER_TX_WATTS); % Set Power of ENB in Watts

  net.setPowerEnbDBm(POWER_ENB_WATTS); % Set Power of ENB in DBm

  net.setNumberSubcarriers(BANDWIDTH) % Set number of subcarriers

  net.setPowerTxWattsFemto(POWER_TX_FEMTO) % Set Power Tx of HENB  in Watts

  net.setPowerTxWatts(POWER_TX_ENB_DBm) % Set Power Tx of ENB in Watts

```

#### Class Methods

#### Calculate RSRP for HENB

 Returns RSRP of given mobility data for HENB

 **Input:**

 **data** => Mobility data generated with class MobilityGenerator

 **femtos** => Matrix with "x" and "y" of femtocells (HENB)

 **Output:**

 **RSRP_femto** => RSRP of femtocells (HENB) in DBm

 **RSRP_femtos_w** => RSRP of femtocells (HENB) in Watts

 **dists_femtos** => Calculated euclidean distance of user to HENB in each second

 **loss_femtos** => Pathloss of cells to user

```matlab

net = MobilityNetwork; % Constructor of class

[RSRP_femto, RSRP_femto_w, dists_femtos, loss_femtos] = net.rsrpFemtos( data , femtos );

```

#### Calculate RSRP for ENB

 Returns RSRP of given mobility data for ENB

 **Input:**

 **data** => Mobility data generated with class MobilityGenerator

 **macros** => Matrix with "x" and "y" of macrocells (ENB)

 **Output:**

 **RSRP_macro** => RSRP of macrocells (ENB) in DBm

 **RSRP_macro_w** => RSRP of macrocells (ENB) in Watts

 **dists_macro** => Calculated euclidean distance of user to ENB in each second

 **loss_macro** => Pathloss of cells to user

```matlab

net = MobilityNetwork; % Constructor of class

[RSRP_macro_w, RSRP_macro, dists_macro, loss_macro] = net.rsrpMacros(data,macro);

```

#### Calculate RSSI

 Returns RSSI of given RSRP

 **Input:**

 **RSRP_femto_macro_w** => Concatented RSRP matrix of ENB and HENB  in Watts

 **Output:**

 **Prxtotal** => Total Power Rx

 **RSSI_femto_macro_w** => RSSI of data

```matlab

net = MobilityNetwork; % Constructor of class

[Prxtotal, RSSI_femto_macro_w] = net.rssi( RSRP_femto_macro_w);

```

#### Calculate RSRQ

 Returns RSRQ of given RSRP and RSSI in Watts

 **Input:**

 **RSRP_femto_macro_w** => Concatented RSRP matrix of ENB and HENB

 **RSSI_femto_macro_w** => Concatented RSSI matrix of ENB and HENB

 **Output:**

 **RSRQ_femto_macro_w** => RSRQ calculated in Watts

 **RSRQ_femto_macro** => RSSQ calculated in DBm

```matlab

net = MobilityNetwork; % Constructor of class

[RSRQ_femto_macro_w,RSRQ_femto_macro] = net.rsrq( RSRP_femto_macro_w , RSSI_femto_macro_w);

```

#### Calculate SINR

 Returns SINR of given RSRP and RSSI in Watts

 **Input:**

 **RSRP_femto_macro_w** => Concatented RSRP matrix of ENB and HENB

 **Prxtotal** => Total Power Rx

 **Output:**

 **SINR_femto_macro_w** => SINR calculated in Watts

 **SINR_femto_macro** => SINR calculated in DBm

```matlab

net = MobilityNetwork; % Constructor of class

[SINR_femto_macro_w,SINR_femto_macro] = net.sinr( RSRP_femto_macro_w , Prxtotal)

```

#### Calculate Channel Capacity

 Calculate the throughput in the Shannon-Hartley theorem for channel capacity
 **Input:**

 **SINR_femto_macro_w** => Concatented SINR matrix of ENB and HENB

 **out_handover_sinr_op** => SINR of Handover Opportunistic result

 **Output:**

 **channel_capacity** => Throughput calculated (per user)

```matlab

net = MobilityNetwork; % Constructor of class

channel_capacity = net.channelCapacity( SINR_femto_macro_w , out_handover_sinr_OP)

```
### Class Connection

This class inherites from MobilityNetwork.

#### Class Properties

```matlab

  LIMITER => limit the number of HENB visible per user

```

#### Class Methods

#### Get user connections with RSRP

**Input:**

 **RSRP_femto** => RSRP of HENB in DBm. Calculated with MobilityNetwork lass

 **RSRP_macro** => RSRP of ENB in DBm. Calculated  with MobilityNetwork class

 **RSRP_femto_w** => RSRP of HENB in Watts.

 **RSRP_macro_w** => RSRP of ENB in DBm. Calculated  with MobilityNetwork class

 **Output:**

**indexes_femto_macro** => Cell Matrix of original positions of values for each user

**conected_femto_macro** => Cell Matrix RSRP in DBm values sorted

**indexes_femto_macro_w** => Cell Matrix of original positions of values for each user

**conected_femto_macro_w** => Cell Matrix RSRP in Watts values sorted for each user

```matlab

  conn = MobilityConnection; % Class constructor

  % Function that returns for each second the best RSRP sorting the matrix with all macro and femtocells

  [indexes_femto_macro, conected_femto_macro, indexes_femto_macro_w, conected_femto_macro_w ] = conectionsRSRP(RSRP_femto , RSRP_macro,RSRP_femto_w , RSRP_macro_w)

```

#### Select initial connected cell of user given RSRP

**Input:**

 **connected_femto_macro** => Cell Matrix RSRP in DBm values sorted

 **indexes_femto_macro** => RSRP of HENB in DBm. Calculated with MobilityNetwork lass

 **Output:**

**initia_cell** => Cell Matrix of original positions of values for each user

**index_initial_cell** => Cell Matrix RSRP in DBm values sorted

```matlab
  %   Select the most appropriate cell for a UE to camp
  %   Camp on servingcell- The cell with the highest RSRP in the measurement set
  [initial_cell, index_initial_cell] = conn.cellSelectionRSRP(conected_femto_macro, indexes_femto_macro)
```

#### Get user connections with SINR

**Input:**

 **SINR_femto_macro** => SINR of ENB and HENB in DBm. Calculated with MobilityNetwork lass

 **Output:**

**indexes_femto_macro_SINR** => Cell Matrix of original positions of values for each user

**conected_femto_macro_SINR** => Cell Matrix SINR in DBm values sorted for each user

```matlab

  conn = MobilityConnection; % Class constructor

  % Function that returns for each second the best SINR sorting the matrix with all macro and femtocells
[indexes_femto_macro_SINR, conected_femto_macro_SINR] = conn.conectionsSINR(SINR_femto_macro)

```

#### Select initial connected cell of user given SINR

**Input:**

 **connected_femto_macro** => Cell Matrix SINR in DBm values sorted

 **indexes_femto_macro** => SINR of HENB in DBm. Calculated with MobilityNetwork lass

 **Output:**

**initia_cell** => Cell Matrix of original positions of values for each user

**index_initial_cell** => Cell Matrix SINR in DBm values sorted

```matlab
  %   Select the most appropriate cell for a UE to camp
  %   Camp on servingcell- The cell with the highest SINR in the measurement set
  [initial_cell, index_initial_cell] = conn.cellSelectionSINR(conected_femto_macro, indexes_femto_macro)
```

#### Get user connections with RSRQ

**Input:**

 **RSRQ_femto_macro** => RSRQ of ENB and HENB in DBm. Calculated with MobilityNetwork lass

 **Output:**

**indexes_femto_macro_RSRQ** => Cell Matrix of original positions of values for each user

**conected_femto_macro_RSRQ** => Cell Matrix RSRQ in DBm values sorted for each user

```matlab

  conn = MobilityConnection; % Class constructor

  % Function that returns for each second the best RSRQ sorting the matrix with all macro and femtocells
[indexes_femto_macro_RSRQ, conected_femto_macro_RSRQ] = conn.conectionsRSRQ(RSRQ_femto_macro)
```

#### Select initial connected cell of user given RSRQ

**Input:**

 **connected_femto_macro_RSRQ** => Cell Matrix RSRQ in DBm values sorted

 **indexes_femto_macro_RSRQ** => RSRQ of HENB in DBm. Calculated with MobilityNetwork lass

 **Output:**

**initia_cell** => Cell Matrix of original positions of values for each user

**index_initial_cell** => Cell Matrix RSRQ in DBm values sorted

```matlab
  %   Select the most appropriate cell for a UE to camp
  %   Camp on servingcell- The cell with the highest RSRQ in the measurement set
  [initial_cell, index_initial_cell] = conn.cellSelectionRSRQ(conected_femto_macro_RSRQ, indexes_femto_macro_RSRQ);
```

#### Get user connections with Channel Capacity

**Input:**

 **ChannelCapacity_femto_macro** => Channel Capacity of ENB and HENB. Calculated with MobilityNetwork lass

 **Output:**

**indexes_femto_macro_ChannelCapacity** => Cell Matrix of original positions of values for each user

**conected_femto_macro_ChannelCapacity** => Cell Matrix of Channel Capacity values sorted for each user

```matlab

  conn = MobilityConnection; % Class constructor

  % Function that returns for each second the best Channel Capacity sorting the matrix with all macro and femtocells
[indexes_femto_macro_ChannelCapacity, conected_femto_macro_ChannelCapacity] = conn.conectionsChannelCapacity(ChannelCapacity_femto_macro);
```

#### Select initial connected cell of user given Channel Capacity

**Input:**

 **conected_femto_macro_ChannelCapacity** => Cell Matrix Channel Capacity values sorted

 **indexes_femto_macro** => Channel Capacity of HENB in DBm. Calculated with MobilityNetwork lass

 **Output:**

**initia_cell** => Cell Matrix of original positions of values for each user

**index_initial_cell** => Cell Matrix Channel Capacity values sorted

```matlab
  %   Select the most appropriate cell for a UE to camp
  %   Camp on servingcell- The cell with the highest Channel Capacity in the measurement set
  [initial_cell, index_initial_cell] = cellSelectionChannelCapacity(obj,conected_femto_macro_ChannelCapacity, indexes_femto_macro);
```

### Class Handover

This class inherites from MobilityNetwork.

#### Class Properties

```matlab
HYSTERESIS = 2; % Hysteresis
     % Parameters of Topsis
    RSRP_MIN = -135; % Max value of RSRP for use in Handover TOPSIS
    RSRP_MAX = -13; % Min value of RSRP for use in Handover TOPSIS
    %Channel
    CHANNEL_CAPACITY_MIN = -10*10^8; % Min value of Channel Capacity for use in Handover TOPSIS
    CHANNEL_CAPACITY_MAX = 13*10^8; % Max value of Channel Capacity for use in Handover TOPSIS
    %SINR
    SINR_MIN = -130; % Min value of SINR for use in Handover TOPSIS
    SINR_MAX = 75; % Max value of Channel Capacity for use in Handover TOPSIS

    % Literals Definition for Topsis
    LITERAL_VERY_LOW    =   [0   0.05   0.1625];          % Literal definition of very low rule
    LITERAL_LOW         =   [0.0525   0.15   0.2925];     % Literal definition of  low rule
    LITERAL_MEDIUM      =   [0.1225    0.2500    0.4225]; % Literal definition of medium rule
    LITERAL_HIGH        =   [0.1925    0.3500    0.5525]; % Literal definition of high rule
    LITERAL_VERY_HIGH   =   [0.2625    0.4500    0.6500]; % Literal definition of very rule

```

#### Class Methods

#### Calculate Handover A3 Event

**Input**

**RSRP_femto_macro**  => Calculated RSRP in DBm.

**RSRQ_femto_macro**  => Calculated RSRQ in DBm.

**SINR_femto_macro**  => Calculated SINR in DBm.

**initial_cell_RSRP**  => Values of RSRP user initially connected.

**initial_cell_RSRQ**  => Values of RSRQ user initially connected.

**initial_cell_SINR**  => Values of SINR user initially connected.

**index_initial_cell_RSRP**  => Original positions connected RSRP

**index_initial_cell_RSRQ**  => Original positions connected RSRQ

**index_initial_cell_SINR**  => Original positions connected SINR

**Output**

**handoverOut** => Struct with evaluated data

> Data description of handoverOut:

OUT_HANDOVER_RSRP  => RSRP values where a handover was counted

OUT_HANDOVER_RSRQ  => RSRQ values where a handover was counted

OUT_HANDOVER_SINR  => SINR values where a handover was counted

INDEX_HANDOVER_RSRP => Index of HENB or ENB on RSRP atrix where user made handover

INDEX_HANDOVER_SINR => Index of HENB or ENB on SINR atrix where user made handover

INDEX_HANDOVER_RSRQ => Index of HENB or ENB on RSRQ atrix where user made handover

TOTAL_HANDOVER_COUNT => Total number of handovers for each users

TOTAL_HANDOVER_FAILURE => Total number of handover failure for each user

TOTAL_HANDOVER_PING_PONG => Total number of handover ping pong

TOTAL_NOT_HANDOVER_PING_PONG => Total number of handover not ping pong

| OUT_HANDOVER_RSRP | OUT_HANDOVER_RSRQ| OUT_HANDOVER_SINR | INDEX_HANDOVER_RSRP | INDEX_HANDOVER_SINR |  INDEX_HANDOVER_RSRQ | TOTAL_HANDOVER_COUNT | TOTAL_HANDOVER_FAILURE | TOTAL_HANDOVER_PING_PONG | TOTAL_NOT_HANDOVER_PING_PONG |
|-------------------|---------------------|---------------------|---------------------|---------------------|-------------------|---------------------|--------------------|--------------------------|------------------------------|
| Cell Array| Cell Array| Cell Array| Cell Array| Cell Array| Cell Array| Cell Array| Cell Array| Cell Array| Cell Array|

```matlab
hand = MobilityHandover; % Class constructor;

handoverOut = hand.handoverA3(Input); % Cited variables in input

```

#### Calculate handover with Fuzzy

Documentation Soon.

#### Calculate handover with TOPSIS

Documentation Soon.

#### Calculate handover with CRE

Documentation Soon.


text:
@implementation Fraction
@synthesize numerator, denominator;

-(id) initWith: (int) n over: (int) d {
    self = [super init];
    if(self)
        [self setTo:n over: d];
    return self;
}

-(void) print
{
    NSLog (@"The value of myFraction is:");
    NSLog (@"%i/%i", numerator, denominator);
}

-(void) setTo: (int) n over: (int) d {
    static int hitCount = 0;
    numerator = n;
    denominator = d;
    hitCount++;

}

//-(int) numerator
//{
//    return numerator;
//}
//
//-(int) denominator
//{
//    return denominator;
//}

-(double) convertToNum
{
    if (denominator != 0)
        return (double) numerator / denominator;
    else
        return NAN;
}

-(void) reduce {
    int u = numerator;
    int v = denominator;
    int temp;

    while(v != 0) {
        temp = u%v;
        u = v;
        v = temp;
    }

    numerator /= u;
    denominator /= u;
}

-(NSString*) description {
    return [NSString stringWithFormat: @"%i/%i", numerator, denominator];
}
@end