<commit_before>var log = require('../../logging');
var requestUtil = require('./requestUtil');
var responseUtil = require('./responseUtil');
const uuidv4            = require('uuid/v4');
const multiparty        = require('multiparty');
const config            = require('../../config');
const modelsUtil        = require('../../models/util/util');

var INVALID_DATA = 'Invalid data key in body, should be a JSON.';
var INVALID_ID = 'Invalid ID field. Should be an integer.';
var NO_DATAPOINT_FOUND =
  'No datapoint was found with given ID. make sure that you have permissions ' +
  'to view datapoint.';
var NO_FILE_FOUND = 'No file found with given datapoint.';

function getRecordingsFromModel(modelClass, request, response) {

  // Check that if the request was authenticated that is was
  // authenticated by a user JWT, not a device JWT.
  // TODO get passport to do this...
  if (request.user !== null && !requestUtil.isFromAUser(request))
  {return responseUtil.notFromAUser(response);}

  var query = requestUtil.getSequelizeQueryFromHeaders(request);
  if (query.badRequest)
  {return responseUtil.invalidDatapointGet(response, query.badRequest);}

  modelClass
    .findAllWithUser(request.user, query)
    .then((modelInstances) => {
      var result = {
        rows: [],
        limit: modelInstances.limit,
        offset: modelInstances.offset,
        count: modelInstances.count,
      };
      // Just save the front end fields for each model.
      for (var key in modelInstances.rows)
      {result.rows.push(modelInstances.rows[key].getFrontendFields());}

      return responseUtil.validDatapointGet(response, result);
    })
    .catch((error) => catchError(error, response));
}

/**
 * Processes the POST request checking that the request is valid then saving the
 *  metadata in a sequelize model and uploading the file to the file storage.
 * @param {Object} modelClass - Sequelize Model of the type of the recording.
 * @param {Object} request - Express request object.
 * @param {Object} response - Express response object.
 */
function addRecordingFromPost(model, request, response) {
  var device = request.device;
  var modelClass = model;
  var modelInstance;
  var file;

  if (request.device === null) {
    throw { badRequest: "expected device" };
  }

  requestUtil
    .getFileAndDataField(request)
    .then(([data, f]) => {
      file = f;
      // Build model. But limit what fields can be set.
      modelInstance = modelClass.build(data, {
        fields: modelClass.apiSettableFields
      });

      modelInstance.set('DeviceId', device.id);
      modelInstance.set('GroupId', device.GroupId);
      if (typeof device.public == 'boolean') {
        modelInstance.set('public', device.public);
      } else {
        model.setDataValue('public', false);
      }
      return modelInstance.validate();
    })
    .then(() => modelInstance.save())
    .then(() => responseUtil.validRecordingUpload(response, modelInstance.id))
    .then(() => modelInstance.processRecording(file))
    .then((processedFile) => modelInstance.saveFile(processedFile))
    .catch((error) => {
      catchError(error, response, responseUtil.invalidDatapointUpload);
    });
}

function getRecordingFile(modelClass, request, response) {

  // Check that if the request was authenticated that is was
  // authenticated by a user JWT, not a device JWT.
  // TODO get passport to do this...
  if (request.user !== null && !requestUtil.isFromAUser(request))
  {return responseUtil.notFromAUser(response);}

  var id = parseInt(request.params.id);
  if (!id)
  {return responseUtil.invalidDataId(response);}

  modelClass
    .getFileData(id, request.user)
    .then((fileData) => {
      if (fileData === null || fileData.key === null) {
        responseUtil.invalidFileRequest(response, NO_FILE_FOUND);
        throw { badRequest: NO_FILE_FOUND };
      }
      return responseUtil.validFileRequest(response, {
        _type: 'fileDownload',
        key: fileData.key,
        filename: fileData.name,
        mimeType: fileData.mimeType,
      });
    })
    .catch((error) => {
      catchError(error, response, responseUtil.invalidDatapointGet);
    });
}

function updateDataFromPut(modelClass, request, response) {

  if (!requestUtil.isFromAUser(request)) {
    return responseUtil.notFromAUser(response);
  }

  var data = parseJsonFromString(request.body.data);
  if (data === null) {
    return responseUtil.invalidDatapointUpdate(response, INVALID_DATA);
  }

  var id = parseInt(request.params.id);
  if (!id) {
    return responseUtil.invalidDatapointUpdate(response, INVALID_ID);
  }

  modelClass
    .findAllWithUser(request.user, { where: { id: id } })
    .then((modelInstances) => {
      var modelInstance = modelInstances.rows[0];
      if (modelInstance === null || modelInstance === undefined) {
        responseUtil.invalidDatapointUpdate(response, NO_DATAPOINT_FOUND);
        throw { badRequest: NO_DATAPOINT_FOUND };
      }
      return modelInstance.update(data, {
        fields: modelClass.apiUpdateableFields
      });
    })
    .then(() => responseUtil.validDatapointUpdate(response))
    .catch((error) => {
      catchError(error, response, responseUtil.invalidDatapointUpdate);
    });
}

function deleteDataPoint(modelClass, request, response) {
  if (!requestUtil.isFromAUser(request))
  {return responseUtil.notFromAUser(response);}

  var id = parseInt(request.params.id);
  if (!id)
  {return responseUtil.invalidDataId(response);}

  modelClass
    .deleteModelInstance(id, request.user)
    .then(() => responseUtil.validDatapointDelete(response))
    .catch(err => {
      catchError(err, response, responseUtil.invalidDatapointDelete);
    });
}

// Returns a JSON of the string, if parsing to a JSON failes null is returned.
function parseJsonFromString(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    log.debug("Could not parse string to JSON: ", jsonString);
    return null;
  }
}

function catchError(error, response, responseFunction) {
  if (error.badRequest) {
    responseFunction(response, error.badRequest);
    return log.info('Bad request: ', error.badRequest);
  }
  if (error.name === 'SequelizeValidationError') {
    responseFunction(response, error.message);
    return log.info('Bad request: ', error.message);
  }
  return responseUtil.serverError(response, error);
}

function multipartDownload(recordTypeName, buildRecord){
  return (request, response) => {
    var key = uuidv4();
    var data;
    var upload;

    // Note regarding multiparty: there are no guarantees about the
    // order that the field and part handlers will be called. You need
    // to formulate the response to the client in the close handler.
    var form = new multiparty.Form();

    // Handle the "data" field.
    form.on('field', (name, value) => {
      if (name != 'data') {
        return;
      }

      try {
        data = JSON.parse(value);
      } catch (err) {
        // This leaves `data` unset so that the close handler (below)
        // will fail the upload.
        log.error("invalid 'data' field:", err);
      }
    });

    // Handle the "file" part.
    form.on('part', (part) => {
      if (part.name != 'file') {
        part.resume();
        return;
      }

      upload = modelsUtil.openS3().upload({
        Bucket: config.s3.bucket,
        Key: key,
        Body: part,
      }).promise()
        .catch((err) => {
          return err;
        });
      log.debug('started streaming upload to bucket...');
    });

    // Handle any errors. If this is called, the close handler
    // shouldn't be.
    form.on('error', (err) => {
      responseUtil.serverError(response, err);
    });

    // This gets called once all fields and parts have been read.
    form.on('close', async () => {
      if (!data) {
        log.error("upload missing 'data' field");
        responseUtil.invalidDatapointUpload(response);
        return;
      }
      if (!upload) {
        log.error("upload was never started");
        responseUtil.invalidDatapointUpload(response);
        return;
      }

      var dbRecord;
      try {
        // Wait for the upload to complete.
        var uploadResult = await upload;
        if (uploadResult instanceof Error) {
          responseUtil.serverError(response, uploadResult);
          return;
        }
        log.info("finished streaming upload to object store. key:", key);

        // Store a record for the upload.
        dbRecord = buildRecord(request, data, key);
        await dbRecord.validate();
        await dbRecord.save();
      } catch (err) {
        responseUtil.serverError(response, err);
        return;
      }
      responseUtil.validRecordingUpload(response, dbRecord.id);
    });

    form.parse(request);
  };
}

exports.getRecordingsFromModel = getRecordingsFromModel;
exports.addRecordingFromPost = addRecordingFromPost;
exports.updateDataFromPut = updateDataFromPut;
exports.getRecordingFile = getRecordingFile;
exports.deleteDataPoint = deleteDataPoint;
exports.parseJsonFromString = parseJsonFromString;
exports.handleResponse = responseUtil.send;
exports.catchError = catchError;
exports.multipartDownload = multipartDownload;
<commit_msg>Avoid double response when audio recording not found<commit_after>var log = require('../../logging');
var requestUtil = require('./requestUtil');
var responseUtil = require('./responseUtil');
const uuidv4            = require('uuid/v4');
const multiparty        = require('multiparty');
const config            = require('../../config');
const modelsUtil        = require('../../models/util/util');

var INVALID_DATA = 'Invalid data key in body, should be a JSON.';
var INVALID_ID = 'Invalid ID field. Should be an integer.';
var NO_DATAPOINT_FOUND =
  'No datapoint was found with given ID. make sure that you have permissions ' +
  'to view datapoint.';
var NO_FILE_FOUND = 'No file found with given datapoint.';

function getRecordingsFromModel(modelClass, request, response) {

  // Check that if the request was authenticated that is was
  // authenticated by a user JWT, not a device JWT.
  // TODO get passport to do this...
  if (request.user !== null && !requestUtil.isFromAUser(request))
  {return responseUtil.notFromAUser(response);}

  var query = requestUtil.getSequelizeQueryFromHeaders(request);
  if (query.badRequest)
  {return responseUtil.invalidDatapointGet(response, query.badRequest);}

  modelClass
    .findAllWithUser(request.user, query)
    .then((modelInstances) => {
      var result = {
        rows: [],
        limit: modelInstances.limit,
        offset: modelInstances.offset,
        count: modelInstances.count,
      };
      // Just save the front end fields for each model.
      for (var key in modelInstances.rows)
      {result.rows.push(modelInstances.rows[key].getFrontendFields());}

      return responseUtil.validDatapointGet(response, result);
    })
    .catch((error) => catchError(error, response));
}

/**
 * Processes the POST request checking that the request is valid then saving the
 *  metadata in a sequelize model and uploading the file to the file storage.
 * @param {Object} modelClass - Sequelize Model of the type of the recording.
 * @param {Object} request - Express request object.
 * @param {Object} response - Express response object.
 */
function addRecordingFromPost(model, request, response) {
  var device = request.device;
  var modelClass = model;
  var modelInstance;
  var file;

  if (request.device === null) {
    throw { badRequest: "expected device" };
  }

  requestUtil
    .getFileAndDataField(request)
    .then(([data, f]) => {
      file = f;
      // Build model. But limit what fields can be set.
      modelInstance = modelClass.build(data, {
        fields: modelClass.apiSettableFields
      });

      modelInstance.set('DeviceId', device.id);
      modelInstance.set('GroupId', device.GroupId);
      if (typeof device.public == 'boolean') {
        modelInstance.set('public', device.public);
      } else {
        model.setDataValue('public', false);
      }
      return modelInstance.validate();
    })
    .then(() => modelInstance.save())
    .then(() => responseUtil.validRecordingUpload(response, modelInstance.id))
    .then(() => modelInstance.processRecording(file))
    .then((processedFile) => modelInstance.saveFile(processedFile))
    .catch((error) => {
      catchError(error, response, responseUtil.invalidDatapointUpload);
    });
}

function getRecordingFile(modelClass, request, response) {
  // Check that if the request was authenticated that is was
  // authenticated by a user JWT, not a device JWT.
  // TODO get passport to do this...
  if (request.user !== null && !requestUtil.isFromAUser(request)) {
    responseUtil.notFromAUser(response);
    return;
  }

  var id = parseInt(request.params.id);
  if (!id) {
    responseUtil.invalidDataId(response);
    return;
  }

  modelClass
    .getFileData(id, request.user)
    .then((fileData) => {
      if (fileData === null || fileData.key === null) {
        throw { badRequest: NO_FILE_FOUND };
      }
      responseUtil.validFileRequest(response, {
        _type: 'fileDownload',
        key: fileData.key,
        filename: fileData.name,
        mimeType: fileData.mimeType,
      });
    })
    .catch((error) => {
      catchError(error, response, responseUtil.invalidDatapointGet);
    });
}

function updateDataFromPut(modelClass, request, response) {

  if (!requestUtil.isFromAUser(request)) {
    return responseUtil.notFromAUser(response);
  }

  var data = parseJsonFromString(request.body.data);
  if (data === null) {
    return responseUtil.invalidDatapointUpdate(response, INVALID_DATA);
  }

  var id = parseInt(request.params.id);
  if (!id) {
    return responseUtil.invalidDatapointUpdate(response, INVALID_ID);
  }

  modelClass
    .findAllWithUser(request.user, { where: { id: id } })
    .then((modelInstances) => {
      var modelInstance = modelInstances.rows[0];
      if (modelInstance === null || modelInstance === undefined) {
        responseUtil.invalidDatapointUpdate(response, NO_DATAPOINT_FOUND);
        throw { badRequest: NO_DATAPOINT_FOUND };
      }
      return modelInstance.update(data, {
        fields: modelClass.apiUpdateableFields
      });
    })
    .then(() => responseUtil.validDatapointUpdate(response))
    .catch((error) => {
      catchError(error, response, responseUtil.invalidDatapointUpdate);
    });
}

function deleteDataPoint(modelClass, request, response) {
  if (!requestUtil.isFromAUser(request))
  {return responseUtil.notFromAUser(response);}

  var id = parseInt(request.params.id);
  if (!id)
  {return responseUtil.invalidDataId(response);}

  modelClass
    .deleteModelInstance(id, request.user)
    .then(() => responseUtil.validDatapointDelete(response))
    .catch(err => {
      catchError(err, response, responseUtil.invalidDatapointDelete);
    });
}

// Returns a JSON of the string, if parsing to a JSON failes null is returned.
function parseJsonFromString(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    log.debug("Could not parse string to JSON: ", jsonString);
    return null;
  }
}

function catchError(error, response, responseFunction) {
  if (error.badRequest) {
    responseFunction(response, error.badRequest);
    return log.info('Bad request: ', error.badRequest);
  }
  if (error.name === 'SequelizeValidationError') {
    responseFunction(response, error.message);
    return log.info('Bad request: ', error.message);
  }
  return responseUtil.serverError(response, error);
}

function multipartDownload(recordTypeName, buildRecord){
  return (request, response) => {
    var key = uuidv4();
    var data;
    var upload;

    // Note regarding multiparty: there are no guarantees about the
    // order that the field and part handlers will be called. You need
    // to formulate the response to the client in the close handler.
    var form = new multiparty.Form();

    // Handle the "data" field.
    form.on('field', (name, value) => {
      if (name != 'data') {
        return;
      }

      try {
        data = JSON.parse(value);
      } catch (err) {
        // This leaves `data` unset so that the close handler (below)
        // will fail the upload.
        log.error("invalid 'data' field:", err);
      }
    });

    // Handle the "file" part.
    form.on('part', (part) => {
      if (part.name != 'file') {
        part.resume();
        return;
      }

      upload = modelsUtil.openS3().upload({
        Bucket: config.s3.bucket,
        Key: key,
        Body: part,
      }).promise()
        .catch((err) => {
          return err;
        });
      log.debug('started streaming upload to bucket...');
    });

    // Handle any errors. If this is called, the close handler
    // shouldn't be.
    form.on('error', (err) => {
      responseUtil.serverError(response, err);
    });

    // This gets called once all fields and parts have been read.
    form.on('close', async () => {
      if (!data) {
        log.error("upload missing 'data' field");
        responseUtil.invalidDatapointUpload(response);
        return;
      }
      if (!upload) {
        log.error("upload was never started");
        responseUtil.invalidDatapointUpload(response);
        return;
      }

      var dbRecord;
      try {
        // Wait for the upload to complete.
        var uploadResult = await upload;
        if (uploadResult instanceof Error) {
          responseUtil.serverError(response, uploadResult);
          return;
        }
        log.info("finished streaming upload to object store. key:", key);

        // Store a record for the upload.
        dbRecord = buildRecord(request, data, key);
        await dbRecord.validate();
        await dbRecord.save();
      } catch (err) {
        responseUtil.serverError(response, err);
        return;
      }
      responseUtil.validRecordingUpload(response, dbRecord.id);
    });

    form.parse(request);
  };
}

exports.getRecordingsFromModel = getRecordingsFromModel;
exports.addRecordingFromPost = addRecordingFromPost;
exports.updateDataFromPut = updateDataFromPut;
exports.getRecordingFile = getRecordingFile;
exports.deleteDataPoint = deleteDataPoint;
exports.parseJsonFromString = parseJsonFromString;
exports.handleResponse = responseUtil.send;
exports.catchError = catchError;
exports.multipartDownload = multipartDownload;
<|endoftext|>


<commit_before>$(document).ready(function() {

    $('#id_degree_programme_options').change(function() {
        console.log('hello');
        if (this.value === 'extra') {
            $('#unknown_degree').show();
            $('#unknown_degree input').val('');
        } else {
            $('#unknown_degree').hide();
            $('#unknown_degree input').val(this.value);
        }
    });

});
<commit_msg>Use existing id instead of selector in JS<commit_after>$(document).ready(function() {

    $('#id_degree_programme_options').change(function() {
        console.log('hello');
        if (this.value === 'extra') {
            $('#unknown_degree').show();
            $('#id_degree_programme').val('');
        } else {
            $('#unknown_degree').hide();
            $('#id_degree_programme').val(this.value);
        }
    });

});
<|endoftext|>


<commit_before>var React = require('react-native');
var Collapsible = require('react-native-collapsible');
var Accordion = require('react-native-collapsible/Accordion')
var styles = require('../stylesheets/layout');
var Header = require('./header');

var {
  View,
  ListView,
  Text,
  Image,
  TouchableHighlight
} = React;

var EventDetail = React.createClass({
  getInitialState: function() {
    return {
      scenarios: [],
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  },

  componentDidMount: function() {
    this.fetchData();
  },

  fetchData: function() {
    var event_id = this.props.bet_event.id;
    var Event_URL = 'http:/localhost:3000/events/' + event_id + '/scenarios';
    fetch(Event_URL)
    .then((response) => response.json())
    .then((responseData) => {
      this.setState({
        scenarios: responseData,
        dataSource: this.state.dataSource.cloneWithRows(responseData),
        loaded: true,
      });
      console.log(responseData);
    })
    .done();
  },

  goBack() {
    this.props.navigator.pop();
  },

  goToScenario: function(scenario) {
    this.props.navigator.push({
      component: ScenarioDetail,
      passProps: {
        scenario: scenario,
      }
    });
  },

  renderScenarios: function(scenario) {
    return (
      <TouchableHighlight onPress={this.goToScenario.bind(this, scenario)}>
        <View>
          <View style={styles.container}>
          <Text style={styles.bodyText}>{scenario.question}</Text>
          </View>
        <View style={styles.separator} />
        </View>
      </TouchableHighlight>
    )
  },

  renderDropdown: function(scenario) {
    return (
      <View>
        <Text style={styles.bodyText2}>"A bid of 2 bitcoins will net you 6 bitcoins if you win!"</Text>
      </View>

    )
  },

  renderHeader: function(scenario) {
    var yv = scenario.yes_votes,
     nv = scenario.no_votes,
     wd = scenario.wager_difference;
    return (
      <View>
      <View style={styles.container}>
        <Text style={styles.bodyText}>{scenario.question}</Text>
          <Text style={{color: 'green', fontWeight: 'bold'}}>Yes: {yv}</Text>
          <Text style={{color: 'red', fontWeight: 'bold'}}>No: {nv} </Text>
          <Text style={{color: 'blue', fontWeight: 'bold'}}>Wager Difference: {wd}</Text>
          <Text>___________________________________________________</Text>
      </View>
      <View style={styles.separator} />
      </View>
    )
  },

  render() {
    return (
      <Image style={styles.imageBackground} source={{uri: 'http://i.imgur.com/YZWUKAq.jpg'}}>
      <Header/>
      <View style={styles.container}>
      <View style={{color: '#FFFFFF'}}>
        <Accordion
          sections={this.state.scenarios}
          renderHeader={this.renderHeader}
          renderContent={this.renderDropdown}
        />
      </View>
      </View>
      </Image>
    );
  }
});

module.exports = EventDetail;<commit_msg>Randomly increment votes<commit_after>var React = require('react-native');
var Collapsible = require('react-native-collapsible');
var Accordion = require('react-native-collapsible/Accordion')
var styles = require('../stylesheets/layout');
var Header = require('./header');

var {
  View,
  ListView,
  Text,
  Image,
  TouchableHighlight
} = React;

var EventDetail = React.createClass({
  getInitialState: function() {
    return {
      scenarios: [],
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
      loaded: false,
    };
  },

  componentDidMount: function() {
    this.fetchData();
  },

  fetchData: function() {
    var event_id = this.props.bet_event.id;
    var Event_URL = 'http:/localhost:3000/events/' + event_id + '/scenarios';
    fetch(Event_URL)
    .then((response) => response.json())
    .then((responseData) => {
      this.setState({
        scenarios: responseData,
        dataSource: this.state.dataSource.cloneWithRows(responseData),
        loaded: true,
      });
      console.log(responseData);
    })
    .done();
  },

  goBack() {
    this.props.navigator.pop();
  },

  goToScenario: function(scenario) {
    this.props.navigator.push({
      component: ScenarioDetail,
      passProps: {
        scenario: scenario,
      }
    });
  },

  renderScenarios: function(scenario) {
    return (
      <TouchableHighlight onPress={this.goToScenario.bind(this, scenario)}>
        <View>
          <View style={styles.container}>
          <Text style={styles.bodyText}>{scenario.question}</Text>
          </View>
        <View style={styles.separator} />
        </View>
      </TouchableHighlight>
    )
  },

  renderDropdown: function(scenario) {
    return (
      <View>
        <Text style={styles.bodyText2}>"A bid of 2 bitcoins will net you 6 bitcoins if you win!"</Text>
      </View>

    )
  },

  // testBets: function(scenario) {
  //   var ticker = setInterval(testBets, 2000);
  //   console.log(ticker);
  //   console.log("HITTTT");
  //   var array = [yv, nv];
  //   var increment = array[Math.floor(Math.random()*items.length)] + 1;

  //   return (
  //     <View>
  //     <View style={styles.container}>
  //       <Text style={styles.bodyText}>{scenario.question}</Text>
  //         <Text style={{color: 'green', fontWeight: 'bold'}}>Yes: {yv}</Text>
  //         <Text style={{color: 'red', fontWeight: 'bold'}}>No: {nv} </Text>
  //         <Text style={{color: 'blue', fontWeight: 'bold'}}>Wager Difference: {wager_random}</Text>
  //         <Text>___________________________________________________</Text>
  //     </View>
  //     <View style={styles.separator} />
  //     </View>
  //   )
  // },

  renderHeader: function(scenario) {
    var wagers = [-5000, 0,2000,8750, -6500, 3500,0,0,0];
    var wager_random = wagers[Math.floor(Math.random()*wagers.length)];
    var yv = scenario.yes_votes,
     nv = scenario.no_votes;
    var i = Math.floor(Math.random() * 2);
    if (i > 0){
      scenario.yes_votes++;
    } else {
      scenario.no_votes++;
    }
    return (
      <View>
      <View style={styles.container}>
        <Text style={styles.bodyText}>{scenario.question}</Text>
          <Text style={{color: 'green', fontWeight: 'bold'}}>{scenario.yes_votes} yes</Text>
          <Text style={{color: 'red', fontWeight: 'bold'}}>{scenario.no_votes} no</Text>
          <Text style={{color: 'blue', fontWeight: 'bold'}}>Wager Difference: {wager_random}</Text>
          <Text>___________________________________________________</Text>
      </View>
      <View style={styles.separator} />
      </View>
    )
  },

  render() {
    return (
      <Image style={styles.imageBackground} source={{uri: 'http://i.imgur.com/YZWUKAq.jpg'}}>
      <Header/>
      <View style={styles.container}>
      <View style={{color: '#FFFFFF'}}>
        <Accordion
          sections={this.state.scenarios}
          renderHeader={this.renderHeader}
          renderContent={this.renderDropdown}
          renderRow={this.testBets}/>
      </View>
      </View>
      </Image>
    );
  }
});

module.exports = EventDetail;
<|endoftext|>


<commit_before>/**
 * web-T::Framework Languages module
 * @author goshi
 */

webtFramework.inject({

    trans : function(what){

        if (!what)
            return null;

        var w = what.split('.'), found = false;

        if (window['ph']){

            var level = window['ph'];
            for (var i in w){
                if (typeof level[w[i]] != 'undefined' && level[w[i]] !== null){
                    level = level[w[i]];
                } else {
                    return what;
                }
            }

            return level;

        }

        return what;

    }
});
<commit_msg>now languages module can translate in plural form<commit_after>/**
 * web-T::Framework Languages module
 * @author goshi
 */

webtFramework.inject({

    trans : function(what){

        if (!what)
            return null;

        var w = what.split('.'), found = false;

        if (window['ph']){

            var level = window['ph'];
            for (var i in w){
                if (typeof level[w[i]] != 'undefined' && level[w[i]] !== null){
                    level = level[w[i]];
                } else {
                    return what;
                }
            }

            return level;

        }

        return what;

    },

    transPlural: function(what, value){

        if (typeof value == 'undefined' || !value)
            value = 0;

        var mess = this.trans(what);

        // getting days count
        var d_cnt = Math.abs(value) % 100;
        var n1 = d_cnt % 10;
        if (d_cnt > 10 && d_cnt < 20) return typeof mess[5] != 'undefined' ? mess[5] : mess[1];
        if (n1 > 1 && n1 < 5) return mess[2];
        if (n1 == 1)
            return mess[1];
        else
            return typeof mess[5] != 'undefined' ? mess[5] : mess[2];

    }
});
<|endoftext|>


<commit_before>Prism.languages.csharp = Prism.languages.extend('clike', {
	'keyword': /\b(abstract|as|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|async|await|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b/,
	'string': [
		/@("|')(\1\1|\\\1|\\?(?!\1)[\s\S])*\1/,
		/("|')(\\?.)*?\1/
	],
	'number': /\b-?(0x[\da-f]+|\d*\.?\d+)\b/i
});

Prism.languages.insertBefore('csharp', 'keyword', {
	'preprocessor': {
		pattern: /(^\s*)#.*/m,
		lookbehind: true,
		alias: 'property',
		inside: {
			// highlight preprocessor directives as keywords
			'directive': {
				pattern: /(\s*#)\b(define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/,
				lookbehind: true,
				alias: 'keyword'
			}
		}
	}
});
<commit_msg>Fixed detection of float numbers.<commit_after>Prism.languages.csharp = Prism.languages.extend('clike', {
	'keyword': /\b(abstract|as|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|async|await|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b/,
	'string': [
		/@("|')(\1\1|\\\1|\\?(?!\1)[\s\S])*\1/,
		/("|')(\\?.)*?\1/
	],
	'number': /\b-?(0x[\da-f]+|\d*\.?\d+f?)\b/i
});

Prism.languages.insertBefore('csharp', 'keyword', {
	'preprocessor': {
		pattern: /(^\s*)#.*/m,
		lookbehind: true,
		alias: 'property',
		inside: {
			// highlight preprocessor directives as keywords
			'directive': {
				pattern: /(\s*#)\b(define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/,
				lookbehind: true,
				alias: 'keyword'
			}
		}
	}
});
<|endoftext|>


<commit_before>import SiteStructureEnvironment from './environments/SiteStructureEnvironment';
import MaterialsEnvironment from './environments/MaterialsEnvironment';
import CustomizationEnvironment from './environments/CustomizationEnvironment';
import ActionEnvironment from './environments/ActionEnvironment';
import PageStructureEnvironment from './environments/PageStructureEnvironment';
import FrameApi from './../utils/FrameApi';

class VisualBuilder {
  constructor() {
    this.params();
    this.resolutionSwitcher();

    this.environments = new Map([
      ['site-structure', new SiteStructureEnvironment(this, 'site-structure')],
      ['page-structure', new PageStructureEnvironment(this, 'page-structure')],
      ['materials', new MaterialsEnvironment(this, 'materials')],
      ['customization', new CustomizationEnvironment(this, 'customization')],
      ['action', new ActionEnvironment(this, 'action')],
    ]);

    this.environmentSelector();

    // select first environment by default
    this.switchEnvironment('structure');
    $('.monster-environment-selector__environment-link')
      .first()
      .addClass('monster-environment-selector__environment-link--active');
    FrameApi.bindMessageListener(this);
  }

  /**
   * Sets VisualBuilder settings.
   * Uses VisualBuilderSettings variable if provided or default values instead.
   */
  params() {
    const userSettings = window.VisualBuilderSettings || {};
    const settings = {
      'element-selector': '.monster-visual-builder',
      'frame-selector': '.monster-visual-frame',
      'materials': {},
      'groups': {},
      'stackable-container-class': 'monster-stackable-container',
      'new-block-url': '/monster/visual-builder/new-block',
    };
    for (const key in userSettings) {
      if (userSettings.hasOwnProperty(key)) {
        settings[key] = userSettings[key];
      }
    }
    this.settings = settings;
    this.$builder = $(this.settings['element-selector']);
    this.$stackable = $('.' + this.settings['stackable-container-class']);
  }

  resolutionSwitcher() {
    const that = this;
    const bemElem = 'resolution-switcher__resolution-link';
    const activeModifier = `${bemElem}--active`;
    const $resolutionLinks = $(`.${bemElem}`);
    $resolutionLinks.click(function callback() {
      $resolutionLinks.removeClass(activeModifier);
      $(that.settings['frame-selector']).width($(this).data('resolutionWidth'));
      $(this).addClass(activeModifier);
      return false;
    });
  }

  environmentSelector() {
    const that = this;
    const bemElem = 'monster-environment-selector__environment-link';
    const activeModifier = `${bemElem}--active`;
    const $sectionLinks = $(`.${bemElem}`);
    $sectionLinks.click(function callback() {
      const environmentName = $(this).data('environmentName');
      if (that.currentEnvironment === environmentName) {
        return false;
      }

      $sectionLinks.removeClass(activeModifier);
      that.switchEnvironment(environmentName);
      $(this).addClass(activeModifier);
      return false;
    });
  }

  switchEnvironment(environmentName) {
    this.environments.get(environmentName).activate();
    this.currentEnvironment = environmentName;
  }

  clearStackable() {
    this.$stackable.empty();
  }

  createStackablePane() {
    const paneClass = `${this.settings['stackable-container-class']}__pane`;
    const modifier = this.$stackable.find('.' + paneClass).length === 0 ? `${paneClass}--first` : '';
    const $newPane = $(`<div class="${paneClass} ${modifier}"></div>`);
    this.$stackable.append($newPane);
    return $newPane;
  }

  materialByName(name) {
    if (this.settings.materials.hasOwnProperty(name)) {
      return this.settings.materials[name];
    }
    return null;
  }

  get frameContentWindow() {
    return $(this.settings['frame-selector'])[0].contentWindow;
  }

  serialize() {
    FrameApi.sendMessage(this.frameContentWindow, 'serializeContent', ['log']);
  }

  log(result) {
    console.log(result);
  }
}

export default VisualBuilder;
<commit_msg>bugfix<commit_after>import SiteStructureEnvironment from './environments/SiteStructureEnvironment';
import MaterialsEnvironment from './environments/MaterialsEnvironment';
import CustomizationEnvironment from './environments/CustomizationEnvironment';
import ActionEnvironment from './environments/ActionEnvironment';
import PageStructureEnvironment from './environments/PageStructureEnvironment';
import FrameApi from './../utils/FrameApi';

class VisualBuilder {
  constructor() {
    this.params();
    this.resolutionSwitcher();

    this.environments = new Map([
      ['site-structure', new SiteStructureEnvironment(this, 'site-structure')],
      ['page-structure', new PageStructureEnvironment(this, 'page-structure')],
      ['materials', new MaterialsEnvironment(this, 'materials')],
      ['customization', new CustomizationEnvironment(this, 'customization')],
      ['action', new ActionEnvironment(this, 'action')],
    ]);

    this.environmentSelector();

    // select first environment by default
    this.switchEnvironment('site-structure');
    $('.monster-environment-selector__environment-link')
      .first()
      .addClass('monster-environment-selector__environment-link--active');
    FrameApi.bindMessageListener(this);
  }

  /**
   * Sets VisualBuilder settings.
   * Uses VisualBuilderSettings variable if provided or default values instead.
   */
  params() {
    const userSettings = window.VisualBuilderSettings || {};
    const settings = {
      'element-selector': '.monster-visual-builder',
      'frame-selector': '.monster-visual-frame',
      'materials': {},
      'groups': {},
      'stackable-container-class': 'monster-stackable-container',
      'new-block-url': '/monster/visual-builder/new-block',
    };
    for (const key in userSettings) {
      if (userSettings.hasOwnProperty(key)) {
        settings[key] = userSettings[key];
      }
    }
    this.settings = settings;
    this.$builder = $(this.settings['element-selector']);
    this.$stackable = $('.' + this.settings['stackable-container-class']);
  }

  resolutionSwitcher() {
    const that = this;
    const bemElem = 'resolution-switcher__resolution-link';
    const activeModifier = `${bemElem}--active`;
    const $resolutionLinks = $(`.${bemElem}`);
    $resolutionLinks.click(function callback() {
      $resolutionLinks.removeClass(activeModifier);
      $(that.settings['frame-selector']).width($(this).data('resolutionWidth'));
      $(this).addClass(activeModifier);
      return false;
    });
  }

  environmentSelector() {
    const that = this;
    const bemElem = 'monster-environment-selector__environment-link';
    const activeModifier = `${bemElem}--active`;
    const $sectionLinks = $(`.${bemElem}`);
    $sectionLinks.click(function callback() {
      const environmentName = $(this).data('environmentName');
      if (that.currentEnvironment === environmentName) {
        return false;
      }

      $sectionLinks.removeClass(activeModifier);
      that.switchEnvironment(environmentName);
      $(this).addClass(activeModifier);
      return false;
    });
  }

  switchEnvironment(environmentName) {
    this.environments.get(environmentName).activate();
    this.currentEnvironment = environmentName;
  }

  clearStackable() {
    this.$stackable.empty();
  }

  createStackablePane() {
    const paneClass = `${this.settings['stackable-container-class']}__pane`;
    const modifier = this.$stackable.find('.' + paneClass).length === 0 ? `${paneClass}--first` : '';
    const $newPane = $(`<div class="${paneClass} ${modifier}"></div>`);
    this.$stackable.append($newPane);
    return $newPane;
  }

  materialByName(name) {
    if (this.settings.materials.hasOwnProperty(name)) {
      return this.settings.materials[name];
    }
    return null;
  }

  get frameContentWindow() {
    return $(this.settings['frame-selector'])[0].contentWindow;
  }

  serialize() {
    FrameApi.sendMessage(this.frameContentWindow, 'serializeContent', ['log']);
  }

  log(result) {
    console.log(result);
  }
}

export default VisualBuilder;
<|endoftext|>


<commit_before>import { SubmissionError } from 'redux-form'

// Copied from @mindhive/meteor (because we don't want to import it just for this)
const VALIDATION_ERROR = 'validation-error'

const REDUX_FORM_GLOBAL_ERROR_KEY = '_error'

const rethrowAsSubmissionError = (e) => {
  if (e.reason) {
    const fieldKey = (e.error === VALIDATION_ERROR && e.details) || REDUX_FORM_GLOBAL_ERROR_KEY
    throw new SubmissionError({
      [fieldKey]: e.reason,
    })
  } else {
    console.error('Unexpected error type from submit', e, e.stack)  // eslint-disable-line no-console
    throw e
  }
}

export const asSubmissionError = (promiseOrCreator) =>
  typeof promiseOrCreator === 'function' ?
    (...args) => {  // eslint-disable-line consistent-return
      try {
        return promiseOrCreator(...args).catch(rethrowAsSubmissionError)
      } catch (e) {
        rethrowAsSubmissionError(e)
      }
    }
    : promiseOrCreator.catch(rethrowAsSubmissionError)

<commit_msg>Changing asSubmissionError to be better suited for async/await<commit_after>import { SubmissionError } from 'redux-form'

// Copied from @mindhive/meteor (because we don't want to import it just for this)
const VALIDATION_ERROR = 'validation-error'

const REDUX_FORM_GLOBAL_ERROR_KEY = '_error'

export const asSubmissionError = (e) => {
  if (e.reason) {
    const fieldKey = (e.error === VALIDATION_ERROR && e.details) || REDUX_FORM_GLOBAL_ERROR_KEY
    throw new SubmissionError({
      [fieldKey]: e.reason,
    })
  } else {
    console.error('Unexpected error type from submit', e, e.stack)  // eslint-disable-line no-console
    throw e
  }
}
<|endoftext|>


<commit_before>var google = {
    url: `http://mt{1-3}.google.cn/vt/lyrs=h&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}`
};<commit_msg>卫星地图接口<commit_after>var google = {
    url: `http://mt{1-3}.google.cn/vt/lyrs=h&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}`,
    url: `http://mt{1-3}.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}`
};<|endoftext|>


<commit_before>#!/usr/bin/env node

if (process.env['NPM_LOCKDOWN_RUNNING']) process.exit(0);

console.log("NPM Lockdown is here to check your dependencies!  Never fear!");

var http = require('http'),
    crypto = require('crypto'),
    exec = require('child_process').exec,
    fs = require('fs'),
    path = require('path');

try {
  var lockdownJson = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'lockdown.json')));
} catch(e) {
  console.log("\nERROR: I cannot read lockdown.json!  run node_modules/.bin/lockdown-relock to generate!\n");
  process.exit(1);
}

var boundPort;

// during execution fatal errors will be appended to this list
var errors = [];

// during execution non-fatal warnings will be appended to this list
var warn = [];

function rewriteURL(u) {
    return u.replace('registry.npmjs.org', '127.0.0.1:' + boundPort);
}

function packageOk(name, ver, sha, required) {
  if (!lockdownJson[name]) {
    if (required) {
      errors.push("package '" + name + "' not in lockdown.json!");
    }
    return false;
  }

  if (lockdownJson[name][ver] === undefined) {
    if (required) {
      errors.push("package version " + name + "@" + ver + " not in lockdown.json!");
    }
    return false;
  }

  // a '*' shasum is not checked
  var wantSHA = lockdownJson[name][ver];
  if (wantSHA !== '*' && wantSHA !== sha) {
    if (required) {
      errors.push("package " + name + "@" + ver + " has a different checksum (" +
                  wantSHA + " v. " + sha + ")");
    }
    return false;
  }

  if (wantSHA === '*') {
    warn.push("Lockdown cannot guarantee your saftey!  No sha for pkg " + name + "@" + ver +
              " in lockdown.json");
  }

  return true;
}

function rewriteVersionMD(json) {
  if (typeof json === 'string') json = JSON.parse(json);
  if (!json.error) {
    json.dist.tarball = rewriteURL(json.dist.tarball);

    // is the name/version/sha in our lockdown.json?
    if (!packageOk(json.name, json.version, json.dist.shasum, true)) return null;
  }
  return JSON.stringify(json);
}

function rewritePackageMD(json) {
  if (typeof json === 'string') json = JSON.parse(json);
  if (!json.error) {
    Object.keys(json.versions).forEach(function(ver) {
      var data = json.versions[ver];
      var name = data.name;
      var sha = data.dist ? data.dist.shasum : undefined;

      if (packageOk(name, ver, sha, false)) {
        data.dist.tarball = rewriteURL(data.dist.tarball);
      } else {
        delete json.versions[ver];
      }
    });
  }
  return JSON.stringify(json);
}

var server = http.createServer(function (req, res) {
  if (req.method !== 'GET') {
    return res.end('non GET requests not supported', 501);
  }

  // what type of request is this?
  // 1. specific version json metadata (when explicit dependency is expressed)
  //    - for these requests we should verify the name/version/sha advertised is allowed
  // 2. package version json metadata (when version range is expressed - including '*')
  //    XXX: for these requests we should prune all versions that are not allowed
  // 3. tarball - actual bits
  //    XXX: for these requests we should verify the name/version/sha matches something
  //         allowed, otherwise block the transaction
  var arr = req.url.substr(1).split('/');
  var type = [ '', 'package_metadata', 'version_metadata', 'tarball' ][arr.length];

  // let's extract pkg name and version sensitive to the type of request being performed.
  var pkgname, pkgver;
  if (type === 'tarball') {
    pkgname = arr[0];
    var getVer = new RegExp("^" + pkgname + "-(.*)\\.tgz$");
    pkgver = getVer.exec(arr[2])[1];
  } else if (type === 'version_metadata') {
    pkgname = arr[0];
    pkgver = arr[1];
  } else if (type === 'package_metadata') {
    pkgname = arr[0];
  }

  var hash = crypto.createHash('sha1');

  var r = http.request({
    host: 'registry.npmjs.org',
    port: 80,
    method: req.method,
    path: req.url,
    agent: false
  }, function(rres) {
    res.setHeader('Content-Type', rres.headers['content-type']);
    if (type === 'tarball') res.setHeader('Content-Length', rres.headers['content-length']);
    var b = "";
    rres.on('data', function(d) {
      hash.update(d);
      if (type != 'tarball') b += d;
      else res.write(d);
    });
    rres.on('end', function() {
      if (type === 'tarball') {
        res.end();
      } else {
        if (type === 'package_metadata') {
          b = rewritePackageMD(b);
        } else if (type === 'version_metadata') {
          b = rewriteVersionMD(b);
        }
        if (b === null) {
          res.writeHead(404);
          res.end("package installation disallowed by lockdown");
        } else {
          res.setHeader('Content-Length', Buffer.byteLength(b));
          res.writeHead(rres.statusCode);
          res.end(b);
        }
      }
    });
  });
  r.end();
});

server.listen(process.env['LOCKDOWN_PORT'] || 0, '127.0.0.1', function() {
  boundPort = server.address().port;

  var child = exec('npm install', {
    env: {
      NPM_CONFIG_REGISTRY: 'http://127.0.0.1:' + boundPort,
      NPM_LOCKDOWN_RUNNING: "true",
      PATH: process.env['PATH']
    },
    cwd: process.cwd()
  }, function(e) {
    if (warn.length) {
      console.log();
      console.log("LOCKDOWN WARNINGS:");
      warn.forEach(function(e) { console.log("   ", e); });
      console.log();
    }
    if (errors.length) {
      console.log();
      console.log("LOCKDOWN ERRORS:");
      errors.forEach(function(e) { console.log("   ", e); });
      console.log();
    }
    process.exit(e ? 1 : 0);
  });
  child.stdout.pipe(process.stdout);
  child.stderr.pipe(process.stderr);
});
<commit_msg>use a copy of process.env<commit_after>#!/usr/bin/env node

if (process.env['NPM_LOCKDOWN_RUNNING']) process.exit(0);

console.log("NPM Lockdown is here to check your dependencies!  Never fear!");

var http = require('http'),
    crypto = require('crypto'),
    exec = require('child_process').exec,
    fs = require('fs'),
    path = require('path');

try {
  var lockdownJson = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'lockdown.json')));
} catch(e) {
  console.log("\nERROR: I cannot read lockdown.json!  run node_modules/.bin/lockdown-relock to generate!\n");
  process.exit(1);
}

var boundPort;

// during execution fatal errors will be appended to this list
var errors = [];

// during execution non-fatal warnings will be appended to this list
var warn = [];

function rewriteURL(u) {
    return u.replace('registry.npmjs.org', '127.0.0.1:' + boundPort);
}

function packageOk(name, ver, sha, required) {
  if (!lockdownJson[name]) {
    if (required) {
      errors.push("package '" + name + "' not in lockdown.json!");
    }
    return false;
  }

  if (lockdownJson[name][ver] === undefined) {
    if (required) {
      errors.push("package version " + name + "@" + ver + " not in lockdown.json!");
    }
    return false;
  }

  // a '*' shasum is not checked
  var wantSHA = lockdownJson[name][ver];
  if (wantSHA !== '*' && wantSHA !== sha) {
    if (required) {
      errors.push("package " + name + "@" + ver + " has a different checksum (" +
                  wantSHA + " v. " + sha + ")");
    }
    return false;
  }

  if (wantSHA === '*') {
    warn.push("Lockdown cannot guarantee your saftey!  No sha for pkg " + name + "@" + ver +
              " in lockdown.json");
  }

  return true;
}

function rewriteVersionMD(json) {
  if (typeof json === 'string') json = JSON.parse(json);
  if (!json.error) {
    json.dist.tarball = rewriteURL(json.dist.tarball);

    // is the name/version/sha in our lockdown.json?
    if (!packageOk(json.name, json.version, json.dist.shasum, true)) return null;
  }
  return JSON.stringify(json);
}

function rewritePackageMD(json) {
  if (typeof json === 'string') json = JSON.parse(json);
  if (!json.error) {
    Object.keys(json.versions).forEach(function(ver) {
      var data = json.versions[ver];
      var name = data.name;
      var sha = data.dist ? data.dist.shasum : undefined;

      if (packageOk(name, ver, sha, false)) {
        data.dist.tarball = rewriteURL(data.dist.tarball);
      } else {
        delete json.versions[ver];
      }
    });
  }
  return JSON.stringify(json);
}

var server = http.createServer(function (req, res) {
  if (req.method !== 'GET') {
    return res.end('non GET requests not supported', 501);
  }

  // what type of request is this?
  // 1. specific version json metadata (when explicit dependency is expressed)
  //    - for these requests we should verify the name/version/sha advertised is allowed
  // 2. package version json metadata (when version range is expressed - including '*')
  //    XXX: for these requests we should prune all versions that are not allowed
  // 3. tarball - actual bits
  //    XXX: for these requests we should verify the name/version/sha matches something
  //         allowed, otherwise block the transaction
  var arr = req.url.substr(1).split('/');
  var type = [ '', 'package_metadata', 'version_metadata', 'tarball' ][arr.length];

  // let's extract pkg name and version sensitive to the type of request being performed.
  var pkgname, pkgver;
  if (type === 'tarball') {
    pkgname = arr[0];
    var getVer = new RegExp("^" + pkgname + "-(.*)\\.tgz$");
    pkgver = getVer.exec(arr[2])[1];
  } else if (type === 'version_metadata') {
    pkgname = arr[0];
    pkgver = arr[1];
  } else if (type === 'package_metadata') {
    pkgname = arr[0];
  }

  var hash = crypto.createHash('sha1');

  var r = http.request({
    host: 'registry.npmjs.org',
    port: 80,
    method: req.method,
    path: req.url,
    agent: false
  }, function(rres) {
    res.setHeader('Content-Type', rres.headers['content-type']);
    if (type === 'tarball') res.setHeader('Content-Length', rres.headers['content-length']);
    var b = "";
    rres.on('data', function(d) {
      hash.update(d);
      if (type != 'tarball') b += d;
      else res.write(d);
    });
    rres.on('end', function() {
      if (type === 'tarball') {
        res.end();
      } else {
        if (type === 'package_metadata') {
          b = rewritePackageMD(b);
        } else if (type === 'version_metadata') {
          b = rewriteVersionMD(b);
        }
        if (b === null) {
          res.writeHead(404);
          res.end("package installation disallowed by lockdown");
        } else {
          res.setHeader('Content-Length', Buffer.byteLength(b));
          res.writeHead(rres.statusCode);
          res.end(b);
        }
      }
    });
  });
  r.end();
});

server.listen(process.env['LOCKDOWN_PORT'] || 0, '127.0.0.1', function() {
  boundPort = server.address().port;
  var env = Object.create(process.env);
  env.NPM_CONFIG_REGISTRY = 'http://127.0.0.1:' + boundPort;
  env.NPM_LOCKDOWN_RUNNING = "true";

  var child = exec('npm install', {
    env: env,
    cwd: process.cwd()
  }, function(e) {
    if (warn.length) {
      console.log();
      console.log("LOCKDOWN WARNINGS:");
      warn.forEach(function(e) { console.log("   ", e); });
      console.log();
    }
    if (errors.length) {
      console.log();
      console.log("LOCKDOWN ERRORS:");
      errors.forEach(function(e) { console.log("   ", e); });
      console.log();
    }
    process.exit(e ? 1 : 0);
  });
  child.stdout.pipe(process.stdout);
  child.stderr.pipe(process.stderr);
});
<|endoftext|>


<commit_before>import angular from 'angular';

const apiHost = 'https://api.github.com';
const eventLimit = 2;

class GithubAPI {

  /* @ngInject */
  constructor($http) {
    this.$http = $http;
  }

  getActivity(user, repository, limit, enableCommitStatus) {
    if (!user || user === angular.isUndefined()) {
      return Promise.reject('No user was supplied');
    }

    let urlArray = [apiHost];
    if (repository) {
      urlArray = urlArray.concat(['repos', user, repository]);
    } else {
      urlArray = urlArray.concat(['users', user]);
    }
    urlArray.push('events');
    return this.$http.get(urlArray.join('/'))
      .then((response) => this.handleResponse(response, limit, enableCommitStatus))
      .catch((error) => {
        console.error('XHR Failed for getActivity.\n', angular.toJson(error.data, true));
      });
  }

  handleResponse(response, limit, enableCommitStatus) {
    const maxEvents = limit || eventLimit;
    const events = [];

    for (const event of response.data) {
      if (events.length < maxEvents) {
        if (event.type === 'PushEvent') {
          if (enableCommitStatus) {
            this.getStatus(event);
          }
          events.push(event);
        }
      } else {
        return events;
      }
    }
    return events;
  }

  getStatus(event) {
    const sha = event.payload.commits[event.payload.commits.length - 1].sha;
    const url = 'https://api.github.com/repos/' + event.repo.name + '/commits/' + sha + '/statuses';

    return this.$http.get(url)
      .then((response) => {
        event.status = response.data[0] || {};
        return event;
      })
      .catch((error) => {
        console.error('XHR Failed for getStatus.\n', angular.toJson(error.data, true));
      });
  }
}

export default GithubAPI;
<commit_msg>Fix showing non-distinct events<commit_after>import angular from 'angular';

const apiHost = 'https://api.github.com';
const eventLimit = 2;

class GithubAPI {

  /* @ngInject */
  constructor($http) {
    this.$http = $http;
  }

  getActivity(user, repository, limit, enableCommitStatus) {
    if (!user || user === angular.isUndefined()) {
      return Promise.reject('No user was supplied');
    }

    let urlArray = [apiHost];
    if (repository) {
      urlArray = urlArray.concat(['repos', user, repository]);
    } else {
      urlArray = urlArray.concat(['users', user]);
    }
    urlArray.push('events');

    return this.$http.get(urlArray.join('/'))
      .then((response) => this.handleResponse(response, limit, enableCommitStatus))
      .catch((error) => {
        console.error('XHR Failed for getActivity.\n', angular.toJson(error.data, true));
      });
  }

  handleResponse(response, limit, enableCommitStatus) {
    const maxEvents = limit || eventLimit;
    const events = [];

    for (const event of response.data) {
      if (events.length < maxEvents) {
        if (event.type === 'PushEvent' && event.payload.distinct_size > 0) {
          if (enableCommitStatus) {
            this.getStatus(event);
          }
          events.push(event);
        }
      } else {
        return events;
      }
    }
    return events;
  }

  getStatus(event) {
    const sha = event.payload.commits[event.payload.commits.length - 1].sha;
    const url = 'https://api.github.com/repos/' + event.repo.name + '/commits/' + sha + '/statuses';

    return this.$http.get(url)
      .then((response) => {
        event.status = response.data[0] || {};
        return event;
      })
      .catch((error) => {
        console.error('XHR Failed for getStatus.\n', angular.toJson(error.data, true));
      });
  }
}

export default GithubAPI;
<|endoftext|>


<commit_before>var FB = function (url, gameId) {
    this.firebase = new Firebase(url);
    this.gameId = gameId;
};

FB.prototype.ref = function () {
    return this.firebase;
};

FB.prototype.newGame = function (size) {
    var ref = this.firebase.root();
    var key = ref.push().key();
    var def = $.Deferred();
    ref.child('games/' + key).set({size: size}, function(error) {
        if (error) {
            def.reject(error);
        } else {
            def.resolve(key);
        }
    });
    return def.promise();
};

FB.prototype.getGames = function () {
    var def = $.Deferred();
    this.firebase.child('games').orderByKey().limitToLast(5).once('value', function(snap){
        def.resolve(snap.val());
    });
    return def.promise();
};

FB.prototype.setStone = function (x, y, color) {
    return this.firebase.child('games/' + this.gameId + '/board/' + x + "-" + y).set(color);
};

FB.prototype.removeStone = function (x, y) {
    return this.firebase.child('games/' + this.gameId + '/board/' + x + "-" + y).remove();
};

FB.prototype.setToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var self = this;
    var player = 'games/' + this.gameId + '/player' + playerNum + '/token';
    var partner = 'games/' + this.gameId + 'player' + partnerNum + '/token';
    this.firebase.child(player).once('value', function (snap) {
        self.firebase.child(partner).once('value', function (snapPartner) {
            if (_.isNull(snap.val()) && _.isNull(snapPartner.val())) {
                self.firebase.child(player).transaction(function () {
                    return true;
                });
            }
        });
    });
};

FB.prototype.switchToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var partner = 'games/' + this.gameId + '/player' + partnerNum + '/token';
    var player = 'games/' + this.gameId + '/player' + playerNum + '/token';
    this.firebase.child(player).set({});
    this.firebase.child(partner).transaction(function () {
        return true;
    });
};

/**
 * Calls Firebase.on(), Listens for data changes at a particular location
 *
 *

 *     FB.on('board', 'child_added')
 *       .progress( childAdded )
 *       .fail( securityError )
 *       .done( listenerDisposed )
 *

 *
 * @param path
 * @param event
 * @return {jQuery.Deferred}
 */
FB.prototype.on = function (path, event) {
    var def = $.Deferred();

    this.firebase.child(path).on(event, function(snap) {
        def.notify(snap);
    }, function (err) {
        console.error('Access denied attempting to read database ', err, path, event);
    });

    return def.promise();
};

/**
 * Calls Firebase.once(), Listens for exactly one event of the specified event type, and then stops listening.
 *
 * @param path
 * @param event
 * @returns {jQuery.Deferred}
 */
FB.prototype.once = function(path, event) {
    var def = $.Deferred();

    this.firebase.child(path).once(event, function(snap) {
        def.resolve(snap);
    }, function(err) {
        console.error('Access denied attempting to read database', err, path, event);
        def.reject(err);
    });

    return def.promise();
};

FB.prototype.childWithTransaction = function (path, input) {
    var def = $.Deferred();
    this.firebase.child(path).transaction(function (value) {
        def.resolve(value);
        if (value === null) {
            return input;
        } else {
            return;
        }
    }, function (error, committed) {
        def.reject(error, committed);
    });
    return def.promise();
};
<commit_msg>always return the root value<commit_after>var FB = function (url, gameId) {
    this.firebase = new Firebase(url);
    this.gameId = gameId;
};

FB.prototype.ref = function () {
    return this.firebase.root();
};

FB.prototype.newGame = function (size) {
    var ref = this.firebase.root();
    var key = ref.push().key();
    var def = $.Deferred();
    ref.child('games/' + key).set({size: size}, function(error) {
        if (error) {
            def.reject(error);
        } else {
            def.resolve(key);
        }
    });
    return def.promise();
};

FB.prototype.getGames = function () {
    var def = $.Deferred();
    this.firebase.child('games').orderByKey().limitToLast(5).once('value', function(snap){
        def.resolve(snap.val());
    });
    return def.promise();
};

FB.prototype.setStone = function (x, y, color) {
    return this.firebase.child('games/' + this.gameId + '/board/' + x + "-" + y).set(color);
};

FB.prototype.removeStone = function (x, y) {
    return this.firebase.child('games/' + this.gameId + '/board/' + x + "-" + y).remove();
};

FB.prototype.setToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var self = this;
    var player = 'games/' + this.gameId + '/player' + playerNum + '/token';
    var partner = 'games/' + this.gameId + 'player' + partnerNum + '/token';
    this.firebase.child(player).once('value', function (snap) {
        self.firebase.child(partner).once('value', function (snapPartner) {
            if (_.isNull(snap.val()) && _.isNull(snapPartner.val())) {
                self.firebase.child(player).transaction(function () {
                    return true;
                });
            }
        });
    });
};

FB.prototype.switchToken = function (playerNum) {
    var partnerNum = Math.abs(playerNum - 1);
    var partner = 'games/' + this.gameId + '/player' + partnerNum + '/token';
    var player = 'games/' + this.gameId + '/player' + playerNum + '/token';
    this.firebase.child(player).set({});
    this.firebase.child(partner).transaction(function () {
        return true;
    });
};

/**
 * Calls Firebase.on(), Listens for data changes at a particular location
 *
 *

 *     FB.on('board', 'child_added')
 *       .progress( childAdded )
 *       .fail( securityError )
 *       .done( listenerDisposed )
 *

 *
 * @param path
 * @param event
 * @return {jQuery.Deferred}
 */
FB.prototype.on = function (path, event) {
    var def = $.Deferred();

    this.ref().child(path).on(event, function(snap) {
        def.notify(snap);
    }, function (err) {
        console.error('Access denied attempting to read database ', err, path, event);
    });

    return def.promise();
};

/**
 * Calls Firebase.once(), Listens for exactly one event of the specified event type, and then stops listening.
 *
 * @param path
 * @param event
 * @returns {jQuery.Deferred}
 */
FB.prototype.once = function(path, event) {
    var def = $.Deferred();

    this.ref().child(path).once(event, function(snap) {
        def.resolve(snap);
    }, function(err) {
        console.error('Access denied attempting to read database', err, path, event);
        def.reject(err);
    });

    return def.promise();
};

FB.prototype.childWithTransaction = function (path, input) {
    var def = $.Deferred();
    this.ref().child(path).transaction(function (value) {
        def.resolve(value);
        if (value === null) {
            return input;
        } else {
            return;
        }
    }, function (error, committed) {
        def.reject(error, committed);
    });
    return def.promise();
};
<|endoftext|>


<commit_before>'use strict'

module.exports = function (db, DataTypes) {
  let User = db.define('User', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING(1024),
      allowNull: false
    },
    nicknames: {
      type: 'citext[]',
      allowNull: true,
      defaultValue: db.literal('ARRAY[]::citext[]')
    },
    groups: {
      type: DataTypes.ARRAY(DataTypes.STRING(128)),
      allowNull: false,
      defaultValue: []
    }
  }, {
    paranoid: true,
    classMethods: {
      associate: function (models) {
        User.hasMany(models.Rat, { as: 'rats' })
      }
    }
  })

  return User
}
<commit_msg>Add binary blob image database field to users for Trezy's weird profile image thing<commit_after>'use strict'

module.exports = function (db, DataTypes) {
  let User = db.define('User', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4
    },
    email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING(1024),
      allowNull: false
    },
    nicknames: {
      type: 'citext[]',
      allowNull: true,
      defaultValue: db.literal('ARRAY[]::citext[]')
    },
    groups: {
      type: DataTypes.ARRAY(DataTypes.STRING(128)),
      allowNull: false,
      defaultValue: []
    },
    image: {
      type: DataTypes.BLOB(),
      allowNull: true,
      defaultValue: null
    }
  }, {
    paranoid: true,
    classMethods: {
      associate: function (models) {
        User.hasMany(models.Rat, { as: 'rats' })
      }
    }
  })

  return User
}
<|endoftext|>


<commit_before>var collect = require('collect-stream')
var pumpify = require('pumpify')
var mapStream = require('through2-map')
var collectTransform = require('collect-transform-stream')
var defork = require('osm-p2p-defork')
var through = require('through2')

var refs2nodes = require('../lib/util').refs2nodes
var checkRefExist = require('../lib/check_ref_ex.js')

module.exports = function (osm) {
  return function getMap (bbox, opts, cb) {
    if (typeof opts === 'function') {
      cb = opts
      opts = {}
    }
    opts.forks = opts.forks || false

    var query = [[bbox[1], bbox[3]], [bbox[0], bbox[2]]] // left,bottom,right,top

    // For now, filter deletions (until downstream can handle them)
    var deletionFilter = through.obj(function (chunk, enc, next) {
      if (!chunk.deleted) next(null, chunk)
      else next()
    })

    var pipeline = [
      osm.queryStream(query, opts),
      deletionFilter,
      checkRefExist(osm),
      mapStream.obj(refs2nodes)
    ]

    // If forks ought to be filtered out, add another step to the pipeline that
    // does so.
    if (!opts.forks) {
      pipeline.push(deforkStream())
    }

    var queryStreamJson = pumpify.obj.apply(this, pipeline)
    if (cb) {
      collect(queryStreamJson, function (err, elements) {
        if (err) return cb(err)
        cb(null, elements)
      })
    } else {
      return queryStreamJson
    }
  }
}

function deforkStream () {
  return collectTransform(function (res) {
    return defork(res).sort(cmpType)
  })
}

var typeOrder = { node: 0, way: 1, relation: 2 }
function cmpType (a, b) {
  return typeOrder[a.type] - typeOrder[b.type]
}
<commit_msg>fix: don't include deleted nodes as way refs<commit_after>var collect = require('collect-stream')
var pumpify = require('pumpify')
var mapStream = require('through2-map')
var collectTransform = require('collect-transform-stream')
var defork = require('osm-p2p-defork')
var through = require('through2')

var refs2nodes = require('../lib/util').refs2nodes
var checkRefExist = require('../lib/check_ref_ex.js')

module.exports = function (osm) {
  return function getMap (bbox, opts, cb) {
    if (typeof opts === 'function') {
      cb = opts
      opts = {}
    }
    opts.forks = opts.forks || false

    var query = [[bbox[1], bbox[3]], [bbox[0], bbox[2]]] // left,bottom,right,top

    // For now, filter deletions (until downstream can handle them).
    //
    // This also involves removing references to deleted nodes from ways (iD
    // handles this poorly). This relies on the fact that nodes come before
    // ways from the osm-p2p-db query.
    var nodesSeen = {}
    var deletionFilter = through.obj(function (chunk, enc, next) {
      if (chunk.type === 'node') {
        nodesSeen[chunk.id] = true
      } else if (chunk.type === 'way') {
        chunk.refs = chunk.refs.filter(function (id) {
          return !!nodesSeen[id]
        })
      }

      if (!chunk.deleted) next(null, chunk)
      else next()
    })

    var pipeline = [
      osm.queryStream(query, opts),
      deletionFilter,
      checkRefExist(osm),
      mapStream.obj(refs2nodes)
    ]

    // If forks ought to be filtered out, add another step to the pipeline that
    // does so.
    if (!opts.forks) {
      pipeline.push(deforkStream())
    }

    var queryStreamJson = pumpify.obj.apply(this, pipeline)
    if (cb) {
      collect(queryStreamJson, function (err, elements) {
        if (err) return cb(err)
        cb(null, elements)
      })
    } else {
      return queryStreamJson
    }
  }
}

function deforkStream () {
  return collectTransform(function (res) {
    return defork(res).sort(cmpType)
  })
}

var typeOrder = { node: 0, way: 1, relation: 2 }
function cmpType (a, b) {
  return typeOrder[a.type] - typeOrder[b.type]
}
<|endoftext|>


<commit_before>'use strict';

const Keypath = require('gkeypath');

module.exports = function passport(app, config) {
    /*
     * We use as follows:
     * res.flash('info', 'Flash is back!');
     *
     * In template:
     *
     * <% if (flash.info) { %>
     *
<%= flash.info %>

     * <% } %>
     */
    // const flash = require('express-flash-2');
    app.use(flash());
};

var format = require('util').format;
var isArray = require('util').isArray;

/**
 * Expose `flash()` function on responses.
 *
 * @return {Function}
 * @api public
 */
function flash(options) {
    options = options || {};
    var safe = (options.unsafe === undefined) ? true : !options.unsafe;

  return function flashMiddlware(req, res, next) {
        if (!(res.flash && safe)) {
            res.flash = _flash;
        }

        /*
         * This is a hack for now.
         * Issue is we run socket.io from
         * server module.
         * We serve dashboard page from
         * dashboard module.
         *
         */
        if(!req.session) req.session = {};

        // put the flash into res.locals
        var flash = Keypath.get(res, 'req.session.flash', {});
        res.req.session.flash = {};
        res.locals.flash = flash;
        next();
    };
}

module.exports.flash = flash;

/**
 * Queue flash `msg` of the given `type`.
 *
 * Examples:
 *
 *      req.flash('info', 'email sent');
 *      req.flash('error', 'email delivery failed');
 *      req.flash('info', 'email re-sent');
 *      // => 2
 *
 *
 * Formatting:
 *
 * Flash notifications also support arbitrary formatting support.
 * For example you may pass variable arguments to `req.flash()`
 * and use the %s specifier to be replaced by the associated argument:
 *
 *     req.flash('info', 'email has been sent to %s.', userName);
 *
 * Formatting uses `util.format()`, which is available on Node 0.6+.
 *
 * @param {String} type
 * @param {String} msg
 * @return {Number}
 * @api public
 */
function _flash(type, msg) {
  var session = this.req.session;
  if (session === undefined) throw Error('res.flash() requires sessions');
  var msgs = session.flash = session.flash || {};
  if (type && msg) {
    // util.format is available in Node.js 0.6+
    if (arguments.length > 2 && format) {
      var args = Array.prototype.slice.call(arguments, 1);
      msg = format.apply(undefined, args);
    } else if (isArray(msg)) {
      msg.forEach(function(val){
        (msgs[type] = msgs[type] || []).push(val);
      });
      return msgs[type].length;
    }
    return (msgs[type] = msgs[type] || []).push(msg);
  }
}
<commit_msg>update flash middleware def<commit_after>'use strict';

const Keypath = require('gkeypath');

module.exports = function $flashMiddlware(app, config) {
    /*
     * We use as follows:
     * res.flash('info', 'Flash is back!');
     *
     * In template:
     *
     * <% if (flash.info) { %>
     *
<%= flash.info %>

     * <% } %>
     */
    // const flash = require('express-flash-2');
    app.use(flash());
};

const format = require('util').format;
const isArray = require('util').isArray;

/**
 * Expose `flash()` function on responses.
 *
 * @return {Function}
 * @api public
 */
function flash(options) {
    options = options || {};
    var safe = (options.unsafe === undefined) ? true : !options.unsafe;

  return function flashMiddlware(req, res, next) {
        if (!(res.flash && safe)) {
            res.flash = _flash;
        }

        /*
         * This is a hack for now.
         * Issue is we run socket.io from
         * server module.
         * We serve dashboard page from
         * dashboard module.
         *
         */
        if(!req.session) req.session = {};

        // put the flash into res.locals
        var flash = Keypath.get(res, 'req.session.flash', {});
        res.req.session.flash = {};
        res.locals.flash = flash;
        next();
    };
}

module.exports.flash = flash;

/**
 * Queue flash `msg` of the given `type`.
 *
 * Examples:
 *
 *      req.flash('info', 'email sent');
 *      req.flash('error', 'email delivery failed');
 *      req.flash('info', 'email re-sent');
 *      // => 2
 *
 *
 * Formatting:
 *
 * Flash notifications also support arbitrary formatting support.
 * For example you may pass variable arguments to `req.flash()`
 * and use the %s specifier to be replaced by the associated argument:
 *
 *     req.flash('info', 'email has been sent to %s.', userName);
 *
 * Formatting uses `util.format()`, which is available on Node 0.6+.
 *
 * @param {String} type
 * @param {String} msg
 * @return {Number}
 * @api public
 */
function _flash(type, msg) {
  var session = this.req.session;
  if (session === undefined) throw Error('res.flash() requires sessions');
  var msgs = session.flash = session.flash || {};
  if (type && msg) {
    // util.format is available in Node.js 0.6+
    if (arguments.length > 2 && format) {
      var args = Array.prototype.slice.call(arguments, 1);
      msg = format.apply(undefined, args);
    } else if (isArray(msg)) {
      msg.forEach(function(val){
        (msgs[type] = msgs[type] || []).push(val);
      });
      return msgs[type].length;
    }
    return (msgs[type] = msgs[type] || []).push(msg);
  }
}
<|endoftext|>


<commit_before>const mime = require('mime');
const busboy = require('async-busboy');

module.exports = (service) => {

	// Getting member system agent
	const memberAgent = service.getContext().get('Member')[service.memberAgent];
	const Permission = memberAgent.getPermissionMiddleware();

	// Create a new router
	let router = service.createRouter({
		prefix: '/api/v1'
	});

	// Set type to "API" for router
	router.use(service.routeType('API'));

	/**
	 * @api {get} /api/v1/members/profile Getting profile
	 * @apiName GetMemberProfile
	 * @apiGroup Member
	 *
	 * @apiHeader {String} authorization user's token
	 *
	 * @apiSuccess {Object} Member information
	 *
	 * @apiError 403 Account is disabled
	 * @apiError 404 NotFound Account doesn't exist
	 **/
	router.get('/members/profile', Permission('Member.access'), async (ctx, next) => {

		try {
			// Verify member account
			const member = await memberAgent
				.getMemberManager()
				.getProfile(ctx.state.session.id);

			// Response
			ctx.body = member;

		} catch(e) {

			switch(e.name) {
			case 'NotExist':
				ctx.throw(404, {
					code: 'NotExist',
					message: 'Account doesn\'t exist'
				});
			}

			throw e;
		}
	});

	/*
	 * @api {put} /api/v1/members/profile Update member's profile
	 * @apiName UpdateMemberProfile
	 * @apiGroup Member
	 *
	 * @apiHeader {String} authorization user's token
	 *
	 * @apiSuccess {Object} Member information
	 *
	 * @apiError 403 Account is disabled
	 * @apiError 404 Account doesn't exist
	 */
	router.put('/members/profile', Permission('Member.access'), async (ctx, next) => {

		let payload = ctx.request.body;

		try {
			// Update member's profile
			let member = await memberAgent.getMemberManager().updateProfile(ctx.state.session.id, payload);

			// Response
			ctx.body = member;

		} catch(e) {

			switch(e.name) {
			case 'NotExist':
				ctx.throw(404, {
					code: 'NotExist',
					message: 'Account doesn\'t exist'
				});
			case 'ValidationFailed':
				ctx.throw(422, {
					code: 'ValidationFailed',
					message: 'Validation failed',
					errors: e.errors.map((error) => {
						switch(error.type) {
						case 'any.required':
							return {
								field: error.field,
								code: 'required'
							};

						default:
							return {
								field: error.field,
								code: 'invalid'
							};
						}
					})
				});
			}

			throw e;
		}
	});

	/**
	 * @api {put} /api/v1/members/password Change password
	 * @apiName ChangePassword
	 * @apiGroup Member
	 *
	 * @apiHeader {String} Authorization User's token
	 *
	 * @apiParam {String} old Old password
	 * @apiParam {String} new New password
	 *
	 * @apiError 401 Old password is incorrect
	 * @apiError 403 Account is disabled
	 * @apiError 404 Account doesn't exist
	 **/
	router.put('/members/password', Permission('Member.access'), async (ctx, next) => {

		let payload = ctx.request.body;

		// Check parameters
		if (payload['old'] === undefined || payload['new'] === undefined) {
			ctx.throw(400, {
				code: 'BadRequest',
				message: 'Bad request'
			});
		}

		try {
			// Verify member account
			await memberAgent.getMemberManager().changePassword(ctx.state.session.id, payload['old'], payload['new']);

			// Response
			ctx.body = {
				code: 'Success',
				message: 'Password was changed'
			};

		} catch(e) {

			switch(e.name) {
			case 'IncorrectOldPassword':
				ctx.throw(401, {
					code: 'IncorrectOldPassword',
					message: 'Incorrect Old Password'
				});

			case 'Disabled':
				ctx.throw(403, {
					code: 'AccountBlocked',
					message: 'Account was blocked'
				});

			case 'NotExist':
				ctx.throw(404, {
					code: 'NotExist',
					message: 'Account doesn\'t exist'
				});
			}

			throw e;
		}
	});

	/**
	 * @api {post} /api/v1/members/avatar Upload avatar picture
	 * @apiName UploadAvatar
	 * @apiGroup Member
	 *
	 * @apiSuccess {String} token Access token
	 *
	 * @apiError 401 Authentication failed
	 * @apiError 403 Account is disabled
	 * @apiError 422 Parameters are invalid
	 * @apiErrorExample {json} Error-Response:
	 *	HTTP/1.1 422 Validation Failed
	 *	{
	 *		code: 'ValidationFailed',
	 *		message: 'Validation Failed',
	 *		errors: [
	 *			{ field: 'email', code: 'required'  },
	 *			{ field: 'passsword', code: 'invalid'  }
	 *		]
	 *	}
	 **/
	router.post('/members/avatar', async (ctx, next) => {

		try {
			let avatarUrl = await new Promise(async (resolve, reject) => {

				try {
					let ret = await busboy(ctx.req, {
						onFile: async (fieldName, file, filename, encoding, mimetype) => {

							if (fieldName !== 'avatar')
								return;

							// Update avatar picture
							let avatarUrl = await memberAgent
								.getMemberManager()
								.updateAvatarByStream(ctx.state.session.id, {
									contentType: mimetype,
									size: ctx.request.headers['content-length']
								}, file);

							resolve(avatarUrl);
						}
					});
				} catch(e) {
					reject(e);
				}
			});

			// Response
			ctx.body = {
				avatar_url: avatarUrl
			};

		} catch(e) {

			switch(e.name) {
			case 'ValidationFailed':
				ctx.throw(422, {
					code: 'ValidationFailed',
					message: 'Validation failed',
					errors: e.errors.map((error) => {
						switch(error.type) {
						case 'any.required':
							return {
								field: error.field,
								code: 'required'
							};

						default:
							return {
								field: error.field,
								code: 'invalid'
							};
						}
					})
				});
			case 'NotExist':
				ctx.throw(401, {
					code: 'AuthenticationFailed',
					message: 'Authentication failed'
				});
			}

			throw e;
		}
	});

	return router;
};
<commit_msg>remove validation error handling for avatar update<commit_after>const mime = require('mime');
const busboy = require('async-busboy');

module.exports = (service) => {

	// Getting member system agent
	const memberAgent = service.getContext().get('Member')[service.memberAgent];
	const Permission = memberAgent.getPermissionMiddleware();

	// Create a new router
	let router = service.createRouter({
		prefix: '/api/v1'
	});

	// Set type to "API" for router
	router.use(service.routeType('API'));

	/**
	 * @api {get} /api/v1/members/profile Getting profile
	 * @apiName GetMemberProfile
	 * @apiGroup Member
	 *
	 * @apiHeader {String} authorization user's token
	 *
	 * @apiSuccess {Object} Member information
	 *
	 * @apiError 403 Account is disabled
	 * @apiError 404 NotFound Account doesn't exist
	 **/
	router.get('/members/profile', Permission('Member.access'), async (ctx, next) => {

		try {
			// Verify member account
			const member = await memberAgent
				.getMemberManager()
				.getProfile(ctx.state.session.id);

			// Response
			ctx.body = member;

		} catch(e) {

			switch(e.name) {
			case 'NotExist':
				ctx.throw(404, {
					code: 'NotExist',
					message: 'Account doesn\'t exist'
				});
			}

			throw e;
		}
	});

	/*
	 * @api {put} /api/v1/members/profile Update member's profile
	 * @apiName UpdateMemberProfile
	 * @apiGroup Member
	 *
	 * @apiHeader {String} authorization user's token
	 *
	 * @apiSuccess {Object} Member information
	 *
	 * @apiError 403 Account is disabled
	 * @apiError 404 Account doesn't exist
	 */
	router.put('/members/profile', Permission('Member.access'), async (ctx, next) => {

		let payload = ctx.request.body;

		try {
			// Update member's profile
			let member = await memberAgent.getMemberManager().updateProfile(ctx.state.session.id, payload);

			// Response
			ctx.body = member;

		} catch(e) {

			switch(e.name) {
			case 'NotExist':
				ctx.throw(404, {
					code: 'NotExist',
					message: 'Account doesn\'t exist'
				});
			case 'ValidationFailed':
				ctx.throw(422, {
					code: 'ValidationFailed',
					message: 'Validation failed',
					errors: e.errors.map((error) => {
						switch(error.type) {
						case 'any.required':
							return {
								field: error.field,
								code: 'required'
							};

						default:
							return {
								field: error.field,
								code: 'invalid'
							};
						}
					})
				});
			}

			throw e;
		}
	});

	/**
	 * @api {put} /api/v1/members/password Change password
	 * @apiName ChangePassword
	 * @apiGroup Member
	 *
	 * @apiHeader {String} Authorization User's token
	 *
	 * @apiParam {String} old Old password
	 * @apiParam {String} new New password
	 *
	 * @apiError 401 Old password is incorrect
	 * @apiError 403 Account is disabled
	 * @apiError 404 Account doesn't exist
	 **/
	router.put('/members/password', Permission('Member.access'), async (ctx, next) => {

		let payload = ctx.request.body;

		// Check parameters
		if (payload['old'] === undefined || payload['new'] === undefined) {
			ctx.throw(400, {
				code: 'BadRequest',
				message: 'Bad request'
			});
		}

		try {
			// Verify member account
			await memberAgent.getMemberManager().changePassword(ctx.state.session.id, payload['old'], payload['new']);

			// Response
			ctx.body = {
				code: 'Success',
				message: 'Password was changed'
			};

		} catch(e) {

			switch(e.name) {
			case 'IncorrectOldPassword':
				ctx.throw(401, {
					code: 'IncorrectOldPassword',
					message: 'Incorrect Old Password'
				});

			case 'Disabled':
				ctx.throw(403, {
					code: 'AccountBlocked',
					message: 'Account was blocked'
				});

			case 'NotExist':
				ctx.throw(404, {
					code: 'NotExist',
					message: 'Account doesn\'t exist'
				});
			}

			throw e;
		}
	});

	/**
	 * @api {post} /api/v1/members/avatar Upload avatar picture
	 * @apiName UploadAvatar
	 * @apiGroup Member
	 *
	 * @apiSuccess {String} token Access token
	 *
	 * @apiError 401 Authentication failed
	 * @apiError 403 Account is disabled
	 * @apiError 422 Parameters are invalid
	 * @apiErrorExample {json} Error-Response:
	 *	HTTP/1.1 422 Validation Failed
	 *	{
	 *		code: 'ValidationFailed',
	 *		message: 'Validation Failed',
	 *		errors: [
	 *			{ field: 'email', code: 'required'  },
	 *			{ field: 'passsword', code: 'invalid'  }
	 *		]
	 *	}
	 **/
	router.post('/members/avatar', async (ctx, next) => {

		try {
			let avatarUrl = await new Promise(async (resolve, reject) => {

				try {
					let ret = await busboy(ctx.req, {
						onFile: async (fieldName, file, filename, encoding, mimetype) => {

							if (fieldName !== 'avatar')
								return;

							// Update avatar picture
							let avatarUrl = await memberAgent
								.getMemberManager()
								.updateAvatarByStream(ctx.state.session.id, {
									contentType: mimetype,
									size: ctx.request.headers['content-length']
								}, file);

							resolve(avatarUrl);
						}
					});
				} catch(e) {
					reject(e);
				}
			});

			// Response
			ctx.body = {
				avatar_url: avatarUrl
			};

		} catch(e) {

			switch(e.name) {
			case 'NotExist':
				ctx.throw(401, {
					code: 'AuthenticationFailed',
					message: 'Authentication failed'
				});
			}

			throw e;
		}
	});

	return router;
};
<|endoftext|>


<commit_before>// # db api

// ## Load dependencies
var mongoose = require('mongoose');

var db = mongoose.connection;

db.on('error', console.error);

function Db(username,pass) {

    // ## Schema for a frame of a strat
    var frameSchema = new mongoose.Schema({
        desc: String,
        event: {
            desc: String,
            icon: String
        },
        elem: [Object],
        parent: String,
        children: [String],
        editors: [String],
        strat: String
    });

    // ## Schema for a strat
    var stratSchema = new mongoose.Schema({
        stratName: String,
        desc: String,
        owner: {
            // Category
            cat: String,
            name: String
        },
        map: String,
        root: String
    });

    // ## Schema for a user
    var userSchema = new mongoose.Schema({
        id: String,
        name: String,
        displayName: String
    });

    // ## Schema for an organization
    var orgSchema = new mongoose.Schema({
        name: String,
        editors: [Object]
    });

    var Frame = mongoose.model('Frame', frameSchema);
    var Strat = mongoose.model('Strat', stratSchema);
    var User = mongoose.model('User', userSchema);

    var db_users = require('./db_api/users').db(username,pass,User);
    var db_strats = require('./db_api/strats').db(username,pass,User);

    // ## DB Functions

    // Creates a new user entry into db.
    this.newUser = db_users.newUser;

    // Edits a user's display name.
    this.editUserDisplayName = db_users.editUserDisplayName;

    // Find given fields in User.
    this.findInUser = db_users.findInUser;

    // Creates a new strategy entry into db.
    this.newStrat = db_strats.newStrat;

    // Finds user by username.
    this.findUser = db_users.findUser;

    // Find user by steam ID.
    this.findUserBySteamId = db_users.findUserBySteamId;

    // Find strat by username and strat name.
    this.findStrat = db_strats.findStrat;

    // Finds all strategies by a user.
    this.findUserStrats = db_strats.findUserStrats;

    // Delete frame from strat. First checks to make sure no one is currently editing any of the child frames and then deletes a the frame and all of children.
    this.deleteFrame = function(obj, cb) {
        if (checkChildren(obj.strat, obj.frame)) {

        }
    }

    // Check to find children.
    var checkChildren = function(obj) {
        Frame.findOne({strat: obj.strat, _id: obj.frame}, function(err, frame){
            var children = frame.children;

            children.forEach(function(e, i, a){

            });
        });
    }
    mongoose.connect('mongodb://'+username+':'+pass+'@ds047207.mongolab.com:47207/csgodb');
}

exports.db = function(user,pass){
    return new Db(user,pass);
}

//CS:GO Drawing Board is a web application that allows users to develop CS:GO strategies.
//
//Copyright 2014 Duck Syrup
//
//This file is part of CS:GO Drawing Board.
//
//CS:GO Drawing Board is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//CS:GO Drawing Board is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Affero General Public License for more details.
//
//You should have received a copy of the GNU Affero General Public License
//along with CS:GO Drawing Board.  If not, see <http://www.gnu.org/licenses/>.<commit_msg>you are such an idiot<commit_after>// # db api

// ## Load dependencies
var mongoose = require('mongoose');

var db = mongoose.connection;

db.on('error', console.error);

function Db(username,pass) {

    // ## Schema for a frame of a strat
    var frameSchema = new mongoose.Schema({
        desc: String,
        event: {
            desc: String,
            icon: String
        },
        elem: [Object],
        parent: String,
        children: [String],
        editors: [String],
        strat: String
    });

    // ## Schema for a strat
    var stratSchema = new mongoose.Schema({
        stratName: String,
        desc: String,
        owner: {
            // Category
            cat: String,
            name: String
        },
        map: String,
        root: String
    });

    // ## Schema for a user
    var userSchema = new mongoose.Schema({
        steamId: String,
        name: String,
        displayName: String
    });

    // ## Schema for an organization
    var orgSchema = new mongoose.Schema({
        name: String,
        editors: [Object]
    });

    var Frame = mongoose.model('Frame', frameSchema);
    var Strat = mongoose.model('Strat', stratSchema);
    var User = mongoose.model('User', userSchema);

    var db_users = require('./db_api/users').db(username,pass,User);
    //var db_strats = require('./db_api/strats').db(username,pass,User);

    // ## DB Functions

    // Creates a new user entry into db.
    this.newUser = db_users.newUser;

    // Edits a user's display name.
    this.editUserDisplayName = db_users.editUserDisplayName;

    // Find given fields in User.
    this.findInUser = db_users.findInUser;

    // Creates a new strategy entry into db.
    //this.newStrat = db_strats.newStrat;

    // Finds user by username.
    this.findUser = db_users.findUser;

    // Find user by steam ID.
    this.findUserBySteamId = db_users.findUserBySteamId;

    // Find strat by username and strat name.
    //this.findStrat = db_strats.findStrat;

    // Finds all strategies by a user.
    //his.findUserStrats = db_strats.findUserStrats;

    // Delete frame from strat. First checks to make sure no one is currently editing any of the child frames and then deletes a the frame and all of children.
    this.deleteFrame = function(obj, cb) {
        if (checkChildren(obj.strat, obj.frame)) {

        }
    }

    // Check to find children.
    var checkChildren = function(obj) {
        Frame.findOne({strat: obj.strat, _id: obj.frame}, function(err, frame){
            var children = frame.children;

            children.forEach(function(e, i, a){

            });
        });
    }
    mongoose.connect('mongodb://'+username+':'+pass+'@ds047207.mongolab.com:47207/csgodb');
}

exports.db = function(user,pass){
    return new Db(user,pass);
}

//CS:GO Drawing Board is a web application that allows users to develop CS:GO strategies.
//
//Copyright 2014 Duck Syrup
//
//This file is part of CS:GO Drawing Board.
//
//CS:GO Drawing Board is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//CS:GO Drawing Board is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Affero General Public License for more details.
//
//You should have received a copy of the GNU Affero General Public License
//along with CS:GO Drawing Board.  If not, see <http://www.gnu.org/licenses/>.<|endoftext|>


<commit_before>var require = patchRequire(require);
var utils = require('utils');
var magento = require('./src/magento');
var app = function() {
	app.super_.apply(this, arguments);

	this.base_url = '';
};

utils.inherits(app, magento);
<commit_msg>Updated the default app js file so by default it works as Magento Demo store<commit_after>var require = patchRequire(require);
var utils = require('utils');
var magento = require('./src/magento');
var app = function() {
	app.super_.apply(this, arguments);

	// Customize the default Magento application settings here
	// this.base_url = 'http://www.your-application.example.com';
};

utils.inherits(app, magento);
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var resolve = require('resolve');
var glob = require('glob');
var pathParse = require('path-parse');
var pathFormat = require('path-format');
var async = require('async');

var opts = {
  exts: '.@(sa|c|sc)ss',
  pfx: '?(_)'
};

var buildSassGlob = function (path) {
  var parsedPath = pathParse(path);
  if (parsedPath.ext === '' || opts.exts !== parsedPath.ext) {
    parsedPath.ext = opts.exts;
    parsedPath.base = opts.pfx + parsedPath.base + opts.exts;
    parsedPath.name = opts.pfx + parsedPath.name;
  }

  return pathFormat(parsedPath);
};

/**
 * Resolves `url` and calls `done(error, null)` when done.
 * Note that the `done()` function args don't match what node-sass expects.
 */

var resolver = function (url, baseDir, done) {
  resolve(url, {
    basedir: baseDir,
    extensions: [ '.scss', '.sass', '.css' ],
    pathFilter: function (pkg, absPath, relativePath) {
      var globbedPath = buildSassGlob(absPath);
      var paths = glob.sync(globbedPath);
      var resolvedPath = paths && paths[0];
      if (resolvedPath) {
        return path.join(path.dirname(relativePath), path.basename(resolvedPath));
      }
    }
  }, function (err, file) {
    if (err) return done(err);

    // Strip the extension so .css gets evaluated properly as .scss
    file = file.replace(/\.(js|(sa|sc|c)ss)$/, '');
    done(null, file);
  });
};

/**
 * Builds `{file}` or `{contents}` (as node-sass expects) from a list of files.
 */

var importify = function (files) {
  if (files.length === 1) {
    return { file: files[0] };
  } else {
    var contents = files.map(function (fname) {
      return '@import ' + JSON.stringify(fname) + ';';
    }).join('\n');

    return { contents: contents };
  }
};

module.exports = function (url, file, done) {
  var baseDir = path.dirname(file);
  var fullPath = path.resolve(baseDir, url);
  var formattedPath = buildSassGlob(fullPath);

  glob(formattedPath, function (err, urls) {
    if (err) throw err;

    if (urls.length === 0) {
      glob(fullPath, function (err, dirs) {
        if (err) throw err;

        if (dirs.length === 0) {
          resolver(url, baseDir, function (err, results) {
            if (err) throw err;
            done(importify([results]));
          });
        }

        if (dirs.length === 1) {
          resolver(dirs[0], baseDir, function (err, results) {
            if (err) throw err;
            done(importify([results]));
          });
        }
      });
    }

    if (urls.length === 0) return;

    // Resolve all of `urls` through resolver(); then compile them into
    // '@import' statements.
    async.parallel(
      urls.map(function (url) {
        return function (callback) {
          resolver(url, baseDir, callback);
        };
      })
    , function (err, filenames) {
      if (err) throw err;
      done(importify(filenames));
    });
  });
};
<commit_msg>chore: fixed formatting issues<commit_after>'use strict';

var path = require('path');
var resolve = require('resolve');
var glob = require('glob');
var pathParse = require('path-parse');
var pathFormat = require('path-format');
var async = require('async');

var opts = {
  exts: '.@(sa|c|sc)ss',
  pfx: '?(_)'
};

var buildSassGlob = function (path) {
  var parsedPath = pathParse(path);
  if (parsedPath.ext === '' || opts.exts !== parsedPath.ext) {
    parsedPath.ext = opts.exts;
    parsedPath.base = opts.pfx + parsedPath.base + opts.exts;
    parsedPath.name = opts.pfx + parsedPath.name;
  }

  return pathFormat(parsedPath);
};

/**
 * Resolves `url` and calls `done(error, null)` when done.
 * Note that the `done()` function args don't match what node-sass expects.
 */

var resolver = function (url, baseDir, done) {
  resolve(url, {
    basedir: baseDir,
    extensions: [ '.scss', '.sass', '.css' ],
    pathFilter: function (pkg, absPath, relativePath) {
      var globbedPath = buildSassGlob(absPath);
      var paths = glob.sync(globbedPath);
      var resolvedPath = paths && paths[0];
      if (resolvedPath) {
        return path.join(path.dirname(relativePath), path.basename(resolvedPath));
      }
    }
  }, function (err, file) {
    if (err) return done(err);

    // Strip the extension so .css gets evaluated properly as .scss
    file = file.replace(/\.(js|(sa|sc|c)ss)$/, '');
    done(null, file);
  });
};

/**
 * Builds `{file}` or `{contents}` (as node-sass expects) from a list of files.
 */

var importify = function (files) {
  if (files.length === 1) {
    return { file: files[0] };
  } else {
    var contents = files.map(function (fname) {
      return '@import ' + JSON.stringify(fname) + ';';
    }).join('\n');

    return { contents: contents };
  }
};

module.exports = function (url, file, done) {
  var baseDir = path.dirname(file);
  var fullPath = path.resolve(baseDir, url);
  var formattedPath = buildSassGlob(fullPath);

  glob(formattedPath, function (err, urls) {
    if (err) throw err;

    if (urls.length === 0) {
      glob(fullPath, function (err, dirs) {
        if (err) throw err;

        if (dirs.length === 0) {
          resolver(url, baseDir, function (err, results) {
            if (err) throw err;
            done(importify([results]));
          });
        }

        if (dirs.length === 1) {
          resolver(dirs[0], baseDir, function (err, results) {
            if (err) throw err;
            done(importify([results]));
          });
        }
      });
    }

    if (urls.length === 0) return;

    // Resolve all of `urls` through resolver(); then compile them into
    // '@import' statements.
    async.parallel(urls.map(function (url) {
      return function (callback) {
        resolver(url, baseDir, callback);
      };
    }), function (err, filenames) {
      if (err) throw err;
      done(importify(filenames));
    });
  });
};
<|endoftext|>