<commit_before>import React, { Component, PropTypes } from 'react';
import { Modal } from 'react-bootstrap';
import RosterRacer from './Racer';
import RosterRace from './Race';
import style from './roster.css';

export default class Roster extends Component {
  static propTypes = {
    races: PropTypes.array.isRequired,
    addRace: PropTypes.func.isRequired,
    racers: PropTypes.array.isRequired,
    racerAttributes: PropTypes.object.isRequired,
    addRacer: PropTypes.func.isRequired,
    removeRacers: PropTypes.func.isRequired,
    editRacer: PropTypes.func
  }

  constructor(props, context) {
    super(props, context);
    this.state = {
      search: '',
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      selectedRacers: [],
      showModal: false
    };
  }

  handleSearch(e) {
    this.setState({ search: e.target.value });
  }

  handleSelectAllRacers() {
    const { selectedRacers } = this.state;
    const { racers } = this.props;
    if (selectedRacers.length === racers.length) {
      this.setState({
        selectedRacers: []
      });
    } else {
      this.setState({
        selectedRacers: racers.map((racer) => (racer.id))
      });
    }
  }

  handleRacerSelect(racer) {
    const { selectedRacers } = this.state;
    if (~selectedRacers.indexOf(racer.id)) {
      this.setState({
        selectedRacers: selectedRacers.filter((id) => id !== racer.id)
      });
    } else {
      this.setState({
        selectedRacers: [...selectedRacers, racer.id]
      });
    }
  }

  open() {
    const { search } = this.state;
    this.setState({
      newRacerName: search,
      previousSearch: search,
      search: '',
      showModal: true
    });
  }

  cancel() {
    this.setState({
      search: this.state.previousSearch,
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      showModal: false
    });
  }

  createRacer() {
    const { newRacerName, newRacerAttributes } = this.state;
    const { addRacer } = this.props;
    if (newRacerName.trim().length) {
      addRacer({
        name: newRacerName.trim(),
        ...newRacerAttributes
      });
      this.setState({
        search: '',
        previousSearch: '',
        newRacerName: '',
        newRacerAttributes: {},
        showModal: false
      });
    }
  }

  render() {
    let input;
    const { search, selectedRacers } = this.state;
    const { racerAttributes, races, addRace, racers, removeRacers } = this.props;

    return (

          Roster

                Racers

                  <input
                    type="text"
                    className="form-control"
                    style={{
                      width: '80%'
                    }}
                    placeholder="Search for or create a new racer..."
                    autoFocus="true"
                    value={this.state.search}
                    onChange={this.handleSearch.bind(this)}
                  />
                  <i
                    className={`material-icons md-36 unselectable ${style.addRacerBtn}`}
                    tabIndex="0"
                    onClick={() => { this.open(); }}
                    onKeyDown={(e) => {
                      if (e.keyCode === 13) {
                        this.open();
                      }
                    }}
                  >
                    add_box

                    <th
                      className={`${style.racersHeader} unselectable`}
                      onClick={() => this.handleSelectAllRacers()}
                    >

                        {selectedRacers.length === racers.length && racers.length ?
                          'check_box' : 'check_box_outline_blank'
                        }

                    <th className={`${style.racersHeader} unselectable`}>Name

                  {racers.filter((racer) => {
                    if (search && search && search.trim()) {
                      return ~racer.name.toLowerCase().indexOf(search.trim().toLowerCase());
                    }
                    return true;
                  }).map((racer) => (
                    <RosterRacer
                      key={`racer-${racer.id}`}
                      racer={racer}
                      selected={(selectedRacers.indexOf(racer.id) > -1)}
                      onClick={() => this.handleRacerSelect(racer)}
                    />
                  ))}

              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    removeRacers(selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Delete Selected
              </button>
              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    addRace(selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Add Race with selected Racers
              </button>

                Race Setup

              {races.map((race) => (
                <RosterRace
                  key={`race-${race.id}`}
                  race={race}
                  racers={race.racers.map(
                    (racerId) => racers.find((racer) => racer.id === racerId)
                  )}
                />
              ))}

        <Modal
          show={this.state.showModal}
          onHide={() => { this.cancel(); }}
          animation={false}
        >
          <Modal.Header closeButton>
            <Modal.Title>Add Racer</Modal.Title>
          </Modal.Header>
          <Modal.Body>

              Name
              <input
                className="form-control"
                type="text"
                id="newRacerName"
                value={this.state.newRacerName}
                onChange={(e) => {
                  this.setState({ newRacerName: e.target.value });
                }}
              />

          </Modal.Body>
          <Modal.Footer>
            <button
              className="btn btn-default"
              onClick={() => { this.cancel(); }}
            >
              Cancel
            </button>
            <button
              className="btn btn-primary"
              onClick={() => {
                this.createRacer();
              }}
            >
              Save
            </button>
          </Modal.Footer>
        </Modal>

    );
  }
}
<commit_msg>Adding racerAttributes to most places on the roster page.<commit_after>import React, { Component, PropTypes } from 'react';
import { FormGroup, Modal, Radio } from 'react-bootstrap';
import RosterRacer from './Racer';
import RosterRace from './Race';
import style from './roster.css';

const racerAttributeRadioGroup = (key, options, onChange) => (
  <FormGroup
    style={{
      float: 'left',
      display: 'inline-block',
      width: '50%',
      paddingLeft: '5px'
    }}
  >
    {key}
    {options.map((option) => (
      <Radio
        key={option}
        name={key}
        value={option}
        onChange={onChange}
      >
        {option}
      </Radio>
    ))}
  </FormGroup>
);

export default class Roster extends Component {
  static propTypes = {
    races: PropTypes.array.isRequired,
    addRace: PropTypes.func.isRequired,
    racers: PropTypes.array.isRequired,
    racerAttributes: PropTypes.object.isRequired,
    addRacer: PropTypes.func.isRequired,
    removeRacers: PropTypes.func.isRequired,
    editRacer: PropTypes.func
  }

  constructor(props, context) {
    super(props, context);
    this.state = {
      search: '',
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      selectedRacers: [],
      showModal: false
    };
  }

  handleSearch(e) {
    this.setState({ search: e.target.value });
  }

  handleSelectAllRacers() {
    const { selectedRacers } = this.state;
    const { racers } = this.props;
    if (selectedRacers.length === racers.length) {
      this.setState({
        selectedRacers: []
      });
    } else {
      this.setState({
        selectedRacers: racers.map((racer) => (racer.id))
      });
    }
  }

  handleRacerSelect(racer) {
    const { selectedRacers } = this.state;
    if (~selectedRacers.indexOf(racer.id)) {
      this.setState({
        selectedRacers: selectedRacers.filter((id) => id !== racer.id)
      });
    } else {
      this.setState({
        selectedRacers: [...selectedRacers, racer.id]
      });
    }
  }

  open() {
    const { search } = this.state;
    this.setState({
      newRacerName: search,
      previousSearch: search,
      search: '',
      showModal: true
    });
  }

  cancel() {
    this.setState({
      search: this.state.previousSearch,
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      showModal: false
    });
  }

  createRacer() {
    const { newRacerName, newRacerAttributes } = this.state;
    const { addRacer } = this.props;
    if (newRacerName.trim().length) {
      addRacer({
        name: newRacerName.trim(),
        ...newRacerAttributes
      });
      this.setState({
        search: '',
        previousSearch: '',
        newRacerName: '',
        newRacerAttributes: {},
        showModal: false
      });
    }
  }

  render() {
    let input;
    const { search, selectedRacers } = this.state;
    const { racerAttributes, races, addRace, racers, removeRacers } = this.props;

    return (

          Roster

                Racers

                  <input
                    type="text"
                    className="form-control"
                    style={{
                      width: '80%'
                    }}
                    placeholder="Search for or create a new racer..."
                    autoFocus="true"
                    value={this.state.search}
                    onChange={this.handleSearch.bind(this)}
                  />
                  <i
                    className={`material-icons md-36 unselectable ${style.addRacerBtn}`}
                    tabIndex="0"
                    onClick={() => { this.open(); }}
                    onKeyDown={(e) => {
                      if (e.keyCode === 13) {
                        this.open();
                      }
                    }}
                  >
                    add_box

                    <th
                      className={`${style.racersHeader} unselectable`}
                      onClick={() => this.handleSelectAllRacers()}
                    >

                        {selectedRacers.length === racers.length && racers.length ?
                          'check_box' : 'check_box_outline_blank'
                        }

                    <th className={`${style.racersHeader} unselectable`}>Name
                    {Object.keys(racerAttributes).map((key) => (
                      <th className={`${style.racersHeader} unselectable`}>{key}
                    ))}

                  {racers.filter((racer) => {
                    if (search && search && search.trim()) {
                      return ~racer.name.toLowerCase().indexOf(search.trim().toLowerCase());
                    }
                    return true;
                  }).map((racer) => (
                    <RosterRacer
                      key={`racer-${racer.id}`}
                      racer={racer}
                      racerAttributes={racerAttributes}
                      selected={(selectedRacers.indexOf(racer.id) > -1)}
                      onClick={() => this.handleRacerSelect(racer)}
                    />
                  ))}

              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    removeRacers(selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Delete Selected
              </button>
              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    addRace(selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Add Race with selected Racers
              </button>

                Race Setup

              {races.map((race) => (
                <RosterRace
                  key={`race-${race.id}`}
                  race={race}
                  racers={race.racers.map(
                    (racerId) => racers.find((racer) => racer.id === racerId)
                  )}
                />
              ))}

        <Modal
          show={this.state.showModal}
          onHide={() => { this.cancel(); }}
          animation={false}
        >
          <Modal.Header closeButton>
            <Modal.Title>Add Racer</Modal.Title>
          </Modal.Header>
          <Modal.Body>

              Name
              <input
                className="form-control"
                type="text"
                id="newRacerName"
                value={this.state.newRacerName}
                onChange={(e) => {
                  this.setState({ newRacerName: e.target.value });
                }}
              />

            {
              Object.keys(racerAttributes).map((key) => (
                racerAttributeRadioGroup(key, racerAttributes[key], (e) => {
                  const { newRacerAttributes } = this.state;
                  this.setState({
                    newRacerAttributes: Object.assign(
                      {},
                      newRacerAttributes,
                      { [key]: e.target.value }
                    )
                  });
                })
              ))
            }
          </Modal.Body>
          <Modal.Footer>
            <button
              className="btn btn-default"
              onClick={() => { this.cancel(); }}
            >
              Cancel
            </button>
            <button
              className="btn btn-primary"
              onClick={() => {
                this.createRacer();
              }}
            >
              Save
            </button>
          </Modal.Footer>
        </Modal>

    );
  }
}
<|endoftext|>


<commit_before>var n2kMappings = require("./n2kMappings.js").mappings;
var through = require('through');
var debug = require('debug')('signalk:n2k-signalk')

var toDelta = function(n2k) {
  var theMappings = n2kMappings[n2k.pgn];
  var result = {
    updates: [{
      source: {
        label: '',
        type: 'NMEA2000',
        pgn: Number(n2k.pgn),
        src: n2k.src
      },
      timestamp: n2k.timestamp,
      values: toValuesArray(theMappings, n2k)
    }]
  };
  if (typeof theMappings != 'undefined') {
    theMappings.forEach(function(mapping) {
      if (typeof mapping.context === 'function') {
        result.context = mapping.context(n2k);
      }
    });
  }
  return result;
}

function getValue(n2k, theMapping) {
  if (typeof theMapping.source != 'undefined') {
    var stringValue = n2k.fields[theMapping.source];
    var numberValue = Number(stringValue);
    return isNaN(numberValue) ? stringValue : numberValue;
  } else {
    return theMapping.value(n2k);
  }
}

var toValuesArray = function(theMappings, n2k) {
  if (typeof theMappings != 'undefined') {
    return theMappings
      .filter(function(theMapping) {
        try {
          return typeof theMapping.filter === 'undefined' || theMapping.filter(n2k);
        } catch (ex) {
          process.stderr.write(ex + ' ' + n2k);
          return false;
        }
      })
      .map(function(theMapping) {
        try {
          if (typeof theMapping.node != 'undefined') {
            return {
              path: theMapping.node,
              value: getValue(n2k, theMapping)
            }
          }
        } catch (ex) {
          process.stderr.write(ex + ' ' + n2k);
        }
      })
      .filter(function(x) {
        return x != undefined;
      });
  }
  return [];
}

var addToTree = function(pathValue, source, tree) {
  var result = {};
  var temp = tree;
  var parts = msg.path.split('.');
  for (var i = 0; i < parts.length - 1; i++) {
    temp[parts[i]] = {};
    temp = temp[parts[i]];
  }
  temp[parts[parts.length - 1]] = msg;
  return result;
}

function addAsNested(pathValue, source, timestamp, result) {
  var temp = result;
  var parts = pathValue.path.split('.');
  for (var i = 0; i < parts.length - 1; i++) {
    if (typeof temp[parts[i]] === 'undefined') {
      temp[parts[i]] = {};
    }
    temp = temp[parts[i]];
  };

  //mapping produced an object like {latitude:...,longitude:...}
  if (typeof pathValue.value === 'object') {
    temp[parts[parts.length - 1]] = pathValue.value;
    temp[parts[parts.length - 1]].source = source;
    temp[parts[parts.length - 1]].timestamp = timestamp + '';
  } else {
    temp[parts[parts.length - 1]] = {
      value: pathValue.value,
      source: source,
      timestamp: timestamp + ''
    };
  }
}

function deltaToNested(delta) {
  var result = {};
  var timestamp = delta.updates[0].timestamp;
  delete delta.updates[0].source.timestamp;
  delta.updates[0].values.forEach(function(pathValue) {
    addAsNested(pathValue, delta.updates[0].source, timestamp, result);
  });
  return result;
}

exports.toDelta = toDelta;
exports.toNested = function(n2k) {
  return deltaToNested(toDelta(n2k));
}

exports.toDeltaTransformer = function(options) {
  var stream = through(function(data) {
    if (options.debug) {
      console.log(data);
    }
    stream.queue(exports.toDelta(data));
  });
  return stream;
}

exports.toNestedTransformer = function(options) {
  var stream = through(function(data) {
    if (options.debug) {
      console.log(data);
    }
    var nested = exports.toNested(data);
    if (Object.getOwnPropertyNames(nested).length > 0) {
      stream.queue(nested);
    }
  });
  return stream;
}<commit_msg>Src is string in schema to encapsulate all kinds of source info<commit_after>var n2kMappings = require("./n2kMappings.js").mappings;
var through = require('through');
var debug = require('debug')('signalk:n2k-signalk')

var toDelta = function(n2k) {
  var theMappings = n2kMappings[n2k.pgn];
  var result = {
    updates: [{
      source: {
        label: '',
        type: 'NMEA2000',
        pgn: Number(n2k.pgn),
        src: n2k.src.toString()
      },
      timestamp: n2k.timestamp,
      values: toValuesArray(theMappings, n2k)
    }]
  };
  if (typeof theMappings != 'undefined') {
    theMappings.forEach(function(mapping) {
      if (typeof mapping.context === 'function') {
        result.context = mapping.context(n2k);
      }
    });
  }
  return result;
}

function getValue(n2k, theMapping) {
  if (typeof theMapping.source != 'undefined') {
    var stringValue = n2k.fields[theMapping.source];
    var numberValue = Number(stringValue);
    return isNaN(numberValue) ? stringValue : numberValue;
  } else {
    return theMapping.value(n2k);
  }
}

var toValuesArray = function(theMappings, n2k) {
  if (typeof theMappings != 'undefined') {
    return theMappings
      .filter(function(theMapping) {
        try {
          return typeof theMapping.filter === 'undefined' || theMapping.filter(n2k);
        } catch (ex) {
          process.stderr.write(ex + ' ' + n2k);
          return false;
        }
      })
      .map(function(theMapping) {
        try {
          if (typeof theMapping.node != 'undefined') {
            return {
              path: theMapping.node,
              value: getValue(n2k, theMapping)
            }
          }
        } catch (ex) {
          process.stderr.write(ex + ' ' + n2k);
        }
      })
      .filter(function(x) {
        return x != undefined;
      });
  }
  return [];
}

var addToTree = function(pathValue, source, tree) {
  var result = {};
  var temp = tree;
  var parts = msg.path.split('.');
  for (var i = 0; i < parts.length - 1; i++) {
    temp[parts[i]] = {};
    temp = temp[parts[i]];
  }
  temp[parts[parts.length - 1]] = msg;
  return result;
}

function addAsNested(pathValue, source, timestamp, result) {
  var temp = result;
  var parts = pathValue.path.split('.');
  for (var i = 0; i < parts.length - 1; i++) {
    if (typeof temp[parts[i]] === 'undefined') {
      temp[parts[i]] = {};
    }
    temp = temp[parts[i]];
  };

  //mapping produced an object like {latitude:...,longitude:...}
  if (typeof pathValue.value === 'object') {
    temp[parts[parts.length - 1]] = pathValue.value;
    temp[parts[parts.length - 1]].source = source;
    temp[parts[parts.length - 1]].timestamp = timestamp + '';
  } else {
    temp[parts[parts.length - 1]] = {
      value: pathValue.value,
      source: source,
      timestamp: timestamp + ''
    };
  }
}

function deltaToNested(delta) {
  var result = {};
  var timestamp = delta.updates[0].timestamp;
  delete delta.updates[0].source.timestamp;
  delta.updates[0].values.forEach(function(pathValue) {
    addAsNested(pathValue, delta.updates[0].source, timestamp, result);
  });
  return result;
}

exports.toDelta = toDelta;
exports.toNested = function(n2k) {
  return deltaToNested(toDelta(n2k));
}

exports.toDeltaTransformer = function(options) {
  var stream = through(function(data) {
    if (options.debug) {
      console.log(data);
    }
    stream.queue(exports.toDelta(data));
  });
  return stream;
}

exports.toNestedTransformer = function(options) {
  var stream = through(function(data) {
    if (options.debug) {
      console.log(data);
    }
    var nested = exports.toNested(data);
    if (Object.getOwnPropertyNames(nested).length > 0) {
      stream.queue(nested);
    }
  });
  return stream;
}
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import { connect } from 'react-redux'
import { Text } from 'react-native'

import { Router, Scene } from 'react-native-router-flux'

import BusListView from '../components/BusListView';
import StopRequestView from '../components/StopRequestView';
import StartView from '../components/StartView';

const RouterWithRedux = connect()(Router)

class TravellerApp extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
      <RouterWithRedux>
        <Scene key="root" hideNavBar={true}>
          <Scene key="start" component={StartView} initial={true} />
          <Scene key="departures" component={BusListView} />
          <Scene key="stopRequest" component={StopRequestView} type="replace" />
        </Scene>
      </RouterWithRedux>
    )
  }
}

const mapStateProps = (state) => {
  return {

  }
}

const mapDispatchToProps = (dispatch) => {
  return {

  }
}

export default connect(mapStateProps, mapDispatchToProps)(TravellerApp)
<commit_msg>scenes are now separated to pages that contain components<commit_after>import React, {Component} from 'react'
import { connect } from 'react-redux'
import { Text } from 'react-native'

import { Router, Scene } from 'react-native-router-flux'

import BusListPage from '../pages/BusListPage';
import StopRequestPage from '../pages/StopRequestPage';
import StartPage from '../pages/StartPage';

const RouterWithRedux = connect()(Router)

class TravellerApp extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
      <RouterWithRedux>
        <Scene key="root" hideNavBar={true}>
          <Scene key="start" component={StartPage} initial={true} />
          <Scene key="departures" component={BusListPage} />
          <Scene key="stopRequest" component={StopRequestPage} type="replace" />
        </Scene>
      </RouterWithRedux>
    )
  }
}

const mapStateProps = (state) => {
  return {

  }
}

const mapDispatchToProps = (dispatch) => {
  return {

  }
}

export default connect(mapStateProps, mapDispatchToProps)(TravellerApp)
<|endoftext|>


<commit_before>import test from 'tape'
import axios from 'axios'
import Express from 'express'

import branchesRouter from './branches'
import { API_REPOS_BRANCHES } from '../../../../../share/constants/api'

let app
let PORT
test.test('setup', t => {
  app = new Express().use(branchesRouter).listen(0)
  PORT = app.address().port
  t.end()
})

test(`GET ${API_REPOS_BRANCHES} with no param should return branches in default branch`, t => {
  axios
    .get(`http://localhost:${PORT}/api/v1/repos/user1/repo1/branches`)
    .then(res => {
      // console.log(require('util').inspect(res.data, false, null))
      t.deepEqual(
        res.data.sort((a, b) => a.commit.author.date > b.commit.author.date),
        [
          {
            name: 'feature',
            commit: {
              author: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-09-26T15:08:24.000Z'
              },
              committer: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-09-27T01:08:48.000Z'
              },
              message: 'Add `!` to file2\n',
              parents: [
                {
                  url:
                    'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/297862f2168af863ae0e2735caabe8b7461f188f',
                  sha: '297862f2168af863ae0e2735caabe8b7461f188f'
                }
              ],
              sha: '2394f21336aec34a5a225f1e8b9039593f1d1e27',
              tree: {
                url:
                  'http://localhost:3000/api/v1/repos/undefined/undefined/git/trees/ec03c563e29b0f50af9e561ad19f9df24dfe7e10',
                sha: 'ec03c563e29b0f50af9e561ad19f9df24dfe7e10'
              },
              url:
                'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/2394f21336aec34a5a225f1e8b9039593f1d1e27'
            }
          },
          {
            name: 'master',
            commit: {
              author: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-10-24T14:13:53.000Z'
              },
              committer: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-10-24T14:13:53.000Z'
              },
              message: 'Add nested file\n',
              parents: [
                {
                  url:
                    'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/f1582566910f7a5d41b47f0c93ed560e1e1fd8d0',
                  sha: 'f1582566910f7a5d41b47f0c93ed560e1e1fd8d0'
                }
              ],
              sha: '0100c14d9341db683c43e47c6944ecb1616005bd',
              tree: {
                url:
                  'http://localhost:3000/api/v1/repos/undefined/undefined/git/trees/dfd076cc884b4554bab928f62123fb262c02ec6c',
                sha: 'dfd076cc884b4554bab928f62123fb262c02ec6c'
              },
              url:
                'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/0100c14d9341db683c43e47c6944ecb1616005bd'
            }
          }
        ].sort((a, b) => a.commit.author.date > b.commit.author.date)
      )
    })
    .catch(err => {
      t.fail(err.toString())
    })
    .then(t.end)
})

test(`GET ${API_REPOS_BRANCHES} from no exists repo should return 404`, t => {
  axios
    .get(`http://localhost:${PORT}/api/v1/repos/no_exists_user/foo/branches`)
    .then(res => {
      t.fail(res)
    })
    .catch(err => {
      t.is(err.response.status, 404)
    })
    .then(t.end)
})

test.test('teardown', t => {
  app.close()
  t.end()
})
<commit_msg>Pass typecheck<commit_after>// @flow

import test from 'tape'
import axios from 'axios'
import Express from 'express'

import branchesRouter from './branches'
import { API_REPOS_BRANCHES } from '../../../../../share/constants/api'

let app
let PORT
test.test('setup', t => {
  app = Express()
    .use(branchesRouter)
    .listen(0)
  PORT = app.address().port
  t.end()
})

test(`GET ${API_REPOS_BRANCHES} with no param should return branches in default branch`, t => {
  axios
    .get(`http://localhost:${PORT}/api/v1/repos/user1/repo1/branches`)
    .then(res => {
      // console.log(require('util').inspect(res.data, false, null))
      t.deepEqual(
        res.data.sort(
          (a, b) =>
            a.commit.author.date > b.commit.author.date
              ? 1
              : a.commit.author.date < b.commit.author.date ? -1 : 0
        ),
        [
          {
            name: 'feature',
            commit: {
              author: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-09-26T15:08:24.000Z'
              },
              committer: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-09-27T01:08:48.000Z'
              },
              message: 'Add `!` to file2\n',
              parents: [
                {
                  url:
                    'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/297862f2168af863ae0e2735caabe8b7461f188f',
                  sha: '297862f2168af863ae0e2735caabe8b7461f188f'
                }
              ],
              sha: '2394f21336aec34a5a225f1e8b9039593f1d1e27',
              tree: {
                url:
                  'http://localhost:3000/api/v1/repos/undefined/undefined/git/trees/ec03c563e29b0f50af9e561ad19f9df24dfe7e10',
                sha: 'ec03c563e29b0f50af9e561ad19f9df24dfe7e10'
              },
              url:
                'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/2394f21336aec34a5a225f1e8b9039593f1d1e27'
            }
          },
          {
            name: 'master',
            commit: {
              author: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-10-24T14:13:53.000Z'
              },
              committer: {
                name: 'keik',
                email: 'k4t0.kei@gmail.com',
                date: '2016-10-24T14:13:53.000Z'
              },
              message: 'Add nested file\n',
              parents: [
                {
                  url:
                    'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/f1582566910f7a5d41b47f0c93ed560e1e1fd8d0',
                  sha: 'f1582566910f7a5d41b47f0c93ed560e1e1fd8d0'
                }
              ],
              sha: '0100c14d9341db683c43e47c6944ecb1616005bd',
              tree: {
                url:
                  'http://localhost:3000/api/v1/repos/undefined/undefined/git/trees/dfd076cc884b4554bab928f62123fb262c02ec6c',
                sha: 'dfd076cc884b4554bab928f62123fb262c02ec6c'
              },
              url:
                'http://localhost:3000/api/v1/repos/undefined/undefined/git/commits/0100c14d9341db683c43e47c6944ecb1616005bd'
            }
          }
        ].sort(
          (a, b) =>
            a.commit.author.date > b.commit.author.date
              ? 1
              : a.commit.author.date < b.commit.author.date ? -1 : 0
        )
      )
    })
    .catch(err => {
      t.fail(err.toString())
    })
    .then(t.end)
})

test(`GET ${API_REPOS_BRANCHES} from no exists repo should return 404`, t => {
  axios
    .get(`http://localhost:${PORT}/api/v1/repos/no_exists_user/foo/branches`)
    .then(() => {
      t.fail()
    })
    .catch(err => {
      t.is(err.response.status, 404)
    })
    .then(t.end)
})

test.test('teardown', t => {
  app.close()
  t.end()
})
<|endoftext|>


<commit_before>exports.index = function(req, res) {
  /**
   * TODO: Shouldn't a block like this be in a `before` method?
   */
  var user = res.locals.user || null;
  if (!user) {
    req.flash('error', 'You should be logged in...');
    return res.redirect('/');
  }

  // TODO: This could change, and is here for the purpose of stubbing this
  // page out. It should be configured elsewhere.
  var sections = [{
    name: 'Posts',
    actions: [
      {title: 'List', path: '/admin/posts/'},
      {title: 'Create', path: '/admin/posts/new'}
    ]
  }, {
    name: 'Users',
    actions: [
      {title: 'List', path: '/admin/users'}
    ]
  }, {
    name: 'Comments',
    actions: [
      {title: 'List', path: '/admin/comments'}
    ]
  }];

  res.render('admin/index', {
    title: 'Admin Panel',
    sections: sections
  });
};
<commit_msg>Fixed whitespace.<commit_after>exports.index = function(req, res) {
  /**
   * TODO: Shouldn't a block like this be in a `before` method?
   */
  var user = res.locals.user || null;
  if (!user) {
    req.flash('error', 'You should be logged in...');
    return res.redirect('/');
  }

  // TODO: This could change, and is here for the purpose of stubbing this
  // page out. It should be configured elsewhere.
  var sections = [{
    name: 'Posts',
    actions: [
      {title: 'List', path: '/admin/posts/'},
      {title: 'Create', path: '/admin/posts/new'}
    ]
  }, {
    name: 'Users',
    actions: [
      {title: 'List', path: '/admin/users'}
    ]
  }, {
    name: 'Comments',
    actions: [
      {title: 'List', path: '/admin/comments'}
    ]
  }];

  res.render('admin/index', {
    title: 'Admin Panel',
    sections: sections
  });
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';
import ajax from 'ic-ajax';

var NUM_VERSIONS = 5;

export default Ember.ObjectController.extend({
    needs: ['application'],
    isDownloading: false,

    fetchingDownloads: true,
    fetchingFollowing: true,
    following: false,
    showAllVersions: false,
    currentVersion: null,
    requestedVersion: null,
    keywords: [],

    sortedVersions: function() {
        return this.get("model.versions");
    }.property('model.versions.[]'),

    smallSortedVersions: function() {
        return this.get('sortedVersions').slice(0, NUM_VERSIONS);
    }.property('sortedVersions'),

    hasMoreVersions: function() {
        return this.get("sortedVersions.length") > NUM_VERSIONS;
    }.property('sortedVersions'),

    displayedAuthors: function() {
        var self = this;
        if (!this.get('currentVersion')) {
            return [];
        }
        return DS.PromiseArray.create({
            promise: this.get('currentVersion.authors').then(function(authors) {
                var ret = [];
                authors.forEach(function(author) {
                    ret.push(author);
                });
                var others = self.store.metadataFor('user');
                for (var i = 0; i < others.names.length; i++) {
                    ret.push({name: others.names[i]});
                }
                return ret;
            }),
        });
    }.property('currentVersion.authors.@each'),

    anyKeywords: function() {
        return this.get('keywords.length') > 0;
    }.property('keywords'),

    actions: {
        download: function(version) {
            this.set('isDownloading', true);
            var self = this;
            var crate_downloads = this.get('model').get('downloads');
            var ver_downloads = version.get('downloads');
            return ajax({
                url: version.get('dl_path'),
                dataType: 'json',
            }).then(function(data) {
                self.get('model').set('downloads', crate_downloads + 1);
                version.set('downloads', ver_downloads + 1);
                Ember.$('#download-frame').attr('src', data.url);
            }).finally(function() {
                self.set('isDownloading', false);
            });
        },

        toggleVersions: function() {
            this.get('controllers.application')
                .resetDropdownOption(this, 'showAllVersions');
        },

        toggleFollow: function() {
            this.set('fetchingFollowing', true);
            this.set('following', !this.get('following'));
            var url = '/api/v1/crates/' + this.get('model.name') + '/follow';
            var method;
            if (this.get('following')) {
                method = 'put';
            } else {
                method = 'delete';
            }
            var self = this;
            ajax({ method: method, url: url }).finally(function() {
                self.set('fetchingFollowing', false);
            });
        },

        renderChart: function(downloads) {
            var dates = {};
            var versions = [];
            for (var i = 0; i < 90; i++) {
                var now = moment().subtract(i, 'days');
                dates[now.format('MMM D')] = {date: now, cnt: {}};
            }
            downloads.forEach(function(d) {
                var version_id = d.get('version.id');
                var key = moment(d.get('date')).utc().format('MMM D');
                if (dates[key]) {
                    var prev = dates[key].cnt[version_id] || 0;
                    dates[key].cnt[version_id] = prev + d.get('downloads');
                }
            });
            if (this.get('requestedVersion')) {
                versions.push({
                    id: this.get('currentVersion.id'),
                    num: this.get('currentVersion.num'),
                });
            } else {
                var tmp = this.get('smallSortedVersions');
                for (i = 0; i < tmp.length; i++) {
                    versions.push({id: tmp[i].get('id'), num: tmp[i].get('num')});
                }
            }

            var headers = ['Date'];
            versions.sort(function(b) { return b.num; });
            for (i = 0; i < versions.length; i++) {
                headers.push(versions[i].num);
            }
            var data = [headers];
            for (var date in dates) {
                var row = [dates[date].date.toDate()];
                for (i = 0; i < versions.length; i++) {
                    row.push(dates[date].cnt[versions[i].id] || 0);
                }
                data.push(row);
            }

            var drawChart = function() {
                if (!window.google || !window.googleChartsLoaded) {
                    Ember.$('.graph').hide();
                    return;
                } else {
                    Ember.$('.graph').show();
                }
                data = google.visualization.arrayToDataTable(data);

                var fmt = new google.visualization.DateFormat({
                    pattern: 'LLL d, yyyy',
                });
                fmt.format(data, 0);
                var el = document.getElementById('graph-data');
                if (!el) {
                    return;
                }
                var chart = new google.visualization.LineChart(el);
                chart.draw(data, {
                    chartArea: {'width': '80%', 'height': '80%'},
                    hAxis: {
                        minorGridlines: { count: 8 },
                    },
                    vAxis: {
                        minorGridlines: { count: 5 },
                        viewWindow: { min: 0, },
                    },
                });
            };

            Ember.run.scheduleOnce('afterRender', this, drawChart);
            Ember.$(window).off('resize.chart');
            Ember.$(window).on('resize.chart', drawChart);
            Ember.$(document).off('googleChartsLoaded');
            Ember.$(document).on('googleChartsLoaded', drawChart);
        },
    },
});

<commit_msg>Fix redrawing charts on resize<commit_after>import Ember from 'ember';
import DS from 'ember-data';
import ajax from 'ic-ajax';

var NUM_VERSIONS = 5;

export default Ember.ObjectController.extend({
    needs: ['application'],
    isDownloading: false,

    fetchingDownloads: true,
    fetchingFollowing: true,
    following: false,
    showAllVersions: false,
    currentVersion: null,
    requestedVersion: null,
    keywords: [],

    sortedVersions: function() {
        return this.get("model.versions");
    }.property('model.versions.[]'),

    smallSortedVersions: function() {
        return this.get('sortedVersions').slice(0, NUM_VERSIONS);
    }.property('sortedVersions'),

    hasMoreVersions: function() {
        return this.get("sortedVersions.length") > NUM_VERSIONS;
    }.property('sortedVersions'),

    displayedAuthors: function() {
        var self = this;
        if (!this.get('currentVersion')) {
            return [];
        }
        return DS.PromiseArray.create({
            promise: this.get('currentVersion.authors').then(function(authors) {
                var ret = [];
                authors.forEach(function(author) {
                    ret.push(author);
                });
                var others = self.store.metadataFor('user');
                for (var i = 0; i < others.names.length; i++) {
                    ret.push({name: others.names[i]});
                }
                return ret;
            }),
        });
    }.property('currentVersion.authors.@each'),

    anyKeywords: function() {
        return this.get('keywords.length') > 0;
    }.property('keywords'),

    actions: {
        download: function(version) {
            this.set('isDownloading', true);
            var self = this;
            var crate_downloads = this.get('model').get('downloads');
            var ver_downloads = version.get('downloads');
            return ajax({
                url: version.get('dl_path'),
                dataType: 'json',
            }).then(function(data) {
                self.get('model').set('downloads', crate_downloads + 1);
                version.set('downloads', ver_downloads + 1);
                Ember.$('#download-frame').attr('src', data.url);
            }).finally(function() {
                self.set('isDownloading', false);
            });
        },

        toggleVersions: function() {
            this.get('controllers.application')
                .resetDropdownOption(this, 'showAllVersions');
        },

        toggleFollow: function() {
            this.set('fetchingFollowing', true);
            this.set('following', !this.get('following'));
            var url = '/api/v1/crates/' + this.get('model.name') + '/follow';
            var method;
            if (this.get('following')) {
                method = 'put';
            } else {
                method = 'delete';
            }
            var self = this;
            ajax({ method: method, url: url }).finally(function() {
                self.set('fetchingFollowing', false);
            });
        },

        renderChart: function(downloads) {
            var dates = {};
            var versions = [];
            for (var i = 0; i < 90; i++) {
                var now = moment().subtract(i, 'days');
                dates[now.format('MMM D')] = {date: now, cnt: {}};
            }
            downloads.forEach(function(d) {
                var version_id = d.get('version.id');
                var key = moment(d.get('date')).utc().format('MMM D');
                if (dates[key]) {
                    var prev = dates[key].cnt[version_id] || 0;
                    dates[key].cnt[version_id] = prev + d.get('downloads');
                }
            });
            if (this.get('requestedVersion')) {
                versions.push({
                    id: this.get('currentVersion.id'),
                    num: this.get('currentVersion.num'),
                });
            } else {
                var tmp = this.get('smallSortedVersions');
                for (i = 0; i < tmp.length; i++) {
                    versions.push({id: tmp[i].get('id'), num: tmp[i].get('num')});
                }
            }

            var headers = ['Date'];
            versions.sort(function(b) { return b.num; });
            for (i = 0; i < versions.length; i++) {
                headers.push(versions[i].num);
            }
            var data = [headers];
            for (var date in dates) {
                var row = [dates[date].date.toDate()];
                for (i = 0; i < versions.length; i++) {
                    row.push(dates[date].cnt[versions[i].id] || 0);
                }
                data.push(row);
            }

            var drawChart = function() {
                if (!window.google || !window.googleChartsLoaded) {
                    Ember.$('.graph').hide();
                    return;
                } else {
                    Ember.$('.graph').show();
                }
                var myData = google.visualization.arrayToDataTable(data);

                var fmt = new google.visualization.DateFormat({
                    pattern: 'LLL d, yyyy',
                });
                fmt.format(myData, 0);
                var el = document.getElementById('graph-data');
                if (!el) {
                    return;
                }
                var chart = new google.visualization.LineChart(el);
                chart.draw(myData, {
                    chartArea: {'width': '80%', 'height': '80%'},
                    hAxis: {
                        minorGridlines: { count: 8 },
                    },
                    vAxis: {
                        minorGridlines: { count: 5 },
                        viewWindow: { min: 0, },
                    },
                });
            };

            Ember.run.scheduleOnce('afterRender', this, drawChart);
            Ember.$(window).off('resize.chart');
            Ember.$(window).on('resize.chart', drawChart);
            Ember.$(document).off('googleChartsLoaded');
            Ember.$(document).on('googleChartsLoaded', drawChart);
        },
    },
});

<|endoftext|>


<commit_before>var restUrl =  "https://www.dliv.in/rest/";
var status = 0;

var result;
function rest(opts,url, success, error){
	status = 0;
	result="";
	$.ajax(
	{
		url: restUrl+url,
		dataType: "json",
		global: false,
		async: true,
		data: opts,
		success: success,
		error: error
	});
	return result;
}

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function addActivity(opts,success,error) {
	status = 0;
	$.ajax(
	{
		url: restUrl+"stream",
		type: "POST",
		global: false,
		async: true,
		dataType: 'JSON',
		data: opts,
		success: success,
		error: error
	});
}
function addCommentRest(opts,url, success,error) {
	status = 0;
	$.ajax(
	{
		url: restUrl+url,
		type: "POST",
		global: false,
		async: true,
		dataType: 'JSON',
		data: opts,
		success: success,
		error: error
	});
}

function success(data) {
	if(data != undefined && data.success != 0) {
		status = 1;
	} else {
		status = -1;
	}
}

function error(data, t, m) {
	if(t == "timeout") {
		alert("TIMEOUT");
	} else {
		console.log("ERROR " + t + ": " + m);
	}
	status = data.status;
}

function getStatus() {
  return status;
}

function setStatus(uusi) {
	status = uusi;
}

function saveToken(data){
	localStorage.setItem('authtoken',data.authtoken);
}
function saveDL_id(data){
	localStorage.setItem('DL_id',data.DL_id);
}
function getToken(){
	return localStorage.getItem('authtoken');
}
function getDL_id(){
	return localStorage.getItem('DL_id');
}

function saveName(data){
	localStorage.setItem('name',data.name);
}
function getName(){
	return localStorage.getItem('name');
}
function saveStream(data){
	localStorage.setItem('stream',JSON.stringify(data));
}
function getSavedStream(){
	return JSON.parse(localStorage.getItem('stream'));
}
function saveImage(url){
	localStorage.setItem('image',url);
}
function getImage(){
	return localStorage.getItem('image');
}

function saveRelations(relations) {
	localStorage.setItem('relations', JSON.stringify(relations));
}

function getRelations() {
	var relations = localStorage.getItem('relations');

	if (relations !== "")
		return $.parseJSON(relations);
	else
		return null;
}

function getRelation(dlid) {
	var relations = getRelations();

	if (relations !== null) {
		for (var i=0; i<relations.length; ++i) {
			if (relations[i].dlid === dlid) {
				return relations[i];
			}
		}
	}
	return null;
}

function isRelated() {
	if (getRelation(getURLParameter("dlid")) !== null)
		return true;
	else
		return false;
}<commit_msg>rest.js:stä funktioita data.js:ään<commit_after>var restUrl =  "https://www.dliv.in/rest/";
var status = 0;

var result;
function rest(opts,url, success, error){
	status = 0;
	result="";
	$.ajax(
	{
		url: restUrl+url,
		dataType: "json",
		global: false,
		async: true,
		data: opts,
		success: success,
		error: error
	});
	return result;
}

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function addActivity(opts,success,error) {
	status = 0;
	$.ajax(
	{
		url: restUrl+"stream",
		type: "POST",
		global: false,
		async: true,
		dataType: 'JSON',
		data: opts,
		success: success,
		error: error
	});
}
function addCommentRest(opts,url, success,error) {
	status = 0;
	$.ajax(
	{
		url: restUrl+url,
		type: "POST",
		global: false,
		async: true,
		dataType: 'JSON',
		data: opts,
		success: success,
		error: error
	});
}

function success(data) {
	if(data != undefined && data.success != 0) {
		status = 1;
	} else {
		status = -1;
	}
}

function error(data, t, m) {
	if(t == "timeout") {
		alert("TIMEOUT");
	} else {
		console.log("ERROR " + t + ": " + m);
	}
	status = data.status;
}<|endoftext|>


<commit_before>/* global angular, buffer, console, Promise, StellarSdk */

/**
 * Executes a provided (promise-returning) function once per
 * array element, in sequence.
 *
 * @param callback              Function to call per element
 * @returns {Promise}           The resulting promise-chain
 */

Object.defineProperty(Array.prototype, 'forEachThen', {
	value: function (callback) {
		'use strict';

		return this.reduce(function (promise, item) {
			return promise.then(function () {
				return callback(item);
			});
		}, Promise.resolve());
	}
});

angular.module('app')
.factory('Signer', function ($q, Horizon, Keychain, Wallet) {
	'use strict';

	var Buffer = buffer.Buffer;

	function getOperationCategory(op) {
		var category = 1;
		if (op.type === 'setOptions') {
			if (op.masterWeight || op.lowThreshold || op.medThreshold || op.highThreshold || op.signer) {
				category = 2;
			}
		} else if (op.type === 'allowTrust') {
			category = 0;
		}
		return category;
	}

	function getSourceAccount(op, tx) {
		if (op.source) {
			return op.source;
		} else {
			return tx.source;
		}
	}

	function setAccountCategory(accounts, source, category) {
		if (!accounts[source]) {
			accounts[source] = {
				category: [0, 0, 0]
			};
		}
		accounts[source].category[category] = 1;
	}

	/**
	 * Returns an object with all the source accounts of a transaction,
	 * and their corresponding threshold categories
	 *
	 * @param tx
	 * @returns {{}}
	 */

	function getSourceAccounts(tx) {

		var accounts = {};
		tx.operations.forEach(function (op) {
			var category = getOperationCategory(op);
			var source = getSourceAccount(op, tx);
			setAccountCategory(accounts, source, category);
		});

		return accounts;
	}

	function hasEnoughSignatures(sourceAccounts) {
		for (var key in sourceAccounts) {
			if (sourceAccounts.hasOwnProperty(key)) {
				var account = sourceAccounts[key];
				if (account.sum < account.threshold) {
					return false;
				}
			}
		}

		return true;
	}

	/*
	// Returns the "signature base" of this transaction, which is the value
	// that, when hashed, should be signed to create a signature that
	// validators on the Stellar Network will accept.
	//
	// It is composed of a sha-256 network prefix followed by the xdr-encoded form
	// of this transaction.
	// @returns {Buffer}
	*/

	function signatureBase(tx, network) {
		return Buffer.concat([
			new StellarSdk.Network(network).networkId(),
			StellarSdk.xdr.EnvelopeType.envelopeTypeTx().toXDR(),
			tx.tx.toXDR()
		]);
	}

	function transactionHash(tx, network) {
		var base = signatureBase(tx, network);
		return StellarSdk.hash(base);
	}

	/*
	// Signs the transaction with the given {@link Keypair}.
	// @param {...Keypair} keypairs Keypairs of signers
	// @returns {void}
	*/

	function signTransaction(tx, txHash, keys) {
		var sig = keys.signDecorated(txHash);
		tx.signatures.push(sig);
	}

	function getAccountInfo(context) {

		var accounts = context.accounts;
		var sourceAccounts = Object.keys(accounts);
		var accountInfo = sourceAccounts.map(function (source) {
			if (source in Wallet.accounts) {
				return $q.when(Wallet.accounts[source]);
			} else {
				return context.horizon.accounts().accountId(source).call();
			}
		});

		return $q.all(accountInfo)
		.then(function (info) {
			info.forEach(function (i) {
				accounts[i.id].signers		= i.signers;
				accounts[i.id].thresholds	= i.thresholds;
			});
			return context;
		});
	}

	//
	//	calculate signature threshold for each source account
	//

	function getThresholds(context) {
		var accounts = context.accounts;
		var sourceAccounts = Object.keys(accounts);

		sourceAccounts.forEach(function (source) {
			var account = accounts[source];

			var thresholds = [
				account.thresholds.low_threshold  * account.category[0],
				account.thresholds.med_threshold  * account.category[1],
				account.thresholds.high_threshold * account.category[2]
			];

			var threshold = Math.max.apply(null, thresholds);
			if (threshold === 0) {
				threshold = 1;
			}

			account.threshold = threshold;
			account.sum = 0;
			delete account.category;
			delete account.thresholds;
		});

		console.log(accounts);
		return context;
	}

	//
	//	extract signer information into its own structure
	//

	function getSigners(context) {
		var accounts = context.accounts;
		var sourceAccounts = Object.keys(accounts);

		var signers = {};
		sourceAccounts.forEach(function (source) {
			var account = accounts[source];

			account.signers.forEach(function (signer) {
				if (signer.weight !== 0) {
					var value = {
						account:	source,
						weight:		signer.weight
					};

					if (signer.public_key in signers) {
						signers[signer.public_key].push(value);
					} else {
						signers[signer.public_key] = [value];
					}
				}
			});

			delete account.signers;
		});

		console.log(signers);
		context.signers = signers;
		return context;
	}

	//
	//	iterate the list of signers and sign for the keys we control
	//

	function signLocalKeys(context) {
		var accounts = context.accounts;
		var signers = context.signers;

		var localSigners = Object.keys(signers).filter(Keychain.isLocalSigner);
		var txHash = transactionHash(context.tx, context.network);

		return localSigners.forEachThen(function (signer) {
			return Keychain.signTransaction(signer, context.tx, txHash)
			.then(
				function () {
					var sources = signers[signer];
					sources.forEach(function (source) {
						accounts[source.account].sum += source.weight;
					});

					delete signers[signer];
				},
				function (err) {
					console.log(err);
				}
			);
		})
		.then(function () {
			console.log(context.tx);
			return context;
		});
	}

	function sign(context) {
		context.horizon  = Horizon.getServer(context.network);
		context.accounts = getSourceAccounts(context.tx);

		return $q.when(context)
		.then(getAccountInfo)
		.then(getThresholds)
		.then(getSigners)
		.then(signLocalKeys);
	}

	return {
		sign: sign,
		hasEnoughSignatures: hasEnoughSignatures,
		hasExternalSigners: function (context) {
			var signers = Object.keys(context.signers);
			var localSigners = signers.filter(Keychain.isLocalSigner);
			return (signers.length !== localSigners.length);
		}
	};
});
<commit_msg>Remove left-over function<commit_after>/* global angular, buffer, console, Promise, StellarSdk */

/**
 * Executes a provided (promise-returning) function once per
 * array element, in sequence.
 *
 * @param callback              Function to call per element
 * @returns {Promise}           The resulting promise-chain
 */

Object.defineProperty(Array.prototype, 'forEachThen', {
	value: function (callback) {
		'use strict';

		return this.reduce(function (promise, item) {
			return promise.then(function () {
				return callback(item);
			});
		}, Promise.resolve());
	}
});

angular.module('app')
.factory('Signer', function ($q, Horizon, Keychain, Wallet) {
	'use strict';

	var Buffer = buffer.Buffer;

	function getOperationCategory(op) {
		var category = 1;
		if (op.type === 'setOptions') {
			if (op.masterWeight || op.lowThreshold || op.medThreshold || op.highThreshold || op.signer) {
				category = 2;
			}
		} else if (op.type === 'allowTrust') {
			category = 0;
		}
		return category;
	}

	function getSourceAccount(op, tx) {
		if (op.source) {
			return op.source;
		} else {
			return tx.source;
		}
	}

	function setAccountCategory(accounts, source, category) {
		if (!accounts[source]) {
			accounts[source] = {
				category: [0, 0, 0]
			};
		}
		accounts[source].category[category] = 1;
	}

	/**
	 * Returns an object with all the source accounts of a transaction,
	 * and their corresponding threshold categories
	 *
	 * @param tx
	 * @returns {{}}
	 */

	function getSourceAccounts(tx) {

		var accounts = {};
		tx.operations.forEach(function (op) {
			var category = getOperationCategory(op);
			var source = getSourceAccount(op, tx);
			setAccountCategory(accounts, source, category);
		});

		return accounts;
	}

	function hasEnoughSignatures(sourceAccounts) {
		for (var key in sourceAccounts) {
			if (sourceAccounts.hasOwnProperty(key)) {
				var account = sourceAccounts[key];
				if (account.sum < account.threshold) {
					return false;
				}
			}
		}

		return true;
	}

	/*
	// Returns the "signature base" of this transaction, which is the value
	// that, when hashed, should be signed to create a signature that
	// validators on the Stellar Network will accept.
	//
	// It is composed of a sha-256 network prefix followed by the xdr-encoded form
	// of this transaction.
	// @returns {Buffer}
	*/

	function signatureBase(tx, network) {
		return Buffer.concat([
			new StellarSdk.Network(network).networkId(),
			StellarSdk.xdr.EnvelopeType.envelopeTypeTx().toXDR(),
			tx.tx.toXDR()
		]);
	}

	function transactionHash(tx, network) {
		var base = signatureBase(tx, network);
		return StellarSdk.hash(base);
	}

	function getAccountInfo(context) {

		var accounts = context.accounts;
		var sourceAccounts = Object.keys(accounts);
		var accountInfo = sourceAccounts.map(function (source) {
			if (source in Wallet.accounts) {
				return $q.when(Wallet.accounts[source]);
			} else {
				return context.horizon.accounts().accountId(source).call();
			}
		});

		return $q.all(accountInfo)
		.then(function (info) {
			info.forEach(function (i) {
				accounts[i.id].signers		= i.signers;
				accounts[i.id].thresholds	= i.thresholds;
			});
			return context;
		});
	}

	//
	//	calculate signature threshold for each source account
	//

	function getThresholds(context) {
		var accounts = context.accounts;
		var sourceAccounts = Object.keys(accounts);

		sourceAccounts.forEach(function (source) {
			var account = accounts[source];

			var thresholds = [
				account.thresholds.low_threshold  * account.category[0],
				account.thresholds.med_threshold  * account.category[1],
				account.thresholds.high_threshold * account.category[2]
			];

			var threshold = Math.max.apply(null, thresholds);
			if (threshold === 0) {
				threshold = 1;
			}

			account.threshold = threshold;
			account.sum = 0;
			delete account.category;
			delete account.thresholds;
		});

		console.log(accounts);
		return context;
	}

	//
	//	extract signer information into its own structure
	//

	function getSigners(context) {
		var accounts = context.accounts;
		var sourceAccounts = Object.keys(accounts);

		var signers = {};
		sourceAccounts.forEach(function (source) {
			var account = accounts[source];

			account.signers.forEach(function (signer) {
				if (signer.weight !== 0) {
					var value = {
						account:	source,
						weight:		signer.weight
					};

					if (signer.public_key in signers) {
						signers[signer.public_key].push(value);
					} else {
						signers[signer.public_key] = [value];
					}
				}
			});

			delete account.signers;
		});

		console.log(signers);
		context.signers = signers;
		return context;
	}

	//
	//	iterate the list of signers and sign for the keys we control
	//

	function signLocalKeys(context) {
		var accounts = context.accounts;
		var signers = context.signers;

		var localSigners = Object.keys(signers).filter(Keychain.isLocalSigner);
		var txHash = transactionHash(context.tx, context.network);

		return localSigners.forEachThen(function (signer) {
			return Keychain.signTransaction(signer, context.tx, txHash)
			.then(
				function () {
					var sources = signers[signer];
					sources.forEach(function (source) {
						accounts[source.account].sum += source.weight;
					});

					delete signers[signer];
				},
				function (err) {
					console.log(err);
				}
			);
		})
		.then(function () {
			console.log(context.tx);
			return context;
		});
	}

	function sign(context) {
		context.horizon  = Horizon.getServer(context.network);
		context.accounts = getSourceAccounts(context.tx);

		return $q.when(context)
		.then(getAccountInfo)
		.then(getThresholds)
		.then(getSigners)
		.then(signLocalKeys);
	}

	return {
		sign: sign,
		hasEnoughSignatures: hasEnoughSignatures,
		hasExternalSigners: function (context) {
			var signers = Object.keys(context.signers);
			var localSigners = signers.filter(Keychain.isLocalSigner);
			return (signers.length !== localSigners.length);
		}
	};
});
<|endoftext|>


<commit_before>/* global angular */
import {Chess} from '../../contract/Chess.sol';
angular.module('dappChess').factory('games', function (navigation, accounts, $rootScope, $route) {
  const games = {
    list: [],
    openGames: []
  };
  /*
   * Structure of games list:
   * [
   *  gameId: <string>,
   *  {
   *    self: {
   *      username: <string>,
   *      accountId: <string>,
   *      color: <string>
   *    },
   *    opponent: {
   *      username: <string>,
   *      accountId: <string>,
   *      color: <string>
   *    }
   *  }
   * ]
   */

  games.getGame = function (id) {
    return games.list.find(function (game) {
      return game.gameId === id;
    });
  };

  games.removeGame = function(id) {
    for(let i in games.list) {
      if(games.list[i].gameId === id) {
        games.list.splice(i, 1);
        break;
      }
    }
  };

  /**
   * Convert an array to a game object as seen in the contract with the given gameId.
   * @param gameId of the game
   * @param array containing the data
   * @returns object as seen in the contract
   */
  games.convertArrayToGame = function (gameId, array) {
    return {
      gameId: gameId,
      player1: array[0],
      player2: array[1],
      player1Alias: array[2],
      player2Alias: array[3],
      nextPlayer: array[4],
      playerWhite: array[5],
      winner: array[6],
      ended: array[7]
    };
  };

  /**
   * Add a game to the list, if there is no game with the same id.
   * @param contractGameObject An object with the structure of a Game in the contract

   *     { player1: "<address>", player2: "<address>", ... }
   * @returns the new created game or undefined, if the gameId is already in the list
   */
  games.add = function (contractGameObject) {
    if (typeof games.getGame(contractGameObject.gameId) !== 'undefined') {
      return;
    }
    let game = { gameId: contractGameObject.gameId };

    if (accounts.availableAccounts.indexOf(contractGameObject.player2) !== -1) {
      game.self = {
        username: contractGameObject.player2Alias,
        accountId: contractGameObject.player2,
        color: (contractGameObject.playerWhite === contractGameObject.player2 ? 'white' : 'black')
      };
      game.opponent = {
        username: contractGameObject.player1Alias,
        accountId: contractGameObject.player1,
        color: (contractGameObject.playerWhite === contractGameObject.player1 ? 'white' : 'black')
      };
    } else {
      game.self = {
        username: contractGameObject.player1Alias,
        accountId: contractGameObject.player1,
        color: (contractGameObject.playerWhite === contractGameObject.player1 ? 'white' : 'black')
      };
      if (typeof contractGameObject.player2 !== 'undefined' &&
          contractGameObject.player2 !== '0x0000000000000000000000000000000000000000') {
        game.opponent = {
          username: contractGameObject.player2Alias,
          accountId: contractGameObject.player2,
          color: (contractGameObject.playerWhite === contractGameObject.player2 ? 'white' : 'black')
        };
      }
    }
    if(typeof(contractGameObject.winner) !== 'undefined' &&
      contractGameObject.winner !== '0x0000000000000000000000000000000000000000') {
      if(game.self.accountId === contractGameObject.winner) {
        game.winner = 'self';
      }
      else if(game.opponent.accountId === contractGameObject.winner) {
        game.winner = 'opponent';
      }
    }

    game.ended = contractGameObject.ended;

    games.list.push(game);

    return game;
  };

  games.setWinner = function(gameId, winnerAccountId) {
    for(let i in games.list) {
      if(games.list[i].gameId === gameId) {
        if(games.list[i].self.accountId === winnerAccountId) {
          games.list[i].winner = 'self';
          games.list[i].ended = true;

          console.log(accounts.availableAccounts, winnerAccountId,
                      accounts.availableAccounts.indexOf(winnerAccountId) !== -1);
          if (accounts.availableAccounts.indexOf(winnerAccountId) !== -1) {
            $rootScope.$broadcast('message',
              'You have won the game against ' + games.list[i].opponent.username,
              'message', 'playgame');
          }
        }
        else if(games.list[i].opponent.accountId === winnerAccountId) {
          games.list[i].winner = 'opponent';
          games.list[i].ended = true;

          console.log(accounts.availableAccounts, games.list[i].self.accountId,
                      accounts.availableAccounts.indexOf(games.list[i].self.accountId) !== -1);
          if (accounts.availableAccounts.indexOf(games.list[i].self.accountId) !== -1) {
            $rootScope.$broadcast('message',
              'You have lost the game against ' + games.list[i].opponent.username,
              'message', 'playgame');
          }
        }
        else {
          console.log('error: could not find winner ' + winnerAccountId,
            'self: ' + games.list[i].self.accountId,
            'opponent: ' + games.list[i].opponent.accountId
          );
        }

        $rootScope.$apply();

        break;
      }
    }
  };

  games.eventGameInitialized = function (err, data) {
    console.log('eventGameInitialized', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
        'Your game could not be created, the following error occured: ' + err,
        'error', 'startgame');*/
    } else {
      let game = games.add(data.args);
      games.openGames.push(game.gameId);

      if (accounts.availableAccounts.indexOf(game.self.accountId) !== -1) {
        $rootScope.$broadcast('message',
          'Your game has successfully been created and has the id ' + game.gameId,
          'success', 'startgame');
      }

      $rootScope.$apply();
    }
  };

  games.eventGameJoined = function (err, data) {
    console.log('eventGameJoined', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
        'It was not possible to join the game, the following error occured: ' + err,
        'error', 'joingame');*/
    } else {
      let gameId = data.args.gameId;
      let p1accountId = data.args.player1;
      let p1username = data.args.player1Alias;
      let p1color = (data.args.playerWhite === data.args.player1 ? 'white' : 'black');
      let p2accountId = data.args.player2;
      let p2username = data.args.player2Alias;
      let p2color = (data.args.playerWhite === data.args.player2 ? 'white' : 'black');

      let game = games.getGame(gameId);
      if (typeof game === 'undefined') {
        game = games.add(data.args);
      } else {
        // remove game from openGames
        let gameIndex = games.openGames.indexOf(gameId);
        games.openGames.splice(gameIndex, 1);
        if (accounts.availableAccounts.indexOf(p2accountId) !== -1) {
          game.self = {
            username: p2username,
            accountId: p2accountId,
            color: p2color
          };
          game.opponent = {
            username: p1username,
            accountId: p1accountId,
            color: p1color
          };
        } else {
          game.self = {
            username: p1username,
            accountId: p1accountId,
            color: p1color
          };
          game.opponent = {
            username: p2username,
            accountId: p2accountId,
            color: p2color
          };
        }
      }

      if (accounts.availableAccounts.indexOf(game.self.accountId) !== -1) {
        $rootScope.$broadcast('message', 'Your game against ' +
                game.opponent.username.replace(/<(?:.|\n)*?>/gm, '') +
                ' has started',
            'success', 'joingame');

        if($route.current.activePage === navigation.joinGamePage) {
          navigation.goto(navigation.playGamePage, gameId);
        }
        else {
          $rootScope.$apply();
        }
      }
    }
  };

  games.eventGameStateChanged = function (err, data) {
    console.log('eventGameStateChanged', err, data);
  };

  games.eventMove = function (err, data) {
    console.log('eventMove', err, data);
  };

  games.eventGameEnded = function(err, data) {
    console.log('eventGameEnded', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
        'The surrender could not be saved, the following error occurred: ' + err,
        'error', 'playgame');*/
    } else {
      games.setWinner(data.args.gameId, data.args.winner);
    }
  };

  games.eventGameClosed = function(err, data) {
    console.log('eventGameClosed', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
       'The surrender could not be saved, the following error occurred: ' + err,
       'error', 'playgame');*/
    } else {
      let game = games.getGame(data.args.gameId);

      if(game) {
        // If the player closed his own game
        if (accounts.availableAccounts.indexOf(data.args.player) !== -1) {
          navigation.goto(navigation.welcomePage);

          $rootScope.$broadcast('message',
            'Your game with the id ' + data.args.gameId + ' was closed',
            'success', 'playgame');

          games.removeGame(data.args.gameId);

          $rootScope.$apply();
        }
        else {
          let openGameIndex = games.openGames.indexOf(game.gameId);

          // If this was an open game of another player
          if(openGameIndex !== -1) {
            games.removeGame(data.args.gameId);
            games.openGames.splice(openGameIndex, 1);

            $rootScope.$apply();
          }
        }
      }
    }
  };

  // Fetch games of player
  for (let accountId of accounts.availableAccounts) {
    for (let currentGameId of Chess.getGamesOfPlayer(accountId)) {
      // Check if the game already exists in the games list
      let game = games.getGame(currentGameId);
      if (typeof game === 'undefined') {
        games.add(games.convertArrayToGame(currentGameId, Chess.games(currentGameId)));
      }
    }
  }

  // Fetch open games
  const end = '0x656e640000000000000000000000000000000000000000000000000000000000';
  for (let currentGameId = Chess.head();
       currentGameId !== end;
       currentGameId = Chess.openGameIds(currentGameId)) {
    // Check if the open game already exists in the games list
    let game = games.getGame(currentGameId);
    if (typeof game === 'undefined') {
      games.add(games.convertArrayToGame(currentGameId, Chess.games(currentGameId)));
    }
    games.openGames.push(currentGameId);
  }

  // Event listeners
  Chess.GameInitialized({}, games.eventGameInitialized);
  Chess.GameJoined({}, games.eventGameJoined);
  Chess.GameStateChanged({}, games.eventGameStateChanged);
  Chess.Move({}, games.eventMove);
  Chess.GameEnded({}, games.eventGameEnded);
  Chess.GameClosed({}, games.eventGameClosed);

  return games;
}).filter('ownGames', function (accounts) {
  return function (games) {
    return games.filter(function (game) {
      return accounts.availableAccounts.indexOf(game.self.accountId) !== -1;
    });
  };
}).filter('othersOpenGames', function (accounts) {
  return function (games, openGames) {
    if (typeof games !== 'undefined') {
      return games.filter(function (game) {
        return accounts.availableAccounts.indexOf(game.self.accountId) === -1;
      }).filter(function(game) {
        return openGames.indexOf(game.gameId) !== -1;
      });
    }
  };
});
<commit_msg>Claim ether when game is won<commit_after>/* global angular */
import {web3, Chess} from '../../contract/Chess.sol';
angular.module('dappChess').factory('games', function (navigation, accounts, $rootScope, $route) {
  const games = {
    list: [],
    openGames: []
  };
  /*
   * Structure of games list:
   * [
   *  gameId: <string>,
   *  {
   *    self: {
   *      username: <string>,
   *      accountId: <string>,
   *      color: <string>
   *    },
   *    opponent: {
   *      username: <string>,
   *      accountId: <string>,
   *      color: <string>
   *    }
   *  },
   *  ended: <boolean>,
   *  value: <number>
   * ]
   */

  games.getGame = function (id) {
    return games.list.find(function (game) {
      return game.gameId === id;
    });
  };

  games.removeGame = function(id) {
    for(let i in games.list) {
      if(games.list[i].gameId === id) {
        games.list.splice(i, 1);
        break;
      }
    }
  };

  /**
   * Convert an array to a game object as seen in the contract with the given gameId.
   * @param gameId of the game
   * @param array containing the data
   * @returns object as seen in the contract
   */
  games.convertArrayToGame = function (gameId, array) {
    return {
      gameId: gameId,
      player1: array[0],
      player2: array[1],
      player1Alias: array[2],
      player2Alias: array[3],
      nextPlayer: array[4],
      playerWhite: array[5],
      winner: array[6],
      ended: array[7],
      value: array[8]
    };
  };

  /**
   * Add a game to the list, if there is no game with the same id.
   * @param contractGameObject An object with the structure of a Game in the contract

   *     { player1: "<address>", player2: "<address>", ... }
   * @returns the new created game or undefined, if the gameId is already in the list
   */
  games.add = function (contractGameObject) {
    if (typeof games.getGame(contractGameObject.gameId) !== 'undefined') {
      return;
    }
    let game = {gameId: contractGameObject.gameId};

    if (accounts.availableAccounts.indexOf(contractGameObject.player2) !== -1) {
      game.self = {
        username: contractGameObject.player2Alias,
        accountId: contractGameObject.player2,
        color: (contractGameObject.playerWhite === contractGameObject.player2 ? 'white' : 'black')
      };
      game.opponent = {
        username: contractGameObject.player1Alias,
        accountId: contractGameObject.player1,
        color: (contractGameObject.playerWhite === contractGameObject.player1 ? 'white' : 'black')
      };
    } else {
      game.self = {
        username: contractGameObject.player1Alias,
        accountId: contractGameObject.player1,
        color: (contractGameObject.playerWhite === contractGameObject.player1 ? 'white' : 'black')
      };
      if (typeof contractGameObject.player2 !== 'undefined' &&
        contractGameObject.player2 !== '0x0000000000000000000000000000000000000000') {
        game.opponent = {
          username: contractGameObject.player2Alias,
          accountId: contractGameObject.player2,
          color: (contractGameObject.playerWhite === contractGameObject.player2 ? 'white' : 'black')
        };
      }
    }
    if (typeof(contractGameObject.winner) !== 'undefined' &&
      contractGameObject.winner !== '0x0000000000000000000000000000000000000000') {
      if (game.self.accountId === contractGameObject.winner) {
        game.winner = 'self';
      }
      else if (game.opponent.accountId === contractGameObject.winner) {
        game.winner = 'opponent';
      }
    }

    if (contractGameObject.ended) {
      game.ended = true;
    }
    else {
      game.ended = false;
    }
    game.value = web3.fromWei(contractGameObject.value, 'ether').toDigits().toString();

    console.log('game added', game);

    games.list.push(game);

    return game;
  };

  games.setWinner = function(gameId, winnerAccountId) {
    for(let i in games.list) {
      if(games.list[i].gameId === gameId) {
        // Perform actions if game is won
        if(games.list[i].self.accountId === winnerAccountId) {
          games.list[i].winner = 'self';
          games.list[i].ended = true;

          console.log(accounts.availableAccounts, winnerAccountId,
                      accounts.availableAccounts.indexOf(winnerAccountId) !== -1);
          if (accounts.availableAccounts.indexOf(winnerAccountId) !== -1) {
            $rootScope.$broadcast('message',
              'You have won the game against ' + games.list[i].opponent.username,
              'message', 'playgame');

            // When the player did win the game, claim the ether pot
            $rootScope.$broadcast('message',
              'Claiming your won ether in the game against ' + games.list[i].opponent.username,
              'message', 'claimpot');

            try {
              console.log('Trying to claim ether', gameId, {from: winnerAccountId});
              Chess.claimWin(gameId, {from: winnerAccountId});
              $rootScope.$broadcast('message',
                'Your won ether with the amount of ' +
                games.list[i].value +
                ' has been added to your account',
                'success', 'claimpot');
            }
            catch(e) {
              $rootScope.$broadcast('message',
                'Could not claim your won ether',
                'error', 'claimpot');
            }
          }
        }
        else if(games.list[i].opponent.accountId === winnerAccountId) {
          games.list[i].winner = 'opponent';
          games.list[i].ended = true;

          console.log(accounts.availableAccounts, games.list[i].self.accountId,
                      accounts.availableAccounts.indexOf(games.list[i].self.accountId) !== -1);
          if (accounts.availableAccounts.indexOf(games.list[i].self.accountId) !== -1) {
            $rootScope.$broadcast('message',
              'You have lost the game against ' + games.list[i].opponent.username,
              'message', 'playgame');
          }
        }
        else {
          console.log('error: could not find winner ' + winnerAccountId,
            'self: ' + games.list[i].self.accountId,
            'opponent: ' + games.list[i].opponent.accountId
          );
        }

        $rootScope.$apply();

        break;
      }
    }
  };

  games.eventGameInitialized = function (err, data) {
    console.log('eventGameInitialized', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
        'Your game could not be created, the following error occured: ' + err,
        'error', 'startgame');*/
    } else {
      let game = games.add(data.args);
      games.openGames.push(game.gameId);

      if (accounts.availableAccounts.indexOf(game.self.accountId) !== -1) {
        $rootScope.$broadcast('message',
          'Your game has successfully been created and has the id ' + game.gameId,
          'success', 'startgame');
      }

      $rootScope.$apply();
    }
  };

  games.eventGameJoined = function (err, data) {
    console.log('eventGameJoined', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
        'It was not possible to join the game, the following error occured: ' + err,
        'error', 'joingame');*/
    } else {
      let gameId = data.args.gameId;
      let p1accountId = data.args.player1;
      let p1username = data.args.player1Alias;
      let p1color = (data.args.playerWhite === data.args.player1 ? 'white' : 'black');
      let p2accountId = data.args.player2;
      let p2username = data.args.player2Alias;
      let p2color = (data.args.playerWhite === data.args.player2 ? 'white' : 'black');

      let game = games.getGame(gameId);
      if (typeof game === 'undefined') {
        game = games.add(data.args);
      } else {
        // remove game from openGames
        let gameIndex = games.openGames.indexOf(gameId);
        games.openGames.splice(gameIndex, 1);
        if (accounts.availableAccounts.indexOf(p2accountId) !== -1) {
          game.self = {
            username: p2username,
            accountId: p2accountId,
            color: p2color
          };
          game.opponent = {
            username: p1username,
            accountId: p1accountId,
            color: p1color
          };
        } else {
          game.self = {
            username: p1username,
            accountId: p1accountId,
            color: p1color
          };
          game.opponent = {
            username: p2username,
            accountId: p2accountId,
            color: p2color
          };
        }
        game.value = web3.fromWei(data.args.value, 'ether').toDigits().toString();
      }

      if (accounts.availableAccounts.indexOf(game.self.accountId) !== -1) {
        $rootScope.$broadcast('message', 'Your game against ' +
                game.opponent.username.replace(/<(?:.|\n)*?>/gm, '') +
                ' has started',
            'success', 'joingame');

        if($route.current.activePage === navigation.joinGamePage) {
          navigation.goto(navigation.playGamePage, gameId);
        }
        else {
          $rootScope.$apply();
        }
      }
    }
  };

  games.eventGameStateChanged = function (err, data) {
    console.log('eventGameStateChanged', err, data);
  };

  games.eventMove = function (err, data) {
    console.log('eventMove', err, data);
  };

  games.eventGameEnded = function(err, data) {
    console.log('eventGameEnded', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
        'The surrender could not be saved, the following error occurred: ' + err,
        'error', 'playgame');*/
    } else {
      games.setWinner(data.args.gameId, data.args.winner);
    }
  };

  games.eventGameClosed = function(err, data) {
    console.log('eventGameClosed', err, data);
    if (err) {
      console.log('error occured', err);
      /*$rootScope.$broadcast('message',
       'The surrender could not be saved, the following error occurred: ' + err,
       'error', 'playgame');*/
    } else {
      let game = games.getGame(data.args.gameId);

      if(game) {
        // If the player closed his own game
        if (accounts.availableAccounts.indexOf(data.args.player) !== -1) {
          navigation.goto(navigation.welcomePage);

          $rootScope.$broadcast('message',
            'Your game with the id ' + data.args.gameId + ' was closed',
            'success', 'playgame');

          games.removeGame(data.args.gameId);

          $rootScope.$apply();
        }
        else {
          let openGameIndex = games.openGames.indexOf(game.gameId);

          // If this was an open game of another player
          if(openGameIndex !== -1) {
            games.removeGame(data.args.gameId);
            games.openGames.splice(openGameIndex, 1);

            $rootScope.$apply();
          }
        }
      }
    }
  };

  // Fetch games of player
  for (let accountId of accounts.availableAccounts) {
    for (let currentGameId of Chess.getGamesOfPlayer(accountId)) {
      // Check if the game already exists in the games list
      let game = games.getGame(currentGameId);
      if (typeof game === 'undefined') {
        games.add(games.convertArrayToGame(currentGameId, Chess.games(currentGameId)));
      }
    }
  }

  // Fetch open games
  const end = '0x656e640000000000000000000000000000000000000000000000000000000000';
  for (let currentGameId = Chess.head();
       currentGameId !== end;
       currentGameId = Chess.openGameIds(currentGameId)) {
    // Check if the open game already exists in the games list
    let game = games.getGame(currentGameId);
    if (typeof game === 'undefined') {
      games.add(games.convertArrayToGame(currentGameId, Chess.games(currentGameId)));
    }
    games.openGames.push(currentGameId);
  }

  // Event listeners
  Chess.GameInitialized({}, games.eventGameInitialized);
  Chess.GameJoined({}, games.eventGameJoined);
  Chess.GameStateChanged({}, games.eventGameStateChanged);
  Chess.Move({}, games.eventMove);
  Chess.GameEnded({}, games.eventGameEnded);
  Chess.GameClosed({}, games.eventGameClosed);

  return games;
}).filter('ownGames', function (accounts) {
  return function (games) {
    return games.filter(function (game) {
      return accounts.availableAccounts.indexOf(game.self.accountId) !== -1;
    });
  };
}).filter('othersOpenGames', function (accounts) {
  return function (games, openGames) {
    if (typeof games !== 'undefined') {
      return games.filter(function (game) {
        return accounts.availableAccounts.indexOf(game.self.accountId) === -1;
      }).filter(function(game) {
        return openGames.indexOf(game.gameId) !== -1;
      });
    }
  };
});
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs'),
    path = require('path');

var baseDirectory = path.join(__dirname, '..', '..');
var relativeMigrationDirectory = path.join('db', 'migrations');
var absoluteMigrationDirectory = path.join(baseDirectory, relativeMigrationDirectory);

function padNumeral(numeral) {
    return Array(7 - numeral.toString().length).join('0') + numeral;
};

function makeNameFilename(migrationName) {
	return migrationName.replace(/\s+/g, '-');
};

exports.up = function(migrationName) {
};

exports.down = function(migrationName) {
};

exports.create = function(migrationName) {
    var migrationTemplate = [
        '"use strict"',
        '',
        'exports.up = function(mongoose, next) {',
        '    next();',
        '}',
        '',
        'exports.down = function(mongoose, next) {',
        '    next();',
        '}',
        ''
    ].join('\n');

    try {
        fs.mkdirSync(absoluteMigrationDirectory, parseInt('0775', 8));
    } catch (err) {
        // ignore error creating directory
    }

	var existingMigrationOrdinals = fs.readdirSync(absoluteMigrationDirectory).map(function(filename) {
        return parseInt(filename.match(/^(\d+)/)[1], 10);
    }).sort(function(a, b) {
        return a - b;
	});

	var nextOrdinal = (existingMigrationOrdinals.pop() || 0) + 1;
    var fileName = padNumeral(nextOrdinal) + "-" + makeNameFilename(migrationName) + ".js";
	var absoluteFileName = path.join(absoluteMigrationDirectory, fileName);
	fs.writeFileSync(absoluteFileName, migrationTemplate, {mode: parseInt('0664', 8)});
	console.log("New migration created: " + path.join(relativeMigrationDirectory, fileName));
};

<commit_msg>improve output for adding new migrationD<commit_after>"use strict";

var fs = require('fs'),
    path = require('path');

var baseDirectory = path.join(__dirname, '..', '..');
var relativeMigrationDirectory = path.join('db', 'migrations');
var absoluteMigrationDirectory = path.join(baseDirectory, relativeMigrationDirectory);

function padNumeral(numeral) {
    return Array(7 - numeral.toString().length).join('0') + numeral;
};

function makeNameFilename(migrationName) {
	return migrationName.replace(/\s+/g, '-');
};

exports.up = function(migrationName) {
};

exports.down = function(migrationName) {
};

exports.create = function(migrationName) {
    var migrationTemplate = [
        '"use strict"',
        '',
        'exports.up = function(mongoose, next) {',
        '    next();',
        '}',
        '',
        'exports.down = function(mongoose, next) {',
        '    next();',
        '}',
        ''
    ].join('\n');

    try {
        fs.mkdirSync(absoluteMigrationDirectory, parseInt('0775', 8));
    } catch (err) {
        // ignore error creating directory
    }

	var existingMigrationOrdinals = fs.readdirSync(absoluteMigrationDirectory).map(function(filename) {
        return parseInt(filename.match(/^(\d+)/)[1], 10);
    }).sort(function(a, b) {
        return a - b;
	});

	var nextOrdinal = (existingMigrationOrdinals.pop() || 0) + 1;
    var fileName = padNumeral(nextOrdinal) + "-" + makeNameFilename(migrationName) + ".js";
	var absoluteFileName = path.join(absoluteMigrationDirectory, fileName);
	fs.writeFileSync(absoluteFileName, migrationTemplate, {mode: parseInt('0664', 8)});
	console.log("  Created Migration '" + path.join(relativeMigrationDirectory, fileName)); + "'";
};

<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Bio Schema
 */
var BioSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Bio name',
		trim: true
	},
    title: {
        type: String,
        default: '',
        required: 'Please fill Title name',
        trim: true
    },
	created: {
		type: Date,
		default: Date.now
	},
    number: {
        type: Number,
        required:true
    },
    user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
    //don't know if this should be media or photo or what
    //possibly later make this an array
    medium: {
        type: Schema.ObjectId,
        ref: 'Medium'
    }
});

var Bio = mongoose.model('Bio', BioSchema);

////init server data

//clear first
Bio.remove(function(err, bio){

});

var bios = require('./waveExports.json');
for(var i = 0; i < bios.length; i++){
    bios[i].photo = 'modules/bios/img/' + bios[i].photo;
    var bio = new Bio(bios[i]);
    bio.save();
}<commit_msg>stop autopopulation<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Bio Schema
 */
var BioSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Bio name',
		trim: true
	},
    title: {
        type: String,
        default: '',
        required: 'Please fill Title name',
        trim: true
    },
	created: {
		type: Date,
		default: Date.now
	},
    number: {
        type: Number,
        required:true
    },
    user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
    //don't know if this should be media or photo or what
    //possibly later make this an array
    medium: {
        type: Schema.ObjectId,
        ref: 'Medium'
    }
});

var Bio = mongoose.model('Bio', BioSchema);

////init server data

//clear first
//Bio.remove(function(err, bio){
//
//});
//
//var bios = require('./waveExports.json');
//for(var i = 0; i < bios.length; i++){
//    bios[i].photo = 'modules/bios/img/' + bios[i].photo;
//    var bio = new Bio(bios[i]);
//    bio.save();
//}<|endoftext|>


<commit_before>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var Objectid = mongoose.Schema.Types.ObjectId;

var MembershipSchema   = new Schema({
	name: String,
	space_credits_per_month: Number,
	stuff_credits_per_month: Number,
	// bandwidth_per_month: Number,
	description: String,
	cost: Number,
	cost_period: String,
	max_members: Number,
	cost_extra_member: Number,
	space_credits_per_month_extra_member: Number,
	stuff_credits_per_month_extra_member: Number,
	// bandwidth_per_month_extra_member: Number,
	gigs: Number,
	business_address: Boolean,
	hotdesk: Boolean,
	boardroom_access: Boolean,
	free_printing: Boolean,
	hotdesk_discount: Number,
	boardroom_discount: Number,
	discount_multiplier: { type: Number, default: 1 },
	special: Boolean,
	sage: mongoose.Schema.Types.Mixed,
	datatill_product: Number,
	_owner_id: Objectid,
	_deleted: { type: Boolean, default: false, index: true },
});

MembershipSchema.set("_perms", {
	admin: "crud",
	owner: "r",
	user: "r",
	all: "r"
});

module.exports = mongoose.model('Membership', MembershipSchema);<commit_msg>Sage analytics in mt<commit_after>var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var Objectid = mongoose.Schema.Types.ObjectId;
var Sageanalysiscategory = require("./sageanalysiscategory_model");

var MembershipSchema   = new Schema({
	name: String,
	space_credits_per_month: Number,
	stuff_credits_per_month: Number,
	// bandwidth_per_month: Number,
	description: String,
	cost: Number,
	cost_period: String,
	max_members: Number,
	cost_extra_member: Number,
	space_credits_per_month_extra_member: Number,
	stuff_credits_per_month_extra_member: Number,
	sage_analytics_categories: mongoose.Schema.Types.Mixed,
	// bandwidth_per_month_extra_member: Number,
	gigs: Number,
	business_address: Boolean,
	hotdesk: Boolean,
	boardroom_access: Boolean,
	free_printing: Boolean,
	hotdesk_discount: Number,
	boardroom_discount: Number,
	discount_multiplier: { type: Number, default: 1 },
	special: Boolean,
	sage: mongoose.Schema.Types.Mixed,
	datatill_product: Number,
	_owner_id: Objectid,
	_deleted: { type: Boolean, default: false, index: true },
});

MembershipSchema.set("_perms", {
	admin: "crud",
	owner: "r",
	user: "r",
	all: "r"
});

module.exports = mongoose.model('Membership', MembershipSchema);<|endoftext|>


<commit_before>var vm = require('vm'),
    _ = require('underscore'),
    AssetGraph = require('../AssetGraph'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs,
    bootstrapper = require('../bootstrapper'),
    i18nTools = require('../i18nTools');

module.exports = function (queryObj, environment, removeAfter) {
    if (!environment) {
        throw new Error("transforms.runJavaScriptConditionalBlocks: no 'environment' option provided");
    }
    return function runJavaScriptConditionalBlocks(assetGraph) {
        assetGraph.findAssets(_.extend({type: 'Html'}, queryObj)).forEach(function (htmlAsset) {
            var contextProperties = {console: console};
            contextProperties[environment] = true;
            var context = bootstrapper.createContext(htmlAsset, assetGraph, contextProperties);

            assetGraph.collectAssetsPostOrder(htmlAsset, {type: ['HtmlScript', 'HtmlRequireJsMain', 'JavaScriptAmdRequire', 'JavaScriptAmdDefine', 'JavaScriptShimRequire', 'JavaScriptRequireJsCommonJsCompatibilityRequire', 'JavaScriptInclude']}).filter(function (asset) {
                return asset.isLoaded && asset.type === 'JavaScript';
            }).forEach(function (javaScript) {
                // Loop through top-level statements:
                var topLevelStatements = javaScript.parseTree.body;
                for (var i = 0 ; i < topLevelStatements.length ; i += 1) {
                    var node = topLevelStatements[i];
                    if (node instanceof uglifyJs.AST_If &&
                        ((node.condition instanceof uglifyJs.AST_SymbolRef && node.condition.name === environment) ||
                         (node.condition instanceof uglifyJs.AST_Dot && node.condition.property === environment &&
                          node.condition.expression instanceof uglifyJs.AST_SymbolRef &&
                          node.condition.expression.name === 'window'))) {

                        var fileName = javaScript.url || assetGraph.findRelations({to: javaScript})[0].baseAsset.url;
                        new vm.Script(node.body.print_to_string(), fileName).runInContext(context);
                        if (removeAfter) {
                            javaScript.parseTree.body.splice(i, 1);
                            i -= 1;
                        }
                    }
                }
            });
        });
    };
};
<commit_msg>lib/transforms/runJavaScriptConditionalBlocks.js: fix jshint errors<commit_after>var vm = require('vm'),
    _ = require('underscore'),
    AssetGraph = require('../AssetGraph'),
    uglifyJs = AssetGraph.JavaScript.uglifyJs,
    bootstrapper = require('../bootstrapper');

module.exports = function (queryObj, environment, removeAfter) {
    if (!environment) {
        throw new Error('transforms.runJavaScriptConditionalBlocks: no \'environment\' option provided');
    }
    return function runJavaScriptConditionalBlocks(assetGraph) {
        assetGraph.findAssets(_.extend({type: 'Html'}, queryObj)).forEach(function (htmlAsset) {
            var contextProperties = {console: console};
            contextProperties[environment] = true;
            var context = bootstrapper.createContext(htmlAsset, assetGraph, contextProperties);

            assetGraph.collectAssetsPostOrder(htmlAsset, {type: ['HtmlScript', 'HtmlRequireJsMain', 'JavaScriptAmdRequire', 'JavaScriptAmdDefine', 'JavaScriptShimRequire', 'JavaScriptRequireJsCommonJsCompatibilityRequire', 'JavaScriptInclude']}).filter(function (asset) {
                return asset.isLoaded && asset.type === 'JavaScript';
            }).forEach(function (javaScript) {
                // Loop through top-level statements:
                var topLevelStatements = javaScript.parseTree.body;
                for (var i = 0 ; i < topLevelStatements.length ; i += 1) {
                    var node = topLevelStatements[i];
                    if (node instanceof uglifyJs.AST_If &&
                        ((node.condition instanceof uglifyJs.AST_SymbolRef && node.condition.name === environment) ||
                         (node.condition instanceof uglifyJs.AST_Dot && node.condition.property === environment &&
                          node.condition.expression instanceof uglifyJs.AST_SymbolRef &&
                          node.condition.expression.name === 'window'))) {

                        var fileName = javaScript.url || assetGraph.findRelations({to: javaScript})[0].baseAsset.url;
                        new vm.Script(node.body.print_to_string(), fileName).runInContext(context);
                        if (removeAfter) {
                            javaScript.parseTree.body.splice(i, 1);
                            i -= 1;
                        }
                    }
                }
            });
        });
    };
};
<|endoftext|>