<commit_before>import Joi from 'joi';
import Boom from 'boom';
import pick from 'lodash/pick';
import Router from './Router';
import { toBSON, idValidator, idToQuery } from '../libs/mongo-helpers';
import { route } from '../libs/decorators';

class MongoResourceRouter extends Router {
  static applyContextToRoute = (routeId, generateContext) => (request, reply) => {
    const context = generateContext(request);

    switch (routeId) {
      case 'count':
      case 'deleteOne':
      case 'deleteOneById':
      case 'findById':
      case 'findOne':
        Object.assign(request.pre.query, context);
        break;
      case 'createOne':
        Object.assign(request.pre.payload, context);
        break;
      case 'findMany':
        Object.assign(request.pre.queryParams.query, context);
        break;
      case 'replaceOne':
      case 'updateOne':
        Object.assign(request.pre.query, context);
        Object.assign(request.pre.payload, context);
        break;
      default:
    }

    reply();
  };

  constructor(Repository, config) {
    super(
      Joi.attempt(config, Joi.object().keys({
        entitySchema: Joi.object(),
      }).unknown()),
    );

    this.Repository = Repository;

    this.addRoute('deleteOneById', {
      path: '/{id}',
      method: 'DELETE',
      handler: this.deleteOne,
      config: {
        validate: {
          params: {
            id: idValidator,
          },
        },
        description: 'Delete an entity by id',
        pre: [{
          method: (request, reply) => reply(idToQuery(request.params.id)),
          assign: 'query',
        }],
      },
    });

    this.routes.createOne.config.validate.payload = this.config.entitySchema;
    this.routes.replaceOne.config.validate.payload = this.config.entitySchema;
  }

  @route({
    path: '/count',
    method: 'GET',
    config: {
      validate: {
        query: {
          query: Joi.object().default({}),
        },
      },
      description: 'Count entities',
      pre: [{
        method: (request, reply) => reply(toBSON(request.query.query)),
        assign: 'query',
      }],
    },
  })
  count(request) {
    const { query } = request.pre;
    return this.Repository.count({ query });
  }

  @route({
    path: '/',
    method: 'POST',
    config: {
      validate: {
      },
      description: 'Create a new entity',
      pre: [{
        method: (request, reply) => reply(toBSON(request.payload)),
        assign: 'payload',
      }],
    },
  })
  createOne(request) {
    const { payload } = request.pre;
    return this.Repository.createOne(payload);
  }

  @route({
    path: '/deleteOne',
    method: 'DELETE',
    config: {
      validate: {
        payload: {
          query: Joi.object().required(),
        },
      },
      description: 'Delete an entity',
      pre: [{
        method: (request, reply) => reply(toBSON(request.query.query)),
        assign: 'query',
      }],
    },
  })
  deleteOne(request) {
    const { query } = request.pre;
    return this.Repository.deleteOne({ query });
  }

  @route({
    path: '/{id}',
    method: 'GET',
    config: {
      validate: {
        params: {
          id: idValidator,
        },
      },
      description: 'Find an entity by id',
      pre: [{
        method: (request, reply) => reply(idToQuery(request.params.id)),
        assign: 'query',
      }],
    },
  })
  async findById(request) {
    const { query } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound(`Unable to find entity with id ${request.params.id}`);
    }

    return entity;
  }

  @route({
    path: '/',
    method: 'GET',
    config: {
      validate: {
        query: {
          query: Joi.object().default({}),
          offset: Joi.number(),
          limit: Joi.number(),
          orderBy: Joi.object().default({}),
          fields: Joi.object().default({}),
        },
      },
      description: 'Find entities',
      pre: [{
        method: (request, reply) => reply(toBSON(request.query.query)),
        assign: 'query',
      }, {
        method: (request, reply) => {
          const params = pick(request.query, ['fields', 'orderBy']);
          params.query = request.pre.query;

          if (request.query.offset !== undefined) {
            params.skip = parseInt(request.query.offset, 10);
          }

          if (request.query.limit !== undefined) {
            params.limit = parseInt(request.query.limit, 10);
          }

          reply(params);
        },
        assign: 'queryParams',
      }],
    },
  })
  findMany(request) {
    const { queryParams } = request.pre;
    return this.Repository.findMany(queryParams).then(c => c.toArray());
  }

  @route({
    path: '/findOne',
    method: 'GET',
    config: {
      validate: {
        query: {
          query: Joi.object().default({}),
        },
      },
      description: 'Find one entity',
      pre: [{
        method: (request, reply) => reply(toBSON(request.query.query)),
        assign: 'query',
      }],
    },
  })
  async findOne(request) {
    const { query } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound('Unable to find entity.');
    }

    return entity;
  }

  @route({
    path: '/{id}',
    method: 'PUT',
    config: {
      validate: {
        params: {
          id: idValidator,
        },
      },
      description: 'Replace an entity',
      pre: [{
        method: (request, reply) => reply(idToQuery(request.params.id)),
        assign: 'query',
      }, {
        method: (request, reply) => reply(toBSON(request.payload)),
        assign: 'payload',
      }],
    },
  })
  async replaceOne(request) {
    const { query, payload } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound(`Unable to find entity with id ${request.params.id}`);
    }

    return this.Repository.replaceOne({
      ...entity,
      ...payload,
    });
  }

  @route({
    path: '/{id}',
    method: 'PATCH',
    config: {
      validate: {
        params: {
          id: idValidator,
        },
      },
      description: 'Update an entity',
      pre: [{
        method: (request, reply) => reply(idToQuery(request.params.id)),
        assign: 'query',
      }, {
        method: (request, reply) => reply(toBSON(request.payload)),
        assign: 'payload',
      }],
    },
  })
  async updateOne(request) {
    const { query, payload } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound(`Unable to find entity with id ${request.params.id}`);
    }

    try {
      await this.Repository.validate({
        ...entity,
        ...payload,
      });
    } catch (err) {
      if (err.isJoi) {
        throw Boom.badRequest(err.details[0].message);
      }

      throw err;
    }

    return this.Repository.updateOne({
      query,
      update: {
        $set: payload,
      },
    });
  }

  applyContext({ routes, generateContext }) {
    (routes || Object.keys(this.routes)).forEach((routeId) => {
      this.routes[routeId].config.pre.push({
        method: this.constructor.applyContextToRoute(routeId, generateContext),
      });
    });
  }
}

export default MongoResourceRouter;
<commit_msg>[makeen-router] using route shorthands in MongoResourceRouter<commit_after>import Joi from 'joi';
import Boom from 'boom';
import pick from 'lodash/pick';
import Router from './Router';
import { toBSON, idValidator, idToQuery } from '../libs/mongo-helpers';
import { route } from '../libs/decorators';

class MongoResourceRouter extends Router {
  static applyContextToRoute = (routeId, generateContext) =>
    (request, reply) => {
      const context = generateContext(request);

      switch (routeId) {
        case 'count':
        case 'deleteOne':
        case 'deleteOneById':
        case 'findById':
        case 'findOne':
          Object.assign(request.pre.query, context);
          break;
        case 'createOne':
          Object.assign(request.pre.payload, context);
          break;
        case 'findMany':
          Object.assign(request.pre.queryParams.query, context);
          break;
        case 'replaceOne':
        case 'updateOne':
          Object.assign(request.pre.query, context);
          Object.assign(request.pre.payload, context);
          break;
        default:
      }

      reply();
    };

  constructor(Repository, config) {
    super(
      Joi.attempt(
        config,
        Joi.object()
          .keys({
            entitySchema: Joi.object(),
          })
          .unknown(),
      ),
    );

    this.Repository = Repository;

    this.addRoute('deleteOneById', {
      path: '/{id}',
      method: 'DELETE',
      handler: this.deleteOne,
      config: {
        validate: {
          params: {
            id: idValidator,
          },
        },
        description: 'Delete an entity by id',
        pre: [
          {
            method: (request, reply) => reply(idToQuery(request.params.id)),
            assign: 'query',
          },
        ],
      },
    });

    this.routes.createOne.config.validate.payload = this.config.entitySchema;
    this.routes.replaceOne.config.validate.payload = this.config.entitySchema;
  }

  @route.get({
    path: '/count',
    config: {
      validate: {
        query: {
          query: Joi.object().default({}),
        },
      },
      description: 'Count entities',
      pre: [
        {
          method: (request, reply) => reply(toBSON(request.query.query)),
          assign: 'query',
        },
      ],
    },
  })
  count(request) {
    const { query } = request.pre;
    return this.Repository.count({ query });
  }

  @route.post({
    path: '/',
    config: {
      validate: {},
      description: 'Create a new entity',
      pre: [
        {
          method: (request, reply) => reply(toBSON(request.payload)),
          assign: 'payload',
        },
      ],
    },
  })
  createOne(request) {
    const { payload } = request.pre;
    return this.Repository.createOne(payload);
  }

  @route.delete({
    path: '/deleteOne',
    config: {
      validate: {
        payload: {
          query: Joi.object().required(),
        },
      },
      description: 'Delete an entity',
      pre: [
        {
          method: (request, reply) => reply(toBSON(request.query.query)),
          assign: 'query',
        },
      ],
    },
  })
  deleteOne(request) {
    const { query } = request.pre;
    return this.Repository.deleteOne({ query });
  }

  @route.get({
    path: '/{id}',
    config: {
      validate: {
        params: {
          id: idValidator,
        },
      },
      description: 'Find an entity by id',
      pre: [
        {
          method: (request, reply) => reply(idToQuery(request.params.id)),
          assign: 'query',
        },
      ],
    },
  })
  async findById(request) {
    const { query } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound(`Unable to find entity with id ${request.params.id}`);
    }

    return entity;
  }

  @route.get({
    path: '/',
    config: {
      validate: {
        query: {
          query: Joi.object().default({}),
          offset: Joi.number(),
          limit: Joi.number(),
          orderBy: Joi.object().default({}),
          fields: Joi.object().default({}),
        },
      },
      description: 'Find entities',
      pre: [
        {
          method: (request, reply) => reply(toBSON(request.query.query)),
          assign: 'query',
        },
        {
          method: (request, reply) => {
            const params = pick(request.query, ['fields', 'orderBy']);
            params.query = request.pre.query;

            if (request.query.offset !== undefined) {
              params.skip = parseInt(request.query.offset, 10);
            }

            if (request.query.limit !== undefined) {
              params.limit = parseInt(request.query.limit, 10);
            }

            reply(params);
          },
          assign: 'queryParams',
        },
      ],
    },
  })
  findMany(request) {
    const { queryParams } = request.pre;
    return this.Repository.findMany(queryParams).then(c => c.toArray());
  }

  @route.get({
    path: '/findOne',
    config: {
      validate: {
        query: {
          query: Joi.object().default({}),
        },
      },
      description: 'Find one entity',
      pre: [
        {
          method: (request, reply) => reply(toBSON(request.query.query)),
          assign: 'query',
        },
      ],
    },
  })
  async findOne(request) {
    const { query } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound('Unable to find entity.');
    }

    return entity;
  }

  @route.put({
    path: '/{id}',
    method: 'PUT',
    config: {
      validate: {
        params: {
          id: idValidator,
        },
      },
      description: 'Replace an entity',
      pre: [
        {
          method: (request, reply) => reply(idToQuery(request.params.id)),
          assign: 'query',
        },
        {
          method: (request, reply) => reply(toBSON(request.payload)),
          assign: 'payload',
        },
      ],
    },
  })
  async replaceOne(request) {
    const { query, payload } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound(`Unable to find entity with id ${request.params.id}`);
    }

    return this.Repository.replaceOne({
      ...entity,
      ...payload,
    });
  }

  @route.patch({
    path: '/{id}',
    config: {
      validate: {
        params: {
          id: idValidator,
        },
      },
      description: 'Update an entity',
      pre: [
        {
          method: (request, reply) => reply(idToQuery(request.params.id)),
          assign: 'query',
        },
        {
          method: (request, reply) => reply(toBSON(request.payload)),
          assign: 'payload',
        },
      ],
    },
  })
  async updateOne(request) {
    const { query, payload } = request.pre;
    const entity = await this.Repository.findOne({ query });

    if (!entity) {
      throw Boom.notFound(`Unable to find entity with id ${request.params.id}`);
    }

    try {
      await this.Repository.validate({
        ...entity,
        ...payload,
      });
    } catch (err) {
      if (err.isJoi) {
        throw Boom.badRequest(err.details[0].message);
      }

      throw err;
    }

    return this.Repository.updateOne({
      query,
      update: {
        $set: payload,
      },
    });
  }

  applyContext({ routes, generateContext }) {
    (routes || Object.keys(this.routes)).forEach(routeId => {
      this.routes[routeId].config.pre.push({
        method: this.constructor.applyContextToRoute(routeId, generateContext),
      });
    });
  }
}

export default MongoResourceRouter;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/actions';
import Toggle from 'material-ui/Toggle';
import FlatButton from 'material-ui/FlatButton';
import Subheader from 'material-ui/Subheader';
import Paper from 'material-ui/Paper';
import styles from '../assets/formStyles';
import Formsy from 'formsy-react';
import { FormsyText, FormsyRadioGroup, FormsyRadio } from 'formsy-material-ui/lib';
import $ from 'jquery';

export class DevicePage extends React.Component {

  constructor(props) {
    super(props);
    this.errorMessages = {
      nameError: 'Please provide a valid name',
      descriptionError: 'Please enter a valid description',
      priceError: 'Please enter time and price options',
    };
    this.state = {
      canSubmit: false,
      error: '',
      totalCost: 0,
      time: 0,
      units: 0,
    };
  }

  totalCost(time, units) {
    const costPerMs = this.props.appState.featured.cost / 86400000;
    return (units * time * costPerMs).toFixed(2);
  }

  handleTime(e) {
    const time = parseInt(e.target.value, 10);
    const totalCost = this.totalCost(time, this.state.units);

    this.setState({
      time,
      totalCost,
    });
  }

  handleUnits(e) {
    const units = parseInt(e.target.value, 10);
    const totalCost = this.totalCost(this.state.time, units);

    this.setState({
      units,
      totalCost,
    });
  }

  enableButton() {
    this.setState({
      canSubmit: true,
    });
  }

  disableButton() {
    this.setState({
      canSubmit: false,
    });
  }

  toggleDevice(deviceState) {
    const context = this;
    const hardwarekey = this.props.appState.featured.hardwarekey;
     // TODO: need to replace the home ID with the real one once it is in appState
    const apiPath = '/api/v1/homes/1/devices/'.concat(hardwarekey);

    $.post(apiPath, deviceState, (req) => {
      if (!req.success === true) {
        context.setState({
          error: req.message,
        });
      } else {
        this.props.actions.toggleDevice(true);
        this.props.actions.paidUsage(true);
      }
    })
    .fail(() => {
      // set local state to display error
      context.setState({
        error: 'Failed to connect to device, try again.',
      });
    });
  }

  submitForm(data) {
    const totalTime = data.time * data.units;
    const deviceState = this.props.appState.featured;
    deviceState.time = totalTime;
    deviceState.paidusage = true;
    deviceState.isactive = true;

    this.toggleDevice(deviceState);
  }

  notifyFormError(data) {
    console.error('Form error:', data);
  }

  render() {
    let errorMsg =
{this.state.details}
;
    if (this.props.appState.featured.id === '') {
      return (

Uh oh!

You need to choose a device to display.

Click here to return to your dashboard.

      );
    }
    return (

How much time would you like to use the {this.props.appState.featured.name}?

        {errorMsg}

This device is: {this.props.appState.featured.description}

        <Paper style={styles.paperStyle}>
          <Formsy.Form
            onValid={() => this.enableButton()}
            onInvalid={() => this.disableButton()}
            onValidSubmit={(data) => this.submitForm(data)}
            onInvalidSubmit={() => this.notifyFormError()}
          >
            <FormsyRadioGroup name="time" defaultSelected="1" onChange={(e) => this.handleTime(e)}>
              <FormsyRadio
                value="20000"
                label="20 seconds"
              />
              <FormsyRadio
                value="60000"
                label="1 minute"
              />
              <FormsyRadio
                value="3600000"
                label="1 hour"
              />
              <FormsyRadio
                value="86400000"
                label="1 day"
              />
            </FormsyRadioGroup>
            <FormsyText
              name="units"
              validations="isExisty"
              validationError={this.errorMessages.descriptionError}
              required
              style={styles.fieldStyles}
              onChange={(e) => this.handleUnits(e)}
              floatingLabelText="How many units do you want?"
            />
            <FlatButton
              style={styles.submitStyle}
              type="submit"
              label="Submit"
              disabled={!this.state.canSubmit}
            />
          </Formsy.Form>
          <Subheader>

Total cost: {this.state.totalCost}

          </Subheader>
        </Paper>

    );
  }
}

DevicePage.propTypes = {
  actions: PropTypes.object.isRequired,
  appState: PropTypes.object.isRequired,
};

function mapStateToProps(state) {
  return {
    appState: state.appState,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(actions, dispatch),
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(DevicePage);

<commit_msg>Remove toggle from guest device page<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/actions';
import FlatButton from 'material-ui/FlatButton';
import Subheader from 'material-ui/Subheader';
import Paper from 'material-ui/Paper';
import styles from '../assets/formStyles';
import Formsy from 'formsy-react';
import { FormsyText, FormsyRadioGroup, FormsyRadio } from 'formsy-material-ui/lib';
import $ from 'jquery';

export class DevicePage extends React.Component {

  constructor(props) {
    super(props);
    this.errorMessages = {
      nameError: 'Please provide a valid name',
      descriptionError: 'Please enter a valid description',
      priceError: 'Please enter time and price options',
    };
    this.state = {
      canSubmit: false,
      error: '',
      totalCost: 0,
      time: 0,
      units: 0,
    };
  }

  totalCost(time, units) {
    const costPerMs = this.props.appState.featured.cost / 86400000;
    return (units * time * costPerMs).toFixed(2);
  }

  handleTime(e) {
    const time = parseInt(e.target.value, 10);
    const totalCost = this.totalCost(time, this.state.units);

    this.setState({
      time,
      totalCost,
    });
  }

  handleUnits(e) {
    const units = parseInt(e.target.value, 10);
    const totalCost = this.totalCost(this.state.time, units);

    this.setState({
      units,
      totalCost,
    });
  }

  enableButton() {
    this.setState({
      canSubmit: true,
    });
  }

  disableButton() {
    this.setState({
      canSubmit: false,
    });
  }

  toggleDevice(deviceState) {
    const context = this;
    const hardwarekey = this.props.appState.featured.hardwarekey;
     // TODO: need to replace the home ID with the real one once it is in appState
    const apiPath = '/api/v1/homes/1/devices/'.concat(hardwarekey);

    $.post(apiPath, deviceState, (req) => {
      if (!req.success === true) {
        context.setState({
          error: req.message,
        });
      } else {
        this.props.actions.toggleDevice(true);
        this.props.actions.paidUsage(true);
      }
    })
    .fail(() => {
      // set local state to display error
      context.setState({
        error: 'Failed to connect to device, try again.',
      });
    });
  }

  submitForm(data) {
    const totalTime = data.time * data.units;
    const deviceState = this.props.appState.featured;
    deviceState.time = totalTime;
    deviceState.paidusage = true;
    deviceState.isactive = true;

    this.toggleDevice(deviceState);
  }

  notifyFormError(data) {
    console.error('Form error:', data);
  }

  render() {
    let errorMsg =
{this.state.details}
;
    if (this.props.appState.featured.id === '') {
      return (

Uh oh!

You need to choose a device to display.

Click here to return to your dashboard.

      );
    }
    return (

How much time would you like to use the {this.props.appState.featured.name}?

        {errorMsg}

This device is: {this.props.appState.featured.description}

        <Paper style={styles.paperStyle}>
          <Formsy.Form
            onValid={() => this.enableButton()}
            onInvalid={() => this.disableButton()}
            onValidSubmit={(data) => this.submitForm(data)}
            onInvalidSubmit={() => this.notifyFormError()}
          >
            <FormsyRadioGroup name="time" defaultSelected="1" onChange={(e) => this.handleTime(e)}>
              <FormsyRadio
                value="20000"
                label="20 seconds"
              />
              <FormsyRadio
                value="60000"
                label="1 minute"
              />
              <FormsyRadio
                value="3600000"
                label="1 hour"
              />
              <FormsyRadio
                value="86400000"
                label="1 day"
              />
            </FormsyRadioGroup>
            <FormsyText
              name="units"
              validations="isExisty"
              validationError={this.errorMessages.descriptionError}
              required
              style={styles.fieldStyles}
              onChange={(e) => this.handleUnits(e)}
              floatingLabelText="How many units do you want?"
            />
            <FlatButton
              style={styles.submitStyle}
              type="submit"
              label="Submit"
              disabled={!this.state.canSubmit}
            />
          </Formsy.Form>
          <Subheader>

Total cost: {this.state.totalCost}

          </Subheader>
        </Paper>

    );
  }
}

DevicePage.propTypes = {
  actions: PropTypes.object.isRequired,
  appState: PropTypes.object.isRequired,
};

function mapStateToProps(state) {
  return {
    appState: state.appState,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(actions, dispatch),
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(DevicePage);

<|endoftext|>


<commit_before>import test from 'ava';
import path from 'path';
import generator from 'yeoman-test';
import assert from 'yeoman-assert';

test.before.cb(t => {
  generator.run(path.join(__dirname, '..', 'generators', 'app'))
           .withOptions({ skipInstall: true })
           .withPrompts({ name: 'test' })
           .on('end', t.end);
});

test('Generator', () => {
  assert.file([
    'bin/deploy',
    'config/lambda.config.js',
    'config/webpack.config.js',
    'src/index.js',
    'test/index-test.js',
    '.babelrc',
    '.gitignore',
    '.travis.yml',
    'package.json',
    'LICENSE.md',
    'README.md',
    'SAMPLES',
    'schema.json'
  ]);
});
<commit_msg>Simplify tests<commit_after>import test from 'ava';
import path from 'path';
import generator from 'yeoman-test';
import assert from 'yeoman-assert';

test.before(() => {
  return new Promise((resolve, reject) => {
    generator.run(path.join(__dirname, '..', 'generators', 'app'))
             .withOptions({ skipInstall: true })
             .withPrompts({ name: 'test' })
             .on('end', resolve)
             .on('error', reject);
  });
});

test('Generator', () => {
  assert.file([
    'bin/deploy',
    'config/lambda.config.js',
    'config/webpack.config.js',
    'src/index.js',
    'test/index-test.js',
    '.babelrc',
    '.gitignore',
    '.travis.yml',
    'package.json',
    'LICENSE.md',
    'README.md',
    'SAMPLES',
    'schema.json'
  ]);
});
<|endoftext|>


<commit_before>var nodegit = require("nodegit");
var path = require("path");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
fse.ensureDir = promisify(fse.ensureDir);

var fileName = "newFile.txt";
var fileContent = "hello world";

var repository;
var remote;

var signature = nodegit.Signature.create("Foo bar",
  "foo@bar.com", 123456789, 60);

// Load up the repository index and make our initial commit to HEAD
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
  .then(function(repoResult) {
    repository = repoResult;

    return repository.refreshIndex();
  })
  .then(function(index) {
    return index.addAll()
      .then(function() {
        return index.write();
      })
      .then(function() {
        return index.writeTree();
      });
  })
  .then(function(oid) {
    return repository.createCommit("HEAD", signature, signature,
      "commit 111", oid, []);
  })

  // Add a new remote
  .then(function() {
    return nodegit.Remote.create(repository, "origin",
      "git@github.com:tlqylzn/gitnode.git")
    .then(function(remoteResult) {
      remote = remoteResult;

      // Create the push object for this remote
      return remote.push(
        ["refs/heads/master:refs/heads/master"],
        {
          callbacks: {
            credentials: function(url, userName) {
              return nodegit.Cred.sshKeyFromAgent(userName);
            }
          }
        }
      );
    });
  }).done(function() {
    console.log("Done!");
  });
<commit_msg>commit 111<commit_after>var nodegit = require("nodegit");
var path = require("path");
var promisify = require("promisify-node");
var fse = promisify(require("fs-extra"));
fse.ensureDir = promisify(fse.ensureDir);

var fileName = "newFile.txt";
var fileContent = "hello world";

var repository;
var remote;
var oid;

var signature = nodegit.Signature.create("Foo bar",
  "foo@bar.com", 123456789, 60);

// Load up the repository index and make our initial commit to HEAD
nodegit.Repository.open(path.resolve(__dirname, "../.git"))
  .then(function(repoResult) {
    repository = repoResult;

    return repository.refreshIndex();
  })
  .then(function(index) {
    return index.addAll()
      .then(function() {
        return index.write();
      })
      .then(function() {
        return index.writeTree();
      });
  })
  .then(function(oidResult) {
    oid = oidResult;
    return nodegit.Reference.nameToId(repository, "HEAD");
  })
  .then(function(head) {
    return repository.getCommit(head);
  })
  .then(function(parent) {
    return repository.createCommit("HEAD", signature, signature,
      "commit 111", oid, [parent]);
  })

  // Add a new remote
  .then(function() {
    return nodegit.Remote.create(repository, "origin",
      "git@github.com:tlqylzn/gitnode.git")
    .then(function(remoteResult) {
      remote = remoteResult;

      // Create the push object for this remote
      return remote.push(
        ["refs/heads/master:refs/heads/master"],
        {
          callbacks: {
            credentials: function(url, userName) {
              return nodegit.Cred.sshKeyFromAgent(userName);
            }
          }
        }
      );
    });
  }).done(function() {
    console.log("Done!");
  });
<|endoftext|>


<commit_before>import { expect, assert } from 'chai'
import { heightify } from '../src/heightify'
import isObject from '../src/utils/isObject'
import initialError from '../src/utils/initialError'

describe('Heightify', () => {

  describe('Utils', () => {
    describe('isObject', () => {
      it('should return true if object is passed, and false otherwise', () => {
        const obj = {}
        const array = []
        expect(isObject(obj)).to.be.true
        expect(isObject(array)).to.be.false
      })
    })
    describe('initialError', () => {
      it('should throw if heightify is not passed with an object as argument', () => {
        expect(initialError).to.throw(Error)
      })
    })
  })

  describe('error messages', () => {
    it('should be ok if element is defined', () => {
      const heightifyWithDOMElement = heightify({
        element: 'div'
      })
      assert.isOk(heightifyWithDOMElement, 'OK' )
    })

    it('should throw if argument is not an object', () => {
      expect(() => {
        heightify('some options')
      }).to.throw('Expected \'some options\' to be an object.')
    })

    it('should throw when element is not defined', () => {
      expect(() => {
        heightify({})
      }).to.throw('Heightify requires a DOM node to match the height with. Please specify with the object key: \'element\'.')
    })
  })

  describe('Main functionality', () => {
    it('should find the tallest number in array', () => {
      const h = heightify({element: 'div', hasImages: true})
      const fakeArray = [100, 400, 1000, 2, 5, 200, 232]
      expect(h.maxNumberInArray(fakeArray)).to.equal(1000)
    })
  })

})
<commit_msg>resolves #16<commit_after>import { expect, assert } from 'chai'
import { heightify } from '../src/heightify'
import isObject from '../src/utils/isObject'
import initialError from '../src/utils/initialError'

describe('Heightify', () => {
  describe('Utils', () => {
    describe('isObject', () => {
      it('should return true if object is passed, and false otherwise', () => {
        const obj = {}
        const array = []
        expect(isObject(obj)).to.be.true
        expect(isObject(array)).to.be.false
      })
    })
    describe('initialError', () => {
      it('should throw if heightify is not passed with an object as argument', () => {
        expect(initialError).to.throw(Error)
      })
    })
  })

  describe('error messages', () => {
    it('should be ok if element is defined', () => {
      const heightifyWithDOMElement = heightify({
        element: 'div'
      })
      assert.isOk(heightifyWithDOMElement, 'OK' )
    })

    it('should throw if argument is not an object', () => {
      expect(() => {
        heightify('some options')
      }).to.throw('Expected \'some options\' to be an object.')
    })

    it('should throw when element is not defined', () => {
      expect(() => {
        heightify({})
      }).to.throw('Heightify requires a DOM node to match the height with. Please specify with the object key: \'element\'.')
    })
  })

  describe('Main functionality', () => {
    it('should find the tallest number in array', () => {
      const h = heightify({element: 'div', hasImages: true})
      const fakeArray = [100, 400, 1000, 2, 5, 200, 232]
      expect(h.maxNumberInArray(fakeArray)).to.equal(1000)
    })
  })

})
<|endoftext|>


<commit_before>import {View} from '../view';
import {Monitor} from './style.monitor';
import * as columnService from '../column/column.service';
import {getFactory as valueFactory} from '../services/value';
import {noop} from '../utility';
import {VirtualRowStyle, VirtualCellStyle} from './style.virtual';

export class StyleView extends View {
	constructor(model, table) {
		super(model);

		this.table = table;
		this.valueFactory = valueFactory;
		this.active = {
			row: false,
			cell: false
		};

		this.monitor = {
			row: new Monitor(model),
			cell: new Monitor(model)
		};

		model.viewChanged.watch(() => {
			this.invalidate();
		});

		model.styleChanged.watch(e => {
			if (e.hasChanges('row')) {
				this.active.row = e.state.row !== noop;
			}

			if (e.hasChanges('cell')) {
				this.active.cell = e.state.row !== noop;
			}

			this.invalidate();
		});
	}

	invalidate() {
		const active = this.active;
		const model = this.model;
		const isVirtual = model.scroll().mode === 'virtual';
		const isActive = isVirtual || active.row || active.cell;
		if (!isActive) {
			return;
		}

		const table = this.table;
		const valueFactory = this.valueFactory;
		const styleState = model.style();
		const bodyRows = table.body.rows();
		const rowMonitor = this.monitor.row;
		const cellMonitor = this.monitor.cell;
		const columns = table.data.columns();
		const columnMap = columnService.map(columns);
		// TODO: improve perfomance
		const valueCache = new Map();
		const value = (row, column) => {
			let getValue = valueCache.get(column);
			if (!getValue) {
				getValue = valueFactory(column);
				valueCache.set(column, getValue);
			}

			return getValue(row);
		};

		let isRowActive = active.row;
		let isCellActive = active.cell;
		let styleRow = styleState.row;
		let styleCell = styleState.cell;
		if (isVirtual) {
			isRowActive = true;
			isCellActive = true;
			styleRow = new VirtualRowStyle(table).applyFactory();
			styleCell = new VirtualCellStyle(table).applyFactory();
		}

		const domCell = cellMonitor.enter();
		const domRow = rowMonitor.enter();
		try {
			for (let i = 0, rowsLength = bodyRows.length; i < rowsLength; i++) {
				const bodyRow = bodyRows[i];
				const rowIndex = bodyRow.index;
				const dataRow = (bodyRow.model || {}).model;
				if (!dataRow) {
					continue;
				}

				if (isRowActive) {
					const rowContext = {
						class: domRow(bodyRow),
						row: rowIndex,
						value: value,
						columns: {
							map: columnMap,
							list: columns
						}
					};

					styleRow(dataRow, rowContext);
				}

				if (isCellActive) {
					const cells = bodyRow.cells();
					for (let j = 0, cellsLength = cells.length; j < cellsLength; j++) {
						const cell = cells[j];
						const column = columns[j];
						const cellContext = {
							class: domCell(cell),
							row: rowIndex,
							column: j,
							value: value,
							columns: {
								map: columnMap,
								list: columns
							}
						};

						styleCell(dataRow, column, cellContext);
					}
				}
			}
		}
		finally {
			rowMonitor.exit(domRow);
			cellMonitor.exit(domCell);
		}
	}
}<commit_msg>fix typo<commit_after>import {View} from '../view';
import {Monitor} from './style.monitor';
import * as columnService from '../column/column.service';
import {getFactory as valueFactory} from '../services/value';
import {noop} from '../utility';
import {VirtualRowStyle, VirtualCellStyle} from './style.virtual';

export class StyleView extends View {
	constructor(model, table) {
		super(model);

		this.table = table;
		this.valueFactory = valueFactory;
		this.active = {
			row: false,
			cell: false
		};

		this.monitor = {
			row: new Monitor(model),
			cell: new Monitor(model)
		};

		model.viewChanged.watch(() => {
			this.invalidate();
		});

		model.styleChanged.watch(e => {
			if (e.hasChanges('row')) {
				this.active.row = e.state.row !== noop;
			}

			if (e.hasChanges('cell')) {
				this.active.cell = e.state.cell !== noop;
			}

			this.invalidate();
		});
	}

	invalidate() {
		const active = this.active;
		const model = this.model;
		const isVirtual = model.scroll().mode === 'virtual';
		const isActive = isVirtual || active.row || active.cell;
		if (!isActive) {
			return;
		}

		const table = this.table;
		const valueFactory = this.valueFactory;
		const styleState = model.style();
		const bodyRows = table.body.rows();
		const rowMonitor = this.monitor.row;
		const cellMonitor = this.monitor.cell;
		const columns = table.data.columns();
		const columnMap = columnService.map(columns);
		// TODO: improve perfomance
		const valueCache = new Map();
		const value = (row, column) => {
			let getValue = valueCache.get(column);
			if (!getValue) {
				getValue = valueFactory(column);
				valueCache.set(column, getValue);
			}

			return getValue(row);
		};

		let isRowActive = active.row;
		let isCellActive = active.cell;
		let styleRow = styleState.row;
		let styleCell = styleState.cell;
		if (isVirtual) {
			isRowActive = true;
			isCellActive = true;
			styleRow = new VirtualRowStyle(table).applyFactory();
			styleCell = new VirtualCellStyle(table).applyFactory();
		}

		const domCell = cellMonitor.enter();
		const domRow = rowMonitor.enter();
		try {
			for (let i = 0, rowsLength = bodyRows.length; i < rowsLength; i++) {
				const bodyRow = bodyRows[i];
				const rowIndex = bodyRow.index;
				const dataRow = (bodyRow.model || {}).model;
				if (!dataRow) {
					continue;
				}

				if (isRowActive) {
					const rowContext = {
						class: domRow(bodyRow),
						row: rowIndex,
						value: value,
						columns: {
							map: columnMap,
							list: columns
						}
					};

					styleRow(dataRow, rowContext);
				}

				if (isCellActive) {
					const cells = bodyRow.cells();
					for (let j = 0, cellsLength = cells.length; j < cellsLength; j++) {
						const cell = cells[j];
						const column = columns[j];
						const cellContext = {
							class: domCell(cell),
							row: rowIndex,
							column: j,
							value: value,
							columns: {
								map: columnMap,
								list: columns
							}
						};

						styleCell(dataRow, column, cellContext);
					}
				}
			}
		}
		finally {
			rowMonitor.exit(domRow);
			cellMonitor.exit(domCell);
		}
	}
}<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.search");
pimcore.object.search = Class.create(pimcore.object.helpers.gridTabAbstract, {
    systemColumns: ["id", "fullpath", "type", "subtype", "filename", "classname", "creationDate", "modificationDate"],
    fieldObject: {},

    title: t('search_edit'),
    icon: "pimcore_icon_tab_search",
    onlyDirectChildren: false,

    sortinfo: {},
    initialize: function(object) {
        this.object = object;
        this.element = object;
    },

    getLayout: function () {

        if (this.layout == null) {

            // check for classtypes inside of the folder if there is only one type don't display the selection
            var toolbarConfig;

            if (this.object.data.classes && typeof this.object.data.classes == "object") {

                if (this.object.data.classes.length < 1) {
                    return;
                }

                var data = [];
                for (i = 0; i < this.object.data.classes.length; i++) {
                    var klass = this.object.data.classes[i];
                    data.push([klass.id, klass.name, ts(klass.name)]);

                }

                var classStore = new Ext.data.ArrayStore({
                    data: data,
                    sortInfo: {
                        field: 'translatedText',
                        direction: 'ASC'
                    },
                    fields: [
                        {name: 'id', type: 'number'},
                        {name: 'name', type: 'string'},
                        {name: 'translatedText', type: 'string'}
                    ]
                });

                this.classSelector = new Ext.form.ComboBox({
                    name: "selectClass",
                    listWidth: 'auto',
                    store: classStore,
                    mode:"local",
                    valueField: 'id',
                    displayField: 'translatedText',
                    triggerAction: 'all',
                    value: this.object.data["selectedClass"],
                    listeners: {
                        "select": this.changeClassSelect.bind(this)
                    }
                });

                if (this.object.data.classes.length > 1) {
                    toolbarConfig = [new Ext.Toolbar.TextItem({
                        text: t("please_select_a_type")
                    }),this.classSelector];
                }
                else {
                    this.currentClass = this.object.data.classes[0].id;
                }
            }
            else {
                return;
            }

            this.layout = new Ext.Panel({
                title: this.title,
                border: false,
                layout: "fit",
                iconCls: this.icon,
                items: [],
                tbar: toolbarConfig
            });

            if (this.currentClass) {
                //this.layout.on("afterrender", this.setClass.bind(this, this.currentClass));
            }
        }

        return this.layout;
    },

    changeClassSelect: function (field, newValue, oldValue) {
        var selectedClass = newValue.data.id;
        this.setClass(selectedClass);
    },

    setClass: function (classId) {
        this.classId = classId;
        this.getTableDescription(classId);
    },

    getTableDescription: function (classId) {
        Ext.Ajax.request({
            url: "/admin/object-helper/grid-get-column-config",
            params: {id: classId, objectId: this.object.id, gridtype: "grid"},
            success: this.createGrid.bind(this)
        });
    },

    createGrid: function (response) {
        try {

            var itemsPerPage = 20;

            var fields = [];
            if (response.responseText) {
                response = Ext.decode(response.responseText);

                if (response.pageSize) {
                    itemsPerPage = response.pageSize;
                }

                fields = response.availableFields;
                this.gridLanguage = response.language;
                this.sortinfo = response.sortinfo;
                if (response.onlyDirectChildren) {
                    this.onlyDirectChildren = response.onlyDirectChildren;
                }
            } else {
                fields = response;
            }

            this.fieldObject = {};
            for (var i = 0; i < fields.length; i++) {
                this.fieldObject[fields[i].key] = fields[i];
            }

            this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
                clicksToEdit: 1
            });

            var plugins = [this.cellEditing, 'gridfilters'];

            // get current class
            var classStore = pimcore.globalmanager.get("object_types_store");
            var klass = classStore.getById(this.classId);

            var gridHelper = new pimcore.object.helpers.grid(
                klass.data.text,
                fields,
                "/admin/object/grid-proxy/classId/" + this.classId + "/folderId/" + this.object.id,
                {
                    language: this.gridLanguage,
                    limit: itemsPerPage
                },
                false
            );

            gridHelper.showSubtype = false;
            gridHelper.enableEditor = true;
            gridHelper.limit = itemsPerPage;

            var propertyVisibility = klass.get("propertyVisibility");

            this.store = gridHelper.getStore();
            if (this.sortinfo) {
                this.store.setDefaultSort(this.sortinfo.field, this.sortinfo.direction);
            }
            this.store.getProxy().setExtraParam("only_direct_children", this.onlyDirectChildren);
            this.store.load();

            var gridColumns = gridHelper.getGridColumns();

            // add filters
            this.gridfilters = gridHelper.getGridFilters();

            this.languageInfo = new Ext.Toolbar.TextItem({
                text: t("grid_current_language") + ": " + pimcore.available_languages[this.gridLanguage]
            });

            this.toolbarFilterInfo = new Ext.Toolbar.TextItem({
                text: ""
            });

            this.createSqlEditor();

            this.checkboxOnlyDirectChildren = new Ext.form.Checkbox({
                name: "onlyDirectChildren",
                style: "margin-bottom: 5px; margin-left: 5px",
                checked: this.onlyDirectChildren,
                listeners: {
                    "change": function (field, checked) {
                        this.grid.filters.clearFilters();

                        this.store.baseparams = {};
                        this.store.getProxy().setExtraParam("only_direct_children", checked);

                        this.onlyDirectChildren = checked;
                        this.pagingtoolbar.moveFirst();
                    }.bind(this)
                }
            });

            // grid
            this.grid = Ext.create('Ext.grid.Panel', {
                frame: false,
                store: this.store,
                columns: gridColumns,
                columnLines: true,
                stripeRows: true,
                border: true,
                selModel: gridHelper.getSelectionColumn(),
                trackMouseOver: true,
                loadMask: true,
                plugins: plugins,
                viewConfig: {
                    forceFit: false
                },
                tbar: [this.languageInfo, "-", this.toolbarFilterInfo, "->", this.checkboxOnlyDirectChildren, t("only_children"), "-", this.sqlEditor, this.sqlButton, "-", {
                    text: t("search_and_move"),
                    iconCls: "pimcore_icon_search_and_move",
                    handler: pimcore.helpers.searchAndMove.bind(this, this.object.id,
                        function () {
                            this.store.reload();
                        }.bind(this), "object")
                }, "-", {
                    text: t("export_csv"),
                    iconCls: "pimcore_icon_export",
                    handler: function () {

                        Ext.MessageBox.show({
                            title: t('warning'),
                            msg: t('csv_object_export_warning'),
                            buttons: Ext.Msg.OKCANCEL,
                            fn: function (btn) {
                                if (btn == 'ok') {
                                    this.startCsvExport();
                                }
                            }.bind(this),
                            icon: Ext.MessageBox.WARNING
                        });

                    }.bind(this)
                }, "-", {
                    text: t("grid_column_config"),
                    iconCls: "pimcore_icon_grid_column_config",
                    handler: this.openColumnConfig.bind(this)
                }]
            });
            this.grid.on("rowcontextmenu", this.onRowContextmenu);

            this.grid.on("afterrender", function (grid) {
                //this.updateGridHeaderContextMenu(grid);
            }.bind(this));

            this.grid.on("sortchange", function (ct, column, direction, eOpts ) {
                this.sortinfo = {
                    field: column.dataIndex,
                    direction: direction
                };
            }.bind(this));

            // check for filter updates
            this.grid.on("filterupdate", function () {
                this.filterUpdateFunction(this.gridfilters, this.toolbarFilterInfo);
            }.bind(this));

            gridHelper.applyGridEvents(this.grid);

            this.pagingtoolbar = new Ext.PagingToolbar({
                pageSize: itemsPerPage,
                store: this.store,
                displayInfo: true,
                displayMsg: '{0} - {1} / {2}',
                emptyMsg: t("no_objects_found")
            });

            // add per-page selection
            this.pagingtoolbar.add("-");

            this.pagingtoolbar.add(new Ext.Toolbar.TextItem({
                text: t("items_per_page")
            }));
            this.pagingtoolbar.add(new Ext.form.ComboBox({
                store: [
                    [10, "10"],
                    [20, "20"],
                    [40, "40"],
                    [60, "60"],
                    [80, "80"],
                    [100, "100"],
                    [999999, t("all")]
                ],
                mode: "local",
                width: 50,
                value: itemsPerPage,
                triggerAction: "all",
                listeners: {
                    select: function (box, rec, index) {
                        this.pagingtoolbar.pageSize = intval(rec.data.field1);
                        this.pagingtoolbar.moveFirst();
                    }.bind(this)
                }
            }));

            this.editor = new Ext.Panel({
                layout: "border",
                items: [new Ext.Panel({
                    autoScroll: true,
                    items: [this.grid],
                    region: "center",
                    layout: "fit",
                    bbar: this.pagingtoolbar
                })]
            });

            this.layout.removeAll();
            this.layout.add(this.editor);
            this.layout.doLayout();
        } catch (e) {
            console.log(e);
        }

    },

    getGridConfig: function($super) {
        var config = $super();
        config.onlyDirectChildren = this.onlyDirectChildren;
        config.pageSize = this.pagingtoolbar.pageSize;
        return config;
    },

    onRowContextmenu: function (grid, record, tr, rowIndex, e, eOpts ) {

        //$(grid.getView().getRow(rowIndex)).animate( { backgroundColor: '#E0EAEE' }, 100).animate( {
        //    backgroundColor: '#fff' }, 400);

        var menu = new Ext.menu.Menu();
        var data = grid.getStore().getAt(rowIndex);
        var selectedRows = grid.getSelectionModel().getSelection();

        if (selectedRows.length <= 1) {

            menu.add(new Ext.menu.Item({
                text: t('open'),
                iconCls: "pimcore_icon_open",
                handler: function (data) {
                    pimcore.helpers.openObject(data.data.id, "object");
                }.bind(this, data)
            }));
            menu.add(new Ext.menu.Item({
                text: t('show_in_tree'),
                iconCls: "pimcore_icon_show_in_tree",
                handler: function (data) {
                    try {
                        try {
                            Ext.getCmp("pimcore_panel_tree_objects").expand();
                            var tree = pimcore.globalmanager.get("layout_object_tree");
                            pimcore.helpers.selectPathInTree(tree.tree, data.data.idPath);
                        } catch (e) {
                            console.log(e);
                        }

                    } catch (e2) { console.log(e2); }
                }.bind(grid, data)
            }));
            menu.add(new Ext.menu.Item({
                text: t('delete'),
                iconCls: "pimcore_icon_delete",
                handler: function (data) {
                    var store = this.getStore();
                    pimcore.helpers.deleteObject(data.data.id, store.reload.bind(this.getStore()));
                }.bind(grid, data)
            }));
        } else {
            menu.add(new Ext.menu.Item({
                text: t('open_selected'),
                iconCls: "pimcore_icon_open",
                handler: function (data) {
                    var selectedRows = grid.getSelectionModel().getSelections();
                    for (var i = 0; i < selectedRows.length; i++) {
                        pimcore.helpers.openObject(selectedRows[i].data.id, "object");
                    }
                }.bind(this, data)
            }));

            menu.add(new Ext.menu.Item({
                text: t('delete_selected'),
                iconCls: "pimcore_icon_delete",
                handler: function (data) {
                    var ids = [];
                    var selectedRows = grid.getSelectionModel().getSelections();
                    for (var i = 0; i < selectedRows.length; i++) {
                        ids.push(selectedRows[i].data.id);
                    }
                    ids = ids.join(',');

                    pimcore.helpers.deleteObject(ids, function() {
                            this.getStore().reload();
                            pimcore.globalmanager.get("layout_object_tree").tree.getRootNode().reload();
                        }.bind(this)
                    );
                }.bind(grid, data)
            }));
        }

        e.stopEvent();
        menu.showAt(e.pageX, e.pageY);
    }

});
<commit_msg>object grid: fixed class selection if there is only one class<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.object.search");
pimcore.object.search = Class.create(pimcore.object.helpers.gridTabAbstract, {
    systemColumns: ["id", "fullpath", "type", "subtype", "filename", "classname", "creationDate", "modificationDate"],
    fieldObject: {},

    title: t('search_edit'),
    icon: "pimcore_icon_tab_search",
    onlyDirectChildren: false,

    sortinfo: {},
    initialize: function(object) {
        this.object = object;
        this.element = object;
    },

    getLayout: function () {

        if (this.layout == null) {

            // check for classtypes inside of the folder if there is only one type don't display the selection
            var toolbarConfig;

            if (this.object.data.classes && typeof this.object.data.classes == "object") {

                if (this.object.data.classes.length < 1) {
                    return;
                }

                var data = [];
                for (i = 0; i < this.object.data.classes.length; i++) {
                    var klass = this.object.data.classes[i];
                    data.push([klass.id, klass.name, ts(klass.name)]);

                }

                var classStore = new Ext.data.ArrayStore({
                    data: data,
                    sortInfo: {
                        field: 'translatedText',
                        direction: 'ASC'
                    },
                    fields: [
                        {name: 'id', type: 'number'},
                        {name: 'name', type: 'string'},
                        {name: 'translatedText', type: 'string'}
                    ]
                });

                this.classSelector = new Ext.form.ComboBox({
                    name: "selectClass",
                    listWidth: 'auto',
                    store: classStore,
                    mode:"local",
                    valueField: 'id',
                    displayField: 'translatedText',
                    triggerAction: 'all',
                    value: this.object.data["selectedClass"],
                    listeners: {
                        "select": this.changeClassSelect.bind(this)
                    }
                });

                if (this.object.data.classes.length > 1) {
                    toolbarConfig = [new Ext.Toolbar.TextItem({
                        text: t("please_select_a_type")
                    }),this.classSelector];
                }
                else {
                    this.currentClass = this.object.data.classes[0].id;
                }
            }
            else {
                return;
            }

            this.layout = new Ext.Panel({
                title: this.title,
                border: false,
                layout: "fit",
                iconCls: this.icon,
                items: [],
                tbar: toolbarConfig
            });

            if (this.currentClass) {
                this.layout.on("afterrender", this.setClass.bind(this, this.currentClass));
            }
        }

        return this.layout;
    },

    changeClassSelect: function (field, newValue, oldValue) {
        var selectedClass = newValue.data.id;
        this.setClass(selectedClass);
    },

    setClass: function (classId) {
        this.classId = classId;
        this.getTableDescription(classId);
    },

    getTableDescription: function (classId) {
        Ext.Ajax.request({
            url: "/admin/object-helper/grid-get-column-config",
            params: {id: classId, objectId: this.object.id, gridtype: "grid"},
            success: this.createGrid.bind(this)
        });
    },

    createGrid: function (response) {
        try {

            var itemsPerPage = 20;

            var fields = [];
            if (response.responseText) {
                response = Ext.decode(response.responseText);

                if (response.pageSize) {
                    itemsPerPage = response.pageSize;
                }

                fields = response.availableFields;
                this.gridLanguage = response.language;
                this.sortinfo = response.sortinfo;
                if (response.onlyDirectChildren) {
                    this.onlyDirectChildren = response.onlyDirectChildren;
                }
            } else {
                fields = response;
            }

            this.fieldObject = {};
            for (var i = 0; i < fields.length; i++) {
                this.fieldObject[fields[i].key] = fields[i];
            }

            this.cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
                clicksToEdit: 1
            });

            var plugins = [this.cellEditing, 'gridfilters'];

            // get current class
            var classStore = pimcore.globalmanager.get("object_types_store");
            var klass = classStore.getById(this.classId);

            var gridHelper = new pimcore.object.helpers.grid(
                klass.data.text,
                fields,
                "/admin/object/grid-proxy/classId/" + this.classId + "/folderId/" + this.object.id,
                {
                    language: this.gridLanguage,
                    limit: itemsPerPage
                },
                false
            );

            gridHelper.showSubtype = false;
            gridHelper.enableEditor = true;
            gridHelper.limit = itemsPerPage;

            var propertyVisibility = klass.get("propertyVisibility");

            this.store = gridHelper.getStore();
            if (this.sortinfo) {
                this.store.setDefaultSort(this.sortinfo.field, this.sortinfo.direction);
            }
            this.store.getProxy().setExtraParam("only_direct_children", this.onlyDirectChildren);
            this.store.load();

            var gridColumns = gridHelper.getGridColumns();

            // add filters
            this.gridfilters = gridHelper.getGridFilters();

            this.languageInfo = new Ext.Toolbar.TextItem({
                text: t("grid_current_language") + ": " + pimcore.available_languages[this.gridLanguage]
            });

            this.toolbarFilterInfo = new Ext.Toolbar.TextItem({
                text: ""
            });

            this.createSqlEditor();

            this.checkboxOnlyDirectChildren = new Ext.form.Checkbox({
                name: "onlyDirectChildren",
                style: "margin-bottom: 5px; margin-left: 5px",
                checked: this.onlyDirectChildren,
                listeners: {
                    "change": function (field, checked) {
                        this.grid.filters.clearFilters();

                        this.store.baseparams = {};
                        this.store.getProxy().setExtraParam("only_direct_children", checked);

                        this.onlyDirectChildren = checked;
                        this.pagingtoolbar.moveFirst();
                    }.bind(this)
                }
            });

            // grid
            this.grid = Ext.create('Ext.grid.Panel', {
                frame: false,
                store: this.store,
                columns: gridColumns,
                columnLines: true,
                stripeRows: true,
                border: true,
                selModel: gridHelper.getSelectionColumn(),
                trackMouseOver: true,
                loadMask: true,
                plugins: plugins,
                viewConfig: {
                    forceFit: false
                },
                tbar: [this.languageInfo, "-", this.toolbarFilterInfo, "->", this.checkboxOnlyDirectChildren, t("only_children"), "-", this.sqlEditor, this.sqlButton, "-", {
                    text: t("search_and_move"),
                    iconCls: "pimcore_icon_search_and_move",
                    handler: pimcore.helpers.searchAndMove.bind(this, this.object.id,
                        function () {
                            this.store.reload();
                        }.bind(this), "object")
                }, "-", {
                    text: t("export_csv"),
                    iconCls: "pimcore_icon_export",
                    handler: function () {

                        Ext.MessageBox.show({
                            title: t('warning'),
                            msg: t('csv_object_export_warning'),
                            buttons: Ext.Msg.OKCANCEL,
                            fn: function (btn) {
                                if (btn == 'ok') {
                                    this.startCsvExport();
                                }
                            }.bind(this),
                            icon: Ext.MessageBox.WARNING
                        });

                    }.bind(this)
                }, "-", {
                    text: t("grid_column_config"),
                    iconCls: "pimcore_icon_grid_column_config",
                    handler: this.openColumnConfig.bind(this)
                }]
            });
            this.grid.on("rowcontextmenu", this.onRowContextmenu);

            this.grid.on("afterrender", function (grid) {
                //this.updateGridHeaderContextMenu(grid);
            }.bind(this));

            this.grid.on("sortchange", function (ct, column, direction, eOpts ) {
                this.sortinfo = {
                    field: column.dataIndex,
                    direction: direction
                };
            }.bind(this));

            // check for filter updates
            this.grid.on("filterupdate", function () {
                this.filterUpdateFunction(this.gridfilters, this.toolbarFilterInfo);
            }.bind(this));

            gridHelper.applyGridEvents(this.grid);

            this.pagingtoolbar = new Ext.PagingToolbar({
                pageSize: itemsPerPage,
                store: this.store,
                displayInfo: true,
                displayMsg: '{0} - {1} / {2}',
                emptyMsg: t("no_objects_found")
            });

            // add per-page selection
            this.pagingtoolbar.add("-");

            this.pagingtoolbar.add(new Ext.Toolbar.TextItem({
                text: t("items_per_page")
            }));
            this.pagingtoolbar.add(new Ext.form.ComboBox({
                store: [
                    [10, "10"],
                    [20, "20"],
                    [40, "40"],
                    [60, "60"],
                    [80, "80"],
                    [100, "100"],
                    [999999, t("all")]
                ],
                mode: "local",
                width: 50,
                value: itemsPerPage,
                triggerAction: "all",
                listeners: {
                    select: function (box, rec, index) {
                        this.pagingtoolbar.pageSize = intval(rec.data.field1);
                        this.pagingtoolbar.moveFirst();
                    }.bind(this)
                }
            }));

            this.editor = new Ext.Panel({
                layout: "border",
                items: [new Ext.Panel({
                    autoScroll: true,
                    items: [this.grid],
                    region: "center",
                    layout: "fit",
                    bbar: this.pagingtoolbar
                })]
            });

            this.layout.removeAll();
            this.layout.add(this.editor);
            this.layout.doLayout();
        } catch (e) {
            console.log(e);
        }

    },

    getGridConfig: function($super) {
        var config = $super();
        config.onlyDirectChildren = this.onlyDirectChildren;
        config.pageSize = this.pagingtoolbar.pageSize;
        return config;
    },

    onRowContextmenu: function (grid, record, tr, rowIndex, e, eOpts ) {

        //$(grid.getView().getRow(rowIndex)).animate( { backgroundColor: '#E0EAEE' }, 100).animate( {
        //    backgroundColor: '#fff' }, 400);

        var menu = new Ext.menu.Menu();
        var data = grid.getStore().getAt(rowIndex);
        var selectedRows = grid.getSelectionModel().getSelection();

        if (selectedRows.length <= 1) {

            menu.add(new Ext.menu.Item({
                text: t('open'),
                iconCls: "pimcore_icon_open",
                handler: function (data) {
                    pimcore.helpers.openObject(data.data.id, "object");
                }.bind(this, data)
            }));
            menu.add(new Ext.menu.Item({
                text: t('show_in_tree'),
                iconCls: "pimcore_icon_show_in_tree",
                handler: function (data) {
                    try {
                        try {
                            Ext.getCmp("pimcore_panel_tree_objects").expand();
                            var tree = pimcore.globalmanager.get("layout_object_tree");
                            pimcore.helpers.selectPathInTree(tree.tree, data.data.idPath);
                        } catch (e) {
                            console.log(e);
                        }

                    } catch (e2) { console.log(e2); }
                }.bind(grid, data)
            }));
            menu.add(new Ext.menu.Item({
                text: t('delete'),
                iconCls: "pimcore_icon_delete",
                handler: function (data) {
                    var store = this.getStore();
                    pimcore.helpers.deleteObject(data.data.id, store.reload.bind(this.getStore()));
                }.bind(grid, data)
            }));
        } else {
            menu.add(new Ext.menu.Item({
                text: t('open_selected'),
                iconCls: "pimcore_icon_open",
                handler: function (data) {
                    var selectedRows = grid.getSelectionModel().getSelections();
                    for (var i = 0; i < selectedRows.length; i++) {
                        pimcore.helpers.openObject(selectedRows[i].data.id, "object");
                    }
                }.bind(this, data)
            }));

            menu.add(new Ext.menu.Item({
                text: t('delete_selected'),
                iconCls: "pimcore_icon_delete",
                handler: function (data) {
                    var ids = [];
                    var selectedRows = grid.getSelectionModel().getSelections();
                    for (var i = 0; i < selectedRows.length; i++) {
                        ids.push(selectedRows[i].data.id);
                    }
                    ids = ids.join(',');

                    pimcore.helpers.deleteObject(ids, function() {
                            this.getStore().reload();
                            pimcore.globalmanager.get("layout_object_tree").tree.getRootNode().reload();
                        }.bind(this)
                    );
                }.bind(grid, data)
            }));
        }

        e.stopEvent();
        menu.showAt(e.pageX, e.pageY);
    }

});
<|endoftext|>


<commit_before>
// [START app]
'use strict';

// [START setup]

var express = require('express');

var app = express();
var google = require('googleapis');
var bigquery = google.bigquery('v2');

app.enable('trust proxy');

var Datastore = require('@google-cloud/datastore');
//const BigQuery = require('@google-cloud/bigquery');
const projectId = "doolinhomeiot";
const datasetId = "OfficeData";
const tableId = "iotdata";

// Instantiate a datastore client
var datastore = Datastore();

var PubSub = require('@google-cloud/pubsub');

//Instantiate a pubsub client
var pubsub = PubSub();

//The following environment variables are set by app.yaml when running on GAE,
//but will need to be manually set when running locally.
var PUBSUB_VERIFICATION_TOKEN = process.env.PUBSUB_VERIFICATION_TOKEN;

var topic = pubsub.topic(process.env.PUBSUB_TOPIC);

var subscription = pubsub.subscription(process.env.PUBSUB_SUBSCRIPTION_NAME);
google.auth.getApplicationDefault(function(err, authClient) {
    if (err) {
        console.log('Authentication failed because of ', err);
        return;
    }
    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
        var scopes = ['https://www.googleapis.com/auth/cloud-platform'];
        authClient = authClient.createScoped(scopes);
    }
//'insertId': 123456, 'json': '{"nameid": 123,"messagedata":"test1"

//var request = {projectId: projectId,datasetId: datasetId,tableID: tableId,resource: {"kind": "bigquery#tableDataInsertAllRequest","rows":
//    {}, auth: authClient]};

// [END setup]

function storeEvent(message)
{
    var key = datastore.key('officedata');
    key.identifier = "id"
    // You can uncomment some of the other things if you want to store them in the database

    var obj = {
        messageid: message.id
        //deviceid: message.attributes.device_id,
        ////event: message.attributes.event,
        //published: message.attributes.published_at,
        //data: message.data
    }
    datastore.save(
        {
            key: key,
            data: obj
        }, function(err)
        {
            if(err)
            {
                console.log('There was an error storing the event', err);
        }
    console.log('stored in datastore', obj);
        }
    );
    //save to BigQuery Tables
    bigquery.tabledata.insertAll({auth: oath2Client,'projectId': projectId, 'datasetId': datasetId, 'tableId': tableId, 'resource': {"kind": "bigquery#tableDataInsertAllRequest","rows":[{"insertId": 123456, "json": {"nameid": "123","messagedata":"test1"}}]}, func);

        //err: result});

subscription.on('message', function(message) {
    console.log('event received', message);
    // Called every time a message is received.
    // message.id = ID used to acknowledge its receival.
    // message.data = Contents of the message.
    // message.attributes = Attributes of the message.
    storeEvent(message);
    message.ack();
});

// [START listen]
var server = app.listen(process.env.PORT || 8080, function () {
    console.log('App listening on port %s', server.address().port);
    console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;
<commit_msg>Update app.js<commit_after>
// [START app]
'use strict';

// [START setup]

var express = require('express');

var app = express();
var google = require('googleapis');
var bigquery = google.bigquery('v2');

app.enable('trust proxy');

var Datastore = require('@google-cloud/datastore');
//const BigQuery = require('@google-cloud/bigquery');
const projectId = "doolinhomeiot";
const datasetId = "OfficeData";
const tableId = "iotdata";

// Instantiate a datastore client
var datastore = Datastore();

var PubSub = require('@google-cloud/pubsub');

//Instantiate a pubsub client
var pubsub = PubSub();

//The following environment variables are set by app.yaml when running on GAE,
//but will need to be manually set when running locally.
var PUBSUB_VERIFICATION_TOKEN = process.env.PUBSUB_VERIFICATION_TOKEN;

var topic = pubsub.topic(process.env.PUBSUB_TOPIC);

var subscription = pubsub.subscription(process.env.PUBSUB_SUBSCRIPTION_NAME);
google.auth.getApplicationDefault(function(err, authClient) {
    if (err) {
        console.log('Authentication failed because of ', err);
        return;
    }
    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
        var scopes = ['https://www.googleapis.com/auth/cloud-platform'];
        authClient = authClient.createScoped(scopes);
    }
//'insertId': 123456, 'json': '{"nameid": 123,"messagedata":"test1"

//var request = {projectId: projectId,datasetId: datasetId,tableID: tableId,resource: {"kind": "bigquery#tableDataInsertAllRequest","rows":
//    {}, auth: authClient]};

// [END setup]

function storeEvent(message)
{
    var key = datastore.key('officedata');
    key.identifier = "id"
    // You can uncomment some of the other things if you want to store them in the database

    var obj = {
        messageid: message.id
        //deviceid: message.attributes.device_id,
        ////event: message.attributes.event,
        //published: message.attributes.published_at,
        //data: message.data
    }
    datastore.save(
        {
            key: key,
            data: obj
        }, function(err)
        {
            if(err)
            {
                console.log('There was an error storing the event', err);
        }
    console.log('stored in datastore', obj);
        }
    );
    //save to BigQuery Tables
    bigquery.tabledata.insertAll({auth: oath2Client,'projectId': projectId, 'datasetId': datasetId, 'tableId': tableId, 'resource': {"kind": "bigquery#tableDataInsertAllRequest","rows":[{"insertId": 123456, "json": {"nameid": "123","messagedata":"test1"}}]});

        //err: result});

subscription.on('message', function(message) {
    console.log('event received', message);
    // Called every time a message is received.
    // message.id = ID used to acknowledge its receival.
    // message.data = Contents of the message.
    // message.attributes = Attributes of the message.
    storeEvent(message);
    message.ack();
});

// [START listen]
var server = app.listen(process.env.PORT || 8080, function () {
    console.log('App listening on port %s', server.address().port);
    console.log('Press Ctrl+C to quit.');
});
// [END listen]
// [END app]

module.exports = app;
<|endoftext|>