<commit_before>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

const logger = require('_pr/logger')(module);
const dateUtil = require('_pr/lib/utils/dateUtil');
const monitorsModel = require('_pr/model/monitors');
const appConfig = require('_pr/config');
var fileUpload = require('_pr/model/file-upload/file-upload');

var monitorsService = module.exports = {};

monitorsService.checkIfMonitorExists = function (monitorId, callback) {
    monitorsModel.getById(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            return callback(null, monitor);
        }
    });
};

monitorsService.formatResponse = function (monitor, callback) {
    var formatted = {};
    switch (monitor.type) {
        case 'sensu':
        case 'Sensu':
            formatted._id = monitor._id;
            formatted.name = monitor.name;
            formatted.type = monitor.type;
            if (monitor.organization.length) {
                formatted.organization = {
                    id: monitor.organization[0].rowid,
                    name: monitor.organization[0].orgname
                };
            }
            formatted.parameters = monitor.parameters;
            if (formatted.parameters.transportProtocolParameters['password']) {
                delete formatted.parameters.transportProtocolParameters['password'];
            }
            if (monitor.parameters.transportProtocol === 'rabbitmq' && monitor.parameters.transportProtocolParameters.ssl) {
                fileUpload.getReadStreamFileByFileId(monitor.parameters.transportProtocolParameters.ssl.certChainFileId, function (err, file) {
                    delete formatted.parameters.transportProtocolParameters.ssl.certChainFileId;
                    if (err) {
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile'] = null;
                    } else {
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile'] = {};
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile']['id'] = monitor.parameters.transportProtocolParameters.ssl.certChainFileId;
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile']['name'] = file.fileName;
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile']['file'] = file.fileData;
                    }
                    fileUpload.getReadStreamFileByFileId(monitor.parameters.transportProtocolParameters.ssl.privateKeyFileId, function (err, file) {
                        delete formatted.parameters.transportProtocolParameters.ssl.privateKeyFileId;
                        if (err) {
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile'] = null;
                        } else {
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile'] = {};
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile']['id'] = monitor.parameters.transportProtocolParameters.ssl.privateKeyFileId;
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile']['name'] = file.fileName;
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile']['file'] = file.fileData;
                        }
                        callback(formatted);
                    });
                });
            } else {
                callback(formatted);
            }
            break;
        default:
            callback(null);
    }
};

monitorsService.createMonitor = function (monitorsObj, callback) {

    switch (monitorsObj.type) {
        case 'sensu':
        case 'Sensu':
            var saveobj = {};
            saveobj['orgId'] = monitorsObj['orgId'];
            saveobj['type'] = monitorsObj['type'];
            saveobj['name'] = monitorsObj['name'];
            saveobj['parameters'] = {};
            saveobj['parameters']['url'] = monitorsObj['parameters']['url'];
            saveobj['parameters']['transportProtocol'] = monitorsObj['parameters']['transportProtocol'];
            saveobj['parameters']['transportProtocolParameters'] = {};
            saveobj['parameters']['transportProtocolParameters']['host'] = monitorsObj['parameters']['transportProtocolParameters']['host'];
            saveobj['parameters']['transportProtocolParameters']['port'] = monitorsObj['parameters']['transportProtocolParameters']['port'];
            saveobj['parameters']['transportProtocolParameters']['password'] = monitorsObj['parameters']['transportProtocolParameters']['password'];
            if (monitorsObj['parameters']['transportProtocol'] === 'rabbitmq') {
                saveobj['parameters']['transportProtocolParameters']['vhost'] = monitorsObj['parameters']['transportProtocolParameters']['vhost'];
                saveobj['parameters']['transportProtocolParameters']['user'] = monitorsObj['parameters']['transportProtocolParameters']['user'];
                saveobj['parameters']['transportProtocolParameters']['heartbeat'] = monitorsObj['parameters']['transportProtocolParameters']['heartbeat'];
                saveobj['parameters']['transportProtocolParameters']['prefetch'] = monitorsObj['parameters']['transportProtocolParameters']['prefetch'];
                if (monitorsObj['parameters']['transportProtocolParameters']['ssl']) {
                    saveobj['parameters']['transportProtocolParameters']['ssl'] = {};
                    saveobj['parameters']['transportProtocolParameters']['ssl']['certChainFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['certChainFileId'];
                    saveobj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId'];
                }
            }
            monitorsModel.createNew(saveobj, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }

};

monitorsService.updateMonitor = function updateMonitor(monitorId, monitorsObj, callback) {
    switch (monitorsObj.type) {
        case 'sensu':
        case 'Sensu':
            var updateFields = {};
            updateFields['orgId'] = monitorsObj['orgId'];
            updateFields['type'] = monitorsObj['type'];
            updateFields['name'] = monitorsObj['name'];
            updateFields['parameters.url'] = monitorsObj['parameters']['url'];
            updateFields['parameters.transportProtocol'] = monitorsObj['parameters']['transportProtocol'];
            updateFields['parameters.transportProtocolParameters.host'] = monitorsObj['parameters']['transportProtocolParameters']['host'];
            updateFields['parameters.transportProtocolParameters.port'] = monitorsObj['parameters']['transportProtocolParameters']['port'];
            if (monitorsObj['parameters']['transportProtocolParameters']['password']) {
                updateFields['parameters.transportProtocolParameters.password'] = monitorsObj['parameters']['transportProtocolParameters']['password'];
            }
            if (monitorsObj['parameters']['transportProtocol'] === 'rabbitmq') {
                updateFields['parameters.transportProtocolParameters.vhost'] = monitorsObj['parameters']['transportProtocolParameters']['vhost'];
                updateFields['parameters.transportProtocolParameters.user'] = monitorsObj['parameters']['transportProtocolParameters']['user'];
                updateFields['parameters.transportProtocolParameters.heartbeat'] = monitorsObj['parameters']['transportProtocolParameters']['heartbeat'];
                updateFields['parameters.transportProtocolParameters.prefetch'] = monitorsObj['parameters']['transportProtocolParameters']['prefetch'];
                if (monitorsObj['parameters']['transportProtocolParameters']['ssl']) {
                    if (monitorsObj['parameters']['transportProtocolParameters']['ssl']['certChainFileId']) {
                        updateFields['parameters.transportProtocolParameters.ssl.certChainFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['certChainFileId'];
                    }
                    if (monitorsObj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId']) {
                        updateFields['parameters.transportProtocolParameters.ssl.privateKeyFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId'];
                    }

                }
            }
            monitorsModel.updateMonitors(monitorId, updateFields, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }
};

monitorsService.deleteMonitors = function (monitorId, callback) {
    monitorsModel.deleteMonitors(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

monitorsService.getMonitors = function (query, callback) {
    var params = {};
    logger.debug('get monitors');
    if ('filterBy' in query) {
        params = monitorsService.parseFilterBy(query.filterBy);
    }
    monitorsModel.getMonitors(params, function (err, monitors) {
        if (err) {
            logger.error(err);
            var err = new Error('Internal Server Error');
            err.status = 500;
            callback(err);
        } else {
            var res = [];
            if (monitors.length > 0) {
                for (i = 0; i < monitors.length; i++) {
                    monitorsService.formatResponse(monitors[i], function (monitor) {
                        res.push(monitor);
                        if (res.length === monitors.length) {
                            callback(null, res);
                        }
                    });
                }
            }
            callback(null, res);
        }
    });
};

monitorsService.getMonitor = function (monitorId, callback) {
    monitorsModel.getMonitor(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal Server Error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else if (monitor) {
            monitorsService.formatResponse(monitor, function (monitor) {
                callback(null, monitor);
            });
        }
    });
};

// @TODO Query builder to be made generic
monitorsService.parseFilterBy = function (filterByString) {
    var filterQuery = {};

    var filters = filterByString.split('+');
    for (var i = 0; i < filters.length; i++) {
        var filter = filters[i].split(':');
        var filterQueryValues = filter[1].split(",");

        filterQuery[filter[0]] = {'$in': filterQueryValues};
    }

    return filterQuery;
};
<commit_msg>fix for fileid issue<commit_after>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

const logger = require('_pr/logger')(module);
const dateUtil = require('_pr/lib/utils/dateUtil');
const monitorsModel = require('_pr/model/monitors');
const appConfig = require('_pr/config');
var fileUpload = require('_pr/model/file-upload/file-upload');

var monitorsService = module.exports = {};

monitorsService.checkIfMonitorExists = function (monitorId, callback) {
    monitorsModel.getById(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            return callback(null, monitor);
        }
    });
};

monitorsService.formatResponse = function (monitor, callback) {
    var formatted = {};
    switch (monitor.type) {
        case 'sensu':
        case 'Sensu':
            formatted._id = monitor._id;
            formatted.name = monitor.name;
            formatted.type = monitor.type;
            if (monitor.organization.length) {
                formatted.organization = {
                    id: monitor.organization[0].rowid,
                    name: monitor.organization[0].orgname
                };
            }
            formatted.parameters = monitor.parameters;
            if (formatted.parameters.transportProtocolParameters['password']) {
                delete formatted.parameters.transportProtocolParameters['password'];
            }
            if (monitor.parameters.transportProtocol === 'rabbitmq' && monitor.parameters.transportProtocolParameters.ssl) {
                fileUpload.getReadStreamFileByFileId(monitor.parameters.transportProtocolParameters.ssl.certChainFileId, function (err, file) {
                    var certChainFileId =  monitor.parameters.transportProtocolParameters.ssl.certChainFileId;
                    delete formatted.parameters.transportProtocolParameters.ssl.certChainFileId;
                    if (err) {
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile'] = null;
                    } else {
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile'] = {};
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile']['id'] = certChainFileId;
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile']['name'] = file.fileName;
                        formatted.parameters.transportProtocolParameters.ssl['certChainFile']['file'] = file.fileData;
                    }
                    fileUpload.getReadStreamFileByFileId(monitor.parameters.transportProtocolParameters.ssl.privateKeyFileId, function (err, file) {
                        var privateKeyFileId =  monitor.parameters.transportProtocolParameters.ssl.privateKeyFileId;
                        delete formatted.parameters.transportProtocolParameters.ssl.privateKeyFileId;
                        if (err) {
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile'] = null;
                        } else {
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile'] = {};
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile']['id'] = privateKeyFileId;
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile']['name'] = file.fileName;
                            formatted.parameters.transportProtocolParameters.ssl['privateKeyFile']['file'] = file.fileData;
                        }
                        callback(formatted);
                    });
                });
            } else {
                callback(formatted);
            }
            break;
        default:
            callback(null);
    }
};

monitorsService.createMonitor = function (monitorsObj, callback) {

    switch (monitorsObj.type) {
        case 'sensu':
        case 'Sensu':
            var saveobj = {};
            saveobj['orgId'] = monitorsObj['orgId'];
            saveobj['type'] = monitorsObj['type'];
            saveobj['name'] = monitorsObj['name'];
            saveobj['parameters'] = {};
            saveobj['parameters']['url'] = monitorsObj['parameters']['url'];
            saveobj['parameters']['transportProtocol'] = monitorsObj['parameters']['transportProtocol'];
            saveobj['parameters']['transportProtocolParameters'] = {};
            saveobj['parameters']['transportProtocolParameters']['host'] = monitorsObj['parameters']['transportProtocolParameters']['host'];
            saveobj['parameters']['transportProtocolParameters']['port'] = monitorsObj['parameters']['transportProtocolParameters']['port'];
            saveobj['parameters']['transportProtocolParameters']['password'] = monitorsObj['parameters']['transportProtocolParameters']['password'];
            if (monitorsObj['parameters']['transportProtocol'] === 'rabbitmq') {
                saveobj['parameters']['transportProtocolParameters']['vhost'] = monitorsObj['parameters']['transportProtocolParameters']['vhost'];
                saveobj['parameters']['transportProtocolParameters']['user'] = monitorsObj['parameters']['transportProtocolParameters']['user'];
                saveobj['parameters']['transportProtocolParameters']['heartbeat'] = monitorsObj['parameters']['transportProtocolParameters']['heartbeat'];
                saveobj['parameters']['transportProtocolParameters']['prefetch'] = monitorsObj['parameters']['transportProtocolParameters']['prefetch'];
                if (monitorsObj['parameters']['transportProtocolParameters']['ssl']) {
                    saveobj['parameters']['transportProtocolParameters']['ssl'] = {};
                    saveobj['parameters']['transportProtocolParameters']['ssl']['certChainFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['certChainFileId'];
                    saveobj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId'];
                }
            }
            monitorsModel.createNew(saveobj, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }

};

monitorsService.updateMonitor = function updateMonitor(monitorId, monitorsObj, callback) {
    switch (monitorsObj.type) {
        case 'sensu':
        case 'Sensu':
            var updateFields = {};
            updateFields['orgId'] = monitorsObj['orgId'];
            updateFields['type'] = monitorsObj['type'];
            updateFields['name'] = monitorsObj['name'];
            updateFields['parameters.url'] = monitorsObj['parameters']['url'];
            updateFields['parameters.transportProtocol'] = monitorsObj['parameters']['transportProtocol'];
            updateFields['parameters.transportProtocolParameters.host'] = monitorsObj['parameters']['transportProtocolParameters']['host'];
            updateFields['parameters.transportProtocolParameters.port'] = monitorsObj['parameters']['transportProtocolParameters']['port'];
            if (monitorsObj['parameters']['transportProtocolParameters']['password']) {
                updateFields['parameters.transportProtocolParameters.password'] = monitorsObj['parameters']['transportProtocolParameters']['password'];
            }
            if (monitorsObj['parameters']['transportProtocol'] === 'rabbitmq') {
                updateFields['parameters.transportProtocolParameters.vhost'] = monitorsObj['parameters']['transportProtocolParameters']['vhost'];
                updateFields['parameters.transportProtocolParameters.user'] = monitorsObj['parameters']['transportProtocolParameters']['user'];
                updateFields['parameters.transportProtocolParameters.heartbeat'] = monitorsObj['parameters']['transportProtocolParameters']['heartbeat'];
                updateFields['parameters.transportProtocolParameters.prefetch'] = monitorsObj['parameters']['transportProtocolParameters']['prefetch'];
                if (monitorsObj['parameters']['transportProtocolParameters']['ssl']) {
                    if (monitorsObj['parameters']['transportProtocolParameters']['ssl']['certChainFileId']) {
                        updateFields['parameters.transportProtocolParameters.ssl.certChainFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['certChainFileId'];
                    }
                    if (monitorsObj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId']) {
                        updateFields['parameters.transportProtocolParameters.ssl.privateKeyFileId'] = monitorsObj['parameters']['transportProtocolParameters']['ssl']['privateKeyFileId'];
                    }

                }
            }
            monitorsModel.updateMonitors(monitorId, updateFields, function (err, monitor) {
                //@TODO To be generalized
                if (err && err.name === 'ValidationError') {
                    var err = new Error('Bad Request');
                    err.status = 400;
                    callback(err);
                } else if (err) {
                    var err = new Error('Internal Server Error');
                    err.status = 500;
                    callback(err);
                } else {
                    callback(null, monitor);
                }
            });
            break;
        default:
            var err = new Error('Bad request');
            err.status = 400;
            return callback(err);
            break;
    }
};

monitorsService.deleteMonitors = function (monitorId, callback) {
    monitorsModel.deleteMonitors(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal server error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else {
            // @TODO response to be decided
            return callback(null, {});
        }
    });
};

monitorsService.getMonitors = function (query, callback) {
    var params = {};
    logger.debug('get monitors');
    if ('filterBy' in query) {
        params = monitorsService.parseFilterBy(query.filterBy);
    }
    monitorsModel.getMonitors(params, function (err, monitors) {
        if (err) {
            logger.error(err);
            var err = new Error('Internal Server Error');
            err.status = 500;
            callback(err);
        } else {
            var res = [];
            if (monitors.length > 0) {
                for (i = 0; i < monitors.length; i++) {
                    monitorsService.formatResponse(monitors[i], function (monitor) {
                        res.push(monitor);
                        if (res.length === monitors.length) {
                            callback(null, res);
                        }
                    });
                }
            } else {
                callback(null, res);
            }
        }
    });
};

monitorsService.getMonitor = function (monitorId, callback) {
    monitorsModel.getMonitor(monitorId, function (err, monitor) {
        if (err) {
            var err = new Error('Internal Server Error');
            err.status = 500;
            return callback(err);
        } else if (!monitor) {
            var err = new Error('Monitor not found');
            err.status = 404;
            return callback(err);
        } else if (monitor) {
            monitorsService.formatResponse(monitor, function (monitor) {
                callback(null, monitor);
            });
        }
    });
};

// @TODO Query builder to be made generic
monitorsService.parseFilterBy = function (filterByString) {
    var filterQuery = {};

    var filters = filterByString.split('+');
    for (var i = 0; i < filters.length; i++) {
        var filter = filters[i].split(':');
        var filterQueryValues = filter[1].split(",");

        filterQuery[filter[0]] = {'$in': filterQueryValues};
    }

    return filterQuery;
};
<|endoftext|>


<commit_before>import {GraphQLNonNull, GraphQLID, GraphQLString} from 'graphql'
import {GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLList} from 'graphql/type'

import {GraphQLDateTime} from 'graphql-custom-types'
import {ThinCycle} from '../../../../server/graphql/models/Cycle/schema'
import {ThinProject} from '../../../../server/graphql/models/Project/schema'

export const SubjectTypeEnum = new GraphQLEnumType({
  name: 'SubjectTypeEnum',
  values: {
    team: {description: 'A multipart subject requiring responses about each member of a project team'},
    player: {description: 'A player in the game'},
  }
})

export const ResponseTypeEnum = new GraphQLEnumType({
  name: 'ResponseTypeEnum',
  values: {
    percentage: {description: 'A multipart question whose responses must add up to 100%'},
    text: {description: 'A free form text response'},
  }
})

const CommonSurveyQuestionFields = {
  id: {type: new GraphQLNonNull(GraphQLID), description: 'The id of the question'},
  subjectType: {type: new GraphQLNonNull(SubjectTypeEnum), description: 'The type of the subject '},
  responseType: {type: new GraphQLNonNull(ResponseTypeEnum), description: 'The expected type of the response'},
  body: {type: new GraphQLNonNull(GraphQLString), description: 'The body of the question'},
}

const SurveyQuestionInterface = new GraphQLInterfaceType({
  name: 'SurveyQuestionInterface',
  fields: () => CommonSurveyQuestionFields,
  resolveType: resolveSurveyQuestionType,
})

export const PlayerSubject = new GraphQLObjectType({
  name: 'PlayerSubject',
  description: 'A describes a player that is the subject of a question',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLID),
      description: 'The player\'s UUID'
    },
    name: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The player\'s name'
    },
    handle: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The player\'s handle'
    },
  })
})

export const MultiSubjectSurveyQuestion = new GraphQLObjectType({
  name: 'MultiSubjectSurveyQuestion',
  description: 'A survey question about multiple subjects',
  interfaces: [SurveyQuestionInterface],
  fields: () => (Object.assign({},
    CommonSurveyQuestionFields,
    {
      subject: {
        type: new GraphQLNonNull(new GraphQLList(PlayerSubject)),
        description: 'The list of ids of the persons or things this question is asking about'
      },
    }
  ))
})

export const SingleSubjectSurveyQuestion = new GraphQLObjectType({
  name: 'SingleSubjectSurveyQuestion',
  description: 'A survey question about a single subject',
  interfaces: [SurveyQuestionInterface],
  fields: () => (Object.assign({},
    CommonSurveyQuestionFields,
    {
      subject: {
        type: new GraphQLNonNull(PlayerSubject),
        description: 'The id of the person or this question is asking about'
      },
    }
  ))
})

export const SurveyQuestion = new GraphQLUnionType({
  name: 'SurveyQuestion',
  types: [SingleSubjectSurveyQuestion, MultiSubjectSurveyQuestion],
  resolveType: resolveSurveyQuestionType,
})

function resolveSurveyQuestionType(value) {
  if (Array.isArray(value.subject)) {
    return MultiSubjectSurveyQuestion
  }
  return SingleSubjectSurveyQuestion
}

export const Survey = new GraphQLObjectType({
  name: 'Survey',
  description: 'A survey of questions used for retrospectives',
  fields: () => ({
    id: {type: new GraphQLNonNull(GraphQLID), description: "The survey's user UUID"},
    project: {type: ThinProject, description: "The player's chapter"},
    cycle: {type: ThinCycle, description: "The cycle's chapter"},
    questions: {type: new GraphQLList(SurveyQuestion), description: 'The questions for the survey'},
    createdAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was created'},
    updatedAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was last updated'},
  })
})
<commit_msg>survey must have questions!<commit_after>import {GraphQLNonNull, GraphQLID, GraphQLString} from 'graphql'
import {GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLList} from 'graphql/type'

import {GraphQLDateTime} from 'graphql-custom-types'
import {ThinCycle} from '../../../../server/graphql/models/Cycle/schema'
import {ThinProject} from '../../../../server/graphql/models/Project/schema'

export const SubjectTypeEnum = new GraphQLEnumType({
  name: 'SubjectTypeEnum',
  values: {
    team: {description: 'A multipart subject requiring responses about each member of a project team'},
    player: {description: 'A player in the game'},
  }
})

export const ResponseTypeEnum = new GraphQLEnumType({
  name: 'ResponseTypeEnum',
  values: {
    percentage: {description: 'A multipart question whose responses must add up to 100%'},
    text: {description: 'A free form text response'},
  }
})

const CommonSurveyQuestionFields = {
  id: {type: new GraphQLNonNull(GraphQLID), description: 'The id of the question'},
  subjectType: {type: new GraphQLNonNull(SubjectTypeEnum), description: 'The type of the subject '},
  responseType: {type: new GraphQLNonNull(ResponseTypeEnum), description: 'The expected type of the response'},
  body: {type: new GraphQLNonNull(GraphQLString), description: 'The body of the question'},
}

const SurveyQuestionInterface = new GraphQLInterfaceType({
  name: 'SurveyQuestionInterface',
  fields: () => CommonSurveyQuestionFields,
  resolveType: resolveSurveyQuestionType,
})

export const PlayerSubject = new GraphQLObjectType({
  name: 'PlayerSubject',
  description: 'A describes a player that is the subject of a question',
  fields: () => ({
    id: {
      type: new GraphQLNonNull(GraphQLID),
      description: 'The player\'s UUID'
    },
    name: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The player\'s name'
    },
    handle: {
      type: new GraphQLNonNull(GraphQLString),
      description: 'The player\'s handle'
    },
  })
})

export const MultiSubjectSurveyQuestion = new GraphQLObjectType({
  name: 'MultiSubjectSurveyQuestion',
  description: 'A survey question about multiple subjects',
  interfaces: [SurveyQuestionInterface],
  fields: () => (Object.assign({},
    CommonSurveyQuestionFields,
    {
      subject: {
        type: new GraphQLNonNull(new GraphQLList(PlayerSubject)),
        description: 'The list of ids of the persons or things this question is asking about'
      },
    }
  ))
})

export const SingleSubjectSurveyQuestion = new GraphQLObjectType({
  name: 'SingleSubjectSurveyQuestion',
  description: 'A survey question about a single subject',
  interfaces: [SurveyQuestionInterface],
  fields: () => (Object.assign({},
    CommonSurveyQuestionFields,
    {
      subject: {
        type: new GraphQLNonNull(PlayerSubject),
        description: 'The id of the person or this question is asking about'
      },
    }
  ))
})

export const SurveyQuestion = new GraphQLUnionType({
  name: 'SurveyQuestion',
  types: [SingleSubjectSurveyQuestion, MultiSubjectSurveyQuestion],
  resolveType: resolveSurveyQuestionType,
})

function resolveSurveyQuestionType(value) {
  if (Array.isArray(value.subject)) {
    return MultiSubjectSurveyQuestion
  }
  return SingleSubjectSurveyQuestion
}

export const Survey = new GraphQLObjectType({
  name: 'Survey',
  description: 'A survey of questions used for retrospectives',
  fields: () => ({
    id: {type: new GraphQLNonNull(GraphQLID), description: "The survey's user UUID"},
    project: {type: ThinProject, description: "The player's chapter"},
    cycle: {type: ThinCycle, description: "The cycle's chapter"},
    questions: {type: new GraphQLNonNull(new GraphQLList(SurveyQuestion)), description: 'The questions for the survey'},
    createdAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was created'},
    updatedAt: {type: new GraphQLNonNull(GraphQLDateTime), description: 'When this record was last updated'},
  })
})
<|endoftext|>


<commit_before>module.exports = function getMine (req, res) {

    var fs = require('fs');

    var sess = req.session;
    var langId = (req.params.language_id || 'en');

    switch(langId){
        case 'en':
            return setAndsendLanguage('en');
        case 'fr':
            return setAndsendLanguage('fr');
        default:
            return setAndsendLanguage('en');
    }

    function setAndsendLanguage(langId){
        sess.language = langId;
        return res.json({data: getLanguage(langId)});
    }

    function getLanguage(langId){
        return JSON.parse(fs.readFileSync(__dirname + '../../../languages/'+langId+'.json', 'utf8'));
    }

}
<commit_msg>server side: update languages path<commit_after>module.exports = function getMine (req, res) {

    var fs = require('fs');

    var sess = req.session;
    var langId = (req.params.language_id || 'en');

    switch(langId){
        case 'en':
            return setAndsendLanguage('en');
        case 'fr':
            return setAndsendLanguage('fr');
        default:
            return setAndsendLanguage('en');
    }

    function setAndsendLanguage(langId){
        sess.language = langId;
        return res.json({data: getLanguage(langId)});
    }

    function getLanguage(langId){
        return JSON.parse(fs.readFileSync('server/languages/'+langId+'.json', 'utf8'));
    }

}
<|endoftext|>


<commit_before>'use strict';

module.exports = {
    error: {
        inUse: "{0} {1} is already in use",
        incorrectInput: "{0} is not correct",
        requiredProp: "{0} is required"
    },
    generateMessage: (messageType, args) => {
        let messageToReturn = messageType;

        args.forEach((arg, index) => {
            messageToReturn = messageToReturn.replace(`{${index}}`, arg)
        })

        return messageToReturn;
    }
};<commit_msg>Add new messages<commit_after>'use strict';

module.exports = {
    error: {
        fieldsRequired: "Please fill out all required fields",
        incorrectInput: "{0} is not correct",
        invalidCredentials: "Invalid password or username",
        internal: "Server Internal Error: 500",
        inUse: "{0} {1} is already in use",
        requiredProp: "{0} is required",
        minLength: "{0} must be atleast {1} characters long",
        notMatch: "{0} does not match {1}",
        whiteSpace: "{0} cannot be whitspace"
    },
    generateMessage: (messageType, args) => {
        let messageToReturn = messageType;

        args.forEach((arg, index) => {
            messageToReturn = messageToReturn.replace(`{${index}}`, arg)
        })

        return messageToReturn;
    }
};<|endoftext|>


<commit_before>require('dotenv').load();

var Twitter = require('node-tweet-stream')

var stream = new Twitter({
  consumer_key:          process.env.TW_KEY,
  consumer_secret:       process.env.TW_SECRET,
  token:                 process.env.TW_TOKEN,
  token_secret:          process.env.TW_TOKEN_SECRET
});

var urls = [
    'http://www.filfre.net/2015/04/the-68000-wars-part-3-we-made-amiga-they-fucked-it-up/',
    'http://thisisvoid.org/',
    'https://dncmagazine.blob.core.windows.net/downloads/AngularCheatSheet-DNCMagazine.pdf',
    'https://docs.google.com/document/d/1QZxArgMwidgCrAbuSikcB2iBxkffH6w0YB0C1qCsuH0',
    'http://utcc.utoronto.ca/~cks/space/blog/linux/SystemdAndSyslog',
    'http://www.nytimes.com/2015/04/08/opinion/yes-we-were-warned-about-ebola.html',
    'http://www.devttys0.com/2015/04/hacking-the-d-link-dir-890l/',
    'https://www.eff.org/press/releases/eff-busts-podcasting-patent-invalidating-key-claims-patent-office',
    'http://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html',
    'https://code.facebook.com/posts/1639473982937255/updating-our-open-source-patent-grant/',
    'http://quantombone.blogspot.com/2015/04/deep-learning-vs-probabilistic.html',
    'https://mozilla.github.io/server-side-tls/ssl-config-generator/?1',
    'https://github.com/dullgiulio/perso/releases/tag/v0.1',
    'http://blog.easydns.org/2015/04/10/why-we-will-not-be-registering-easydns-sucks/',
    'item?id=9356332',
    'http://jdh.hamkins.org/math-for-eight-year-olds',
    'https://blogs.janestreet.com/building-a-lower-latency-gc/',
    'http://educationware.net/introduction-to-linux-free-course-from-the-linux-foundation/',
    'http://blog.jgc.org/2015/04/the-one-line-you-should-add-to-every.html',
    'http://www.reenigne.org/blog/1k-colours-on-cga-how-its-done/',
    'https://tibastral.github.io/markdownify/',
    'http://www.reenigne.org/blog/8088-pc-speaker-mod-player-how-its-done/',
    'item?id=9358843',
    'https://gist.github.com/ImJasonH/c00cdd7aece6945fb8ea',
    'http://home.web.cern.ch/about/updates/2015/04/first-successful-beam-record-energy-65-tev',
    'http://blog.jetbrains.com/dotnet/2015/04/10/introducing-resharper-cpp/',
    'https://in.news.yahoo.com/the-slave-ship-that-ran-from-kerala-to-new-orleans-085329807.html',
    'http://www.newyorker.com/magazine/2005/09/19/the-lost-city-of-z',
    'https://github.com/kgaughan/memoize.py',
    'http://sangaline.com/blog/optimizing_for_swype/'
];

var url = require('url');

var urls_to_track = urls.map(function(link) {
    var parsed_url = url.parse(link)
    if ( parsed_url.host) {
        var hostname = parsed_url.hostname.replace('www.', '')
        var trimmed_url = hostname + parsed_url.path
    }
    else {
        trimmed_url = 'news.ycombinator.com/' + link
    }
    return trimmed_url
})
.filter(function(url) {
    return url.length < 60
})
.join(',')

console.log(urls_to_track);
stream.track(urls_to_track);

stream.on('tweet', function(t){
  console.log(t.text)
});

stream.on('error', function (err) {
  console.log('Oh no')
})
<commit_msg>Removed trailing / from urls<commit_after>require('dotenv').load();

var Twitter = require('node-tweet-stream')

var stream = new Twitter({
  consumer_key:          process.env.TW_KEY,
  consumer_secret:       process.env.TW_SECRET,
  token:                 process.env.TW_TOKEN,
  token_secret:          process.env.TW_TOKEN_SECRET
});

var urls = [
    'http://www.filfre.net/2015/04/the-68000-wars-part-3-we-made-amiga-they-fucked-it-up/',
    'http://thisisvoid.org',
    'https://dncmagazine.blob.core.windows.net/downloads/AngularCheatSheet-DNCMagazine.pdf',
    'https://docs.google.com/document/d/1QZxArgMwidgCrAbuSikcB2iBxkffH6w0YB0C1qCsuH0',
    'http://utcc.utoronto.ca/~cks/space/blog/linux/SystemdAndSyslog',
    'http://www.nytimes.com/2015/04/08/opinion/yes-we-were-warned-about-ebola.html',
    'http://www.devttys0.com/2015/04/hacking-the-d-link-dir-890l/',
    'https://www.eff.org/press/releases/eff-busts-podcasting-patent-invalidating-key-claims-patent-office',
    'http://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html',
    'https://code.facebook.com/posts/1639473982937255/updating-our-open-source-patent-grant/',
    'http://quantombone.blogspot.com/2015/04/deep-learning-vs-probabilistic.html',
    'https://mozilla.github.io/server-side-tls/ssl-config-generator/?1',
    'https://github.com/dullgiulio/perso/releases/tag/v0.1',
    'http://blog.easydns.org/2015/04/10/why-we-will-not-be-registering-easydns-sucks/',
    'item?id=9356332',
    'http://jdh.hamkins.org/math-for-eight-year-olds',
    'https://blogs.janestreet.com/building-a-lower-latency-gc/',
    'http://educationware.net/introduction-to-linux-free-course-from-the-linux-foundation/',
    'http://blog.jgc.org/2015/04/the-one-line-you-should-add-to-every.html',
    'http://www.reenigne.org/blog/1k-colours-on-cga-how-its-done/',
    'https://tibastral.github.io/markdownify/',
    'http://www.reenigne.org/blog/8088-pc-speaker-mod-player-how-its-done/',
    'item?id=9358843',
    'https://gist.github.com/ImJasonH/c00cdd7aece6945fb8ea',
    'http://home.web.cern.ch/about/updates/2015/04/first-successful-beam-record-energy-65-tev',
    'http://blog.jetbrains.com/dotnet/2015/04/10/introducing-resharper-cpp/',
    'https://in.news.yahoo.com/the-slave-ship-that-ran-from-kerala-to-new-orleans-085329807.html',
    'http://www.newyorker.com/magazine/2005/09/19/the-lost-city-of-z',
    'https://github.com/kgaughan/memoize.py',
    'http://sangaline.com/blog/optimizing_for_swype/'
];

var url = require('url');

var urls_to_track = urls.map(function(link) {
    var parsed_url = url.parse(link)
    if ( parsed_url.host) {
        var hostname = parsed_url.hostname.replace('www.', '')
        var trimmed_url = hostname + parsed_url.path.replace(new RegExp('\/$', 'g'), '')
    }
    else {
        trimmed_url = 'news.ycombinator.com/' + link
    }
    return trimmed_url
})
.filter(function(url) {
    return url.length < 60
})
.join(',')

console.log(urls_to_track);
stream.track(urls_to_track);

stream.on('tweet', function(t){
  console.log(t.text)
});

stream.on('error', function (err) {
  console.log('Oh no')
})
<|endoftext|>


<commit_before>declare module radium {
	declare function exports(element: ReactClass<any>): ReactClass<any>;
}
<commit_msg>chore(flow): add type definitions for Radium<commit_after>declare module 'radium' {
  declare type PluginResult = {
    // Merged into the component directly. Useful for storing things for which you
    // don't need to re-render, event subscriptions, for instance.
    componentFields?: ?Object,

    // Merged into a Radium controlled global state object. Use this instead of
    // module level state for ease of clearing state between tests.
    globalState?: ?Object,

    // Merged into the rendered element's props.
    props?: ?Object,

    // Replaces (not merged into) the rendered element's style property.
    style?: ?Object,
  };

  declare type PluginConfig = {
    // Adds a chunk of css to the root style sheet
    addCSS: (css: string) => {remove: () => void},

    // Helper function when adding CSS
    appendImportantToEachValue: (style: Object) => Object;

    // May not be readable if code has been minified
    componentName: string,

    // The Radium configuration
    config: RadiumConfig,

    // Converts an object of CSS rules to a string, for use with addCSS
    cssRuleSetToString: (
      selector: string,
      rules: Object,
      userAgent: ?string,
    ) => string,

    // Retrieve the value of a field on the component
    getComponentField: (key: string) => mixed,

    // Retrieve the value of a field global to the Radium module
    // Used so that tests can easily clear global state.
    getGlobalState: (key: string) => mixed,

    // Retrieve the value of some state specific to the rendered element.
    // Requires the element to have a unique key or ref or for an element key
    // to be passed in.
    getState: (stateKey: string, elementKey?: string) => mixed,

    // Helper function when adding CSS
    hash: (data: string) => string,

    // Returns true if the value is a nested style object
    isNestedStyle: (value: mixed) => bool,

    // Access to the mergeStyles utility
    mergeStyles: (styles: Array<Object>) => Object,

    // The props of the rendered element. This can be changed by each plugin,
    // and successive plugins will see the result of previous plugins.
    props: Object,

    // Calls setState on the component with the given key and value.
    // By default this is specific to the rendered element, but you can override
    // by passing in the `elementKey` parameter.
    setState: (stateKey: string, value: mixed, elementKey?: string) => mixed,

    // The style prop of the rendered element. This can be changed by each plugin,
    // and successive plugins will see the result of previous plugins. Kept
    // separate from `props` for ease of use.
    style: Object,

    // uses the exenv npm module
    ExecutionEnvironment: {
      canUseEventListeners: bool,
      canUseDOM: bool,
    }
  };

  declare type MediaQueryListListener = (mql: MediaQueryList) => mixed;

  declare type MediaQueryList = {
    matches: bool;
    addListener(listener: MediaQueryListListener): void;
    removeListener(listener: MediaQueryListListener): void;
  };

  declare type Plugin = (pluginConfig: PluginConfig) => ?PluginResult;
  declare type MatchMediaType = (mediaQueryString: string) => MediaQueryList;

  declare type RadiumConfig = {
    matchMedia?: MatchMediaType,
    plugins?: Array<Plugin>,
    userAgent?: string,
  };
  declare class Radium {
    <T: ReactClass>(reactClass: T): T;
    <T: ReactClass>(config: RadiumConfig): (reactClass: T) => T;
    keyframes(animationObject: Object, name?: string): string;
    Style: React$Component<{scopeSelector: string}, {config?: ?RadiumConfig, rules: Object, scopeSelector?: ?string}>;
    StyleRoot: ReactClass;
    getState(state: Object, componentRef: string, property: ':active' | ':hover' | ':focus'): boolean;
  }
  declare var exports: Radium;
}
<|endoftext|>


<commit_before>function Online3DViewerLoad ()
{
	function LoadViewer (viewerElement)
	{
		var urls = viewerElement.getAttribute ('sourcefiles');
		if (urls === undefined || urls === null) {
			return;
		}

		var myThis = this;
		var urlList = urls.split ('|');
		JSM.ConvertURLListToJsonData (urlList, {
			onError : function () {
				var context = viewerElement.getContext ('2d');
				context.font = '12px Arial';
				context.fillText ('Error!', 0, 12);
				return;
			},
			onReady : function (fileNames, jsonData) {
				var viewerSettings = {
					cameraEyePosition : [6.0, -5.5, 4.0],
					cameraCenterPosition : [0.0, 0.0, 0.0],
					cameraUpVector : [0.0, 0.0, 1.0]
				};

				var viewer = new JSM.ThreeViewer ();
				if (!viewer.Start (viewerElement, viewerSettings)) {
					return;
				}

				var currentMeshIndex = 0;
				var environment = new JSM.AsyncEnvironment ({
					onStart : function (taskCount/*, meshes*/) {
						viewer.EnableDraw (false);
					},
					onProcess : function (currentTask, meshes) {
						while (currentMeshIndex < meshes.length) {
							viewer.AddMesh (meshes[currentMeshIndex]);
							currentMeshIndex = currentMeshIndex + 1;
						}
					},
					onFinish : function (meshes) {
						if (meshes.length > 0) {
							viewer.AdjustClippingPlanes (50.0);
							viewer.FitInWindow ();
						}
						viewer.EnableDraw (true);
						viewer.Draw ();
					}
				});
				JSM.ConvertJSONDataToThreeMeshes (jsonData, null, environment);
			}
		});
	}

	var viewers = document.getElementsByClassName ('3dviewer');
	var i;
	for (i = 0; i < viewers.length; i++) {
		LoadViewer (viewers[i]);
	}
}

window.addEventListener ('load', Online3DViewerLoad, true);
<commit_msg>Show error message in case of viewer error.<commit_after>function Online3DViewerLoad ()
{
	function LoadViewer (viewerElement)
	{
		function Error (viewerElement)
		{
			var context = viewerElement.getContext ('2d');
			context.font = '12px Arial';
			context.fillText ('Error!', 0, 12);
		}

		var urls = viewerElement.getAttribute ('sourcefiles');
		if (urls === undefined || urls === null) {
			return;
		}

		var myThis = this;
		var urlList = urls.split ('|');
		JSM.ConvertURLListToJsonData (urlList, {
			onError : function () {
				Error (viewerElement);
				return;
			},
			onReady : function (fileNames, jsonData) {
				var viewerSettings = {
					cameraEyePosition : [6.0, -5.5, 4.0],
					cameraCenterPosition : [0.0, 0.0, 0.0],
					cameraUpVector : [0.0, 0.0, 1.0]
				};

				var viewer = new JSM.ThreeViewer ();
				if (!viewer.Start (viewerElement, viewerSettings)) {
					Error (viewerElement);
					return;
				}

				var currentMeshIndex = 0;
				var environment = new JSM.AsyncEnvironment ({
					onStart : function (taskCount/*, meshes*/) {
						viewer.EnableDraw (false);
					},
					onProcess : function (currentTask, meshes) {
						while (currentMeshIndex < meshes.length) {
							viewer.AddMesh (meshes[currentMeshIndex]);
							currentMeshIndex = currentMeshIndex + 1;
						}
					},
					onFinish : function (meshes) {
						if (meshes.length > 0) {
							viewer.AdjustClippingPlanes (50.0);
							viewer.FitInWindow ();
						}
						viewer.EnableDraw (true);
						viewer.Draw ();
					}
				});
				JSM.ConvertJSONDataToThreeMeshes (jsonData, null, environment);
			}
		});
	}

	var viewers = document.getElementsByClassName ('3dviewer');
	var i;
	for (i = 0; i < viewers.length; i++) {
		LoadViewer (viewers[i]);
	}
}

window.addEventListener ('load', Online3DViewerLoad, true);
<|endoftext|>


<commit_before>var _ = require('lodash');
var Q = require('q');
var csvToObjectUtils = require('./csv-to-object-utils');
var businessFactory = require('./factories/BusinessFactory');
var mongoConnection = require('../mongo/mongoConnection');

function createBusinessRecords() {
    var deferred = Q.defer();

    var businessesPromise = csvToObjectUtils.readCSVFileToObjectsPromise(__dirname + '/businesses_plus.csv');
    var inspectionsPromise = csvToObjectUtils.readCSVFileToObjectsPromise(__dirname + '/inspections_plus.csv');
    var violationsPromise = csvToObjectUtils.readCSVFileToObjectsPromise(__dirname + 'violations_plus.csv');

    Q.all([businessesPromise,inspectionsPromise,violationsPromise]).then(function(x){

        var businesses = x[0];
        var inspections = x[1];
        var violations = x[2];

        var groupedInspections = _.groupBy(inspections,"business_id");
        var groupedViolations = _.groupBy(violations,"business_id");

        var businessModels = [];
        for (var i = 0; i < businesses.length; i++){
            var business = businesses[i];

            var inspectionsForBusiness = groupedInspections[business.business_id];
            var violationsForBusiness = groupedViolations[business.business_id];
            var model = businessFactory.create(business,inspectionsForBusiness,violationsForBusiness);
            businessModels.push(model);
        }
        deferred.resolve(businessModels);
    });
    return deferred.promise;
}
function saveToMongo(businessRecords){
    var deferred = Q.defer();
    mongoConnection.connect(app.config.database)
        .then(function(database){
           app.database = database;
            var promises = [];
            for (var i = 0; i < businessRecords.length; i++){
                promises.push(kickOffSavePromise(businessRecords[i]))
            }
            Q.all(promises).then(function(x){
               deferred.resolve(x);
            });
        });

    return deferred.promise;
}
function kickOffSavePromise(business){
    return business.save();
}
function run(){
    createBusinessRecords()
        .then(saveToMongo)
        .then(function() {
            console.log("Finished");
           process.exit();
        });
}
module.exports = exports;
exports.run = run;
var app = this;<commit_msg>typo in path<commit_after>var _ = require('lodash');
var Q = require('q');
var csvToObjectUtils = require('./csv-to-object-utils');
var businessFactory = require('./factories/BusinessFactory');
var mongoConnection = require('../mongo/mongoConnection');

function createBusinessRecords() {
    var deferred = Q.defer();

    var businessesPromise = csvToObjectUtils.readCSVFileToObjectsPromise(__dirname + '/businesses_plus.csv');
    var inspectionsPromise = csvToObjectUtils.readCSVFileToObjectsPromise(__dirname + '/inspections_plus.csv');
    var violationsPromise = csvToObjectUtils.readCSVFileToObjectsPromise(__dirname + '/violations_plus.csv');

    Q.all([businessesPromise,inspectionsPromise,violationsPromise]).then(function(x){

        var businesses = x[0];
        var inspections = x[1];
        var violations = x[2];

        var groupedInspections = _.groupBy(inspections,"business_id");
        var groupedViolations = _.groupBy(violations,"business_id");

        var businessModels = [];
        for (var i = 0; i < businesses.length; i++){
            var business = businesses[i];

            var inspectionsForBusiness = groupedInspections[business.business_id];
            var violationsForBusiness = groupedViolations[business.business_id];
            var model = businessFactory.create(business,inspectionsForBusiness,violationsForBusiness);
            businessModels.push(model);
        }
        deferred.resolve(businessModels);
    });
    return deferred.promise;
}
function saveToMongo(businessRecords){
    var deferred = Q.defer();
    mongoConnection.connect(app.config.database)
        .then(function(database){
           app.database = database;
            var promises = [];
            for (var i = 0; i < businessRecords.length; i++){
                promises.push(kickOffSavePromise(businessRecords[i]))
            }
            Q.all(promises).then(function(x){
               deferred.resolve(x);
            });
        });

    return deferred.promise;
}
function kickOffSavePromise(business){
    return business.save();
}
function run(){
    createBusinessRecords()
        .then(saveToMongo)
        .then(function() {
            console.log("Finished");
           process.exit();
        });
}
module.exports = exports;
exports.run = run;
var app = this;<|endoftext|>


<commit_before>const
    R = require('ramda'),
    Rx = require('rx'),
    context = document.getElementById("gameScreen").getContext("2d")

context.canvas.width = window.innerWidth * .95
context.canvas.height = window.innerWidth * .6

//Todo
//     only one downarrowdown instead of many, same with uparrowdown,
//         other signals are uparrowup and downarrowup.
//     use downarrowdown and uparrowdown flags in game state
//     remember conversation with my partner
//     explain what's been done since the last video
//     rename series to let's make a game
//     Can't do any more recordings until you've uploaded the ones you've made
//     add fire
//     draw star field image
//     draw asteroid image
//     draw collision image
//     make rocket appear vertically centered at first, and not exactly at the side
//     make rocket move faster (hard-code speed in a const?)
//     add rocket fire animation
//     make star field move
//     add single asteroid move towards you from right side
//     make asteroid appear randomly
//     make array of asteroids
//     collision detection
//     show collision image and then reset game
//     What else before I call it done?
//     put up on heroku and porfolio
//     make sequel: space rocket 2

const
    gameState = {
        rocket: {
            x: 30,
            y: 0,
            width: context.canvas.width / 10,
            height: context.canvas.height / 10,
            keyUpDown: false,
            direction: 0,
            keyDownDown: false,
            speed: 5,
            image: '/images/rocket.png'
        }
    },
    game = (gameState, input) => {
        switch(input) {
            case 'ArrowUpkeydown':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyUpDown: true,
                        direction: -1
                    }
                }
            case 'ArrowDownkeydown':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyDownDown: true,
                        direction: 1
                    }
                }
            case 'ArrowUpkeyup':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyUpDown: false,
                        direction: gameState.rocket.keyDownDown ? 1 : 0
                    }
                }
            case 'ArrowDownkeyup':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyDownDown: false,
                        direction: gameState.rocket.keyUpDown ? -1 : 0
                    }
                }
            case 'tick':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        y: gameState.rocket.y + gameState.rocket.speed * gameState.rocket.direction
                    }
                }
            default:
                return gameState
        }
    },
    image = (url) => {
        var imageObject = new Image()
        imageObject.src = url
        return imageObject
    },
    clock = Rx.Observable.interval(16.67).map(() => 'tick'), // 60 fps
    boolMatch = regex => R.pipe(R.match(regex), R.length)

Rx.Observable.fromEvent(document, 'keydown')
    .merge(Rx.Observable.fromEvent(document, 'keyup'))
    .map(e => e.key + e.type)
    .filter(boolMatch(/^(ArrowUp|ArrowDown).*$/))
    .scan((acc, el) => acc.match(el) ? 'remove' + el : el)
    .filter(R.pipe(boolMatch(/^(remove).*$/), R.not))
    .merge(clock)
    .startWith('')
    .scan(game, gameState)
    .subscribe(gameState => {
        window.requestAnimationFrame(() => {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height)
            context.drawImage(
                image(gameState.rocket.image),
                gameState.rocket.x,
                gameState.rocket.y)
        })
    })
<commit_msg>changed comments<commit_after>const
    R = require('ramda'),
    Rx = require('rx'),
    context = document.getElementById("gameScreen").getContext("2d")

context.canvas.width = window.innerWidth * .95
context.canvas.height = window.innerWidth * .6

//Todo
//     draw star field image
//     make star field image move
//     add fire
//     explain what's been done since the last video
//     rename series to let's make a game
//     Can't do any more recordings until you've uploaded the ones you've made
//     draw asteroid image
//     draw collision image
//     make rocket appear vertically centered at first, and not exactly at the side
//     make rocket move faster (hard-code speed in a const?)
//     add rocket fire animation
//     make star field move
//     add single asteroid move towards you from right side
//     make asteroid appear randomly
//     make array of asteroids
//     collision detection
//     show collision image and then reset game
//     What else before I call it done?
//     put up on heroku and porfolio
//     make sequel: space rocket 2

const
    gameState = {
        rocket: {
            x: 30,
            y: 0,
            width: context.canvas.width / 10,
            height: context.canvas.height / 10,
            keyUpDown: false,
            direction: 0,
            keyDownDown: false,
            speed: 5,
            image: '/images/rocket.png'
        }
    },
    game = (gameState, input) => {
        switch(input) {
            case 'ArrowUpkeydown':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyUpDown: true,
                        direction: -1
                    }
                }
            case 'ArrowDownkeydown':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyDownDown: true,
                        direction: 1
                    }
                }
            case 'ArrowUpkeyup':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyUpDown: false,
                        direction: gameState.rocket.keyDownDown ? 1 : 0
                    }
                }
            case 'ArrowDownkeyup':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        keyDownDown: false,
                        direction: gameState.rocket.keyUpDown ? -1 : 0
                    }
                }
            case 'tick':
                return {
                    ...gameState,
                    rocket: {
                        ...gameState.rocket,
                        y: gameState.rocket.y + gameState.rocket.speed * gameState.rocket.direction
                    }
                }
            default:
                return gameState
        }
    },
    image = (url) => {
        var imageObject = new Image()
        imageObject.src = url
        return imageObject
    },
    clock = Rx.Observable.interval(16.67).map(() => 'tick'), // 60 fps
    boolMatch = regex => R.pipe(R.match(regex), R.length)

Rx.Observable.fromEvent(document, 'keydown')
    .merge(Rx.Observable.fromEvent(document, 'keyup'))
    .map(e => e.key + e.type)
    .filter(boolMatch(/^(ArrowUp|ArrowDown).*$/))
    .scan((acc, el) => acc.match(el) ? 'remove' + el : el)
    .filter(R.pipe(boolMatch(/^(remove).*$/), R.not))
    .merge(clock)
    .startWith('')
    .scan(game, gameState)
    .subscribe(gameState => {
        window.requestAnimationFrame(() => {
            context.clearRect(0, 0, context.canvas.width, context.canvas.height)
            context.drawImage(
                image(gameState.rocket.image),
                gameState.rocket.x,
                gameState.rocket.y)
        })
    })
<|endoftext|>


<commit_before>// Backbone.ModalDialog.js v0.31
//
// Copyright (C)2012 Gareth Elms
// Distributed under MIT License
//
// Documentation and full license availabe at:
// https://github.com/GarethElms/BackboneJSModalView

Backbone.ModalView =
    Backbone.View.extend(
    {
        name: "ModalView",
        modalBlanket: null,
        modalContainer: null,
        defaultOptions:
		{
			fadeInDuration:150,
			fadeOutDuration:150,
			showCloseButton:true,
			bodyOverflowHidden:false,
            setFocusOnFirstFormControl:true,
            targetContainer: document.body,
            slideFromAbove: false,
            slideFromBelow: false,
            slideDistance: 150,
			closeImageUrl: "close-modal.png",
			closeImageHoverUrl: "close-modal-hover.png",
			showModalAtScrollPosition: true,
			permanentlyVisible: false,
            backgroundClickClosesModal: true,
            pressingEscapeClosesModal: true,
            css:
            {
                "border": "2px solid #111",
			    "background-color": "#fff",
			    "-webkit-box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)",
			    "-moz-box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)",
			    "box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)",
                "-webkit-border-radius": "10px",
                "-moz-border-radius": "10px",
                "border-radius": "10px"
            }
		},

        initialize:
            function()
            {
            },
        events:
            {
            },

        showModalBlanket:
            function()
            {
                return this.ensureModalBlanket().fadeIn( this.options.fadeInDuration);
            },

        hideModalBlanket:
            function()
            {
                return this.modalBlanket.fadeOut( this.options.fadeOutDuration);
            },

        ensureModalContainer:
            function( target)
            {
                if( target != null)
                {
                    // A target is passed in, we need to re-render the modal container into the target.
                    if( this.modalContainer != null)
                    {
                        this.modalContainer.remove();
                        this.modalContainer = null;
                    }
                }

                if( this.modalContainer == null)
                {
                    this.modalContainer =
                        $("
")
                            .css({
                                "z-index":"99999",
                                "position":"relative",
                                "-webkit-border-radius": "6px",
                                "-moz-border-radius": "6px",
                                "border-radius": "6px"
                                })
                            .appendTo( target);
                }

                return this.modalContainer;
            },

        ensureModalBlanket:
            function()
            {
                this.modalBlanket = $("#modal-blanket");

                if( this.modalBlanket.length == 0)
                {
                    this.modalBlanket =
                        $("
")
                            .css(
                                {
                                    position: "absolute",
                                    top: 0,
                                    left: 0,
                                    height: $(document).height(), // Span the full document height...
                                    width: "100%", // ...and full width
                                    opacity: 0.5, // Make it slightly transparent
                                    backgroundColor: "#000",
                                    "z-index": 99900
                                })
                            .appendTo( document.body)
                            .hide();
                }
				else
                {
                    // Ensure the blanket spans the whole document, screen may have been updated.
                    this.modalBlanket.css(
                        {
                            height: $(document).height(), // Span the full document height...
                            width: "100%" // ...and full width
                        });
                }

                return this.modalBlanket;
            },

        keyup:
            function( event)
            {
                if( event.keyCode == 27 && this.options.pressingEscapeClosesModal)
                {
                    this.hideModal();
                }
            },

        click:
            function( event)
            {
                if( event.target.id == "modal-blanket" && this.options.backgroundClickClosesModal)
                {
                    this.hideModal();
                }
            },

        setFocusOnFirstFormControl:
            function()
            {
                var controls = $("input, select, email, url, number, range, date, month, week, time, datetime, datetime-local, search, color", $(this.el));
                if( controls.length > 0)
                {
                    $(controls[0]).focus();
                }
            },

        hideModal:
            function()
            {
                this.trigger( "closeModalWindow");

                this.hideModalBlanket();
                $(document.body).unbind( "keyup", this.keyup);
                $(document.body).unbind( "click", this.click);

                if( this.options.bodyOverflowHidden === true)
                {
                    $(document.body).css( "overflow", this.originalBodyOverflowValue);
                }

                var container = this.modalContainer;
                $(this.modalContainer)
                    .fadeOut(
                        this.options.fadeOutDuration,
                        function()
                        {
                            container.remove();
                        });
            },

        getCoordinate:
            function( coordinate, css)
            {
                if( typeof( css[coordinate]) !== "undefined")
                {
                    var value = css[coordinate];
                    delete css[coordinate]; // Don't apply positioning to the $el, we apply it to the modal container. Remove it from options.css

                    return value;
                }
            },

		recenter:
			function()
			{
				return this.recentre();
			},

		recentre: // Re-centre the modal dialog after it has been displayed. Useful if the height changes after initial rendering eg; jquery ui tabs will hide tab sections
            function()
            {
                var $el = $(this.el);
                var coords = {
                    top: this.getCoordinate( "top", this.options.css),
                    left: this.getCoordinate( "left", this.options.css),
                    right: this.getCoordinate( "right", this.options.css),
                    bottom: this.getCoordinate( "bottom", this.options.css),
                    isEmpty: function(){return (this.top == null && this.left == null && this.right == null && this.bottom == null);}
                    };

                var offsets = this.getOffsets();
                var centreY = $(window).height() / 2;
                var centreX = $(window).width() / 2;
                var modalContainer = this.modalContainer;
                var positionY = centreY  - ($el.outerHeight() / 2);
                modalContainer.css({"top": (positionY + offsets.y) + "px"});

                var positionX = centreX - ($el.outerWidth() / 2);
                modalContainer.css({"left": (positionX + offsets.x) + "px"});

                return this;
            },

        getOffsets:
            function()
            {
                var offsetY = 0, offsetX = 0;
                if( this.options.showModalAtScrollPosition)
                {
                    offsetY = $(document).scrollTop(),
                    offsetX = $(document).scrollLeft()
                }

                return {x:offsetX, y:offsetY};
            },

        showModal:
            function( options)
            {
                this.defaultOptions.targetContainer = document.body;
                this.options = $.extend( true, {}, this.defaultOptions, options, this.options);

				if( this.options.permanentlyVisible)
                {
                    this.options.showCloseButton = false;
                    this.options.backgroundClickClosesModal = false;
                    this.options.pressingEscapeClosesModal = false;
                }

                //Set the center alignment padding + border see css style
                var $el = $(this.el);

				var centreY = $(window).height() / 2;
                var centreX = $(window).width() / 2;
                var modalContainer = this.ensureModalContainer( this.options.targetContainer).empty();

		        $el.addClass( "modal");

                var coords = {
                    top: this.getCoordinate( "top", this.options.css),
                    left: this.getCoordinate( "left", this.options.css),
                    right: this.getCoordinate( "right", this.options.css),
                    bottom: this.getCoordinate( "bottom", this.options.css),
                    isEmpty: function(){return (this.top == null && this.left == null && this.right == null && this.bottom == null);}
                    };

				$el.css( this.options.css);

                this.showModalBlanket();
                this.keyup = _.bind( this.keyup, this);
                this.click = _.bind( this.click, this);
                $(document.body).keyup( this.keyup); // This handler is unbound in hideDialog()
                $(document.body).click( this.click); // This handler is unbound in hideDialog()

                if( this.options.bodyOverflowHidden === true)
                {
                    this.originalBodyOverflowValue = $(document.body).css( "overflow");
                    $(document.body).css( "overflow", "hidden");
                }

                modalContainer
                    .append( $el);

                modalContainer.css({
                        "opacity": 0,
                        "position": "absolute",
                        "z-index": 999999});

				var offsets = this.getOffsets();

                // Only apply default centre coordinates if no css positions have been supplied
                if( coords.isEmpty())
                {
                    var positionY = centreY  - ($el.outerHeight() / 2);
                    if( positionY < 10) positionY = 10;

					// Overriding the coordinates with explicit values if they are passed in
                    if( typeof( this.options.y) !== "undefined")
                    {
                        positionY = this.options.y;
                    }
                    else
                    {
                        positionY += offsets.y;
                    }

                    modalContainer.css({"top": positionY + "px"});

                    var positionX = centreX - ($el.outerWidth() / 2);
					// Overriding the coordinates with explicit values if they are passed in
                    if( typeof( this.options.x) !== "undefined")
                    {
                        positionX = this.options.x;
                    }
                    else
                    {
                        positionX += offsets.x;
                    }

                    modalContainer.css({"left": positionX + "px"});
                }
                else
                {
                    if( coords.top != null) modalContainer.css({"top": coords.top + offsets.y});
                    if( coords.left != null) modalContainer.css({"left": coords.left + offsets.x});
                    if( coords.right != null) modalContainer.css({"right": coords.right});
                    if( coords.bottom != null) modalContainer.css({"bottom": coords.bottom});
                }

                if( this.options.setFocusOnFirstFormControl)
                {
                    this.setFocusOnFirstFormControl();
                }

                if( this.options.showCloseButton)
                {
                    var view = this;
                    var image =
                        $(" ")
                            .css({
									"position":"absolute",
									"top":"-10px",
									"right":"-10px",
									"width":"32px",
									"height":"32px",
									"background":"transparent url(" + view.options.closeImageUrl + ") top left no-repeat",
									"text-decoration":"none"})
                            .appendTo( this.modalContainer)
                            .hover(
                                function()
                                {
                                    $(this).css( "background-image", "url(" + view.options.closeImageHoverUrl + ") !important");
                                },
                                function()
                                {
                                    $(this).css( "background-image", "url(" + view.options.closeImageUrl + ") !important");
                                })
                            .click(
                                function( event)
                                {
                                    event.preventDefault();
                                    view.hideModal();
                                });
                }

                var animateProperties = {opacity:1};
                var modalOffset = modalContainer.offset();

                if( this.options.slideFromAbove)
                {
                    modalContainer.css({"top": (modalOffset.top - this.options.slideDistance) + "px"});
                    animateProperties.top = coords.top;
                }

                if( this.options.slideFromBelow)
                {
                    modalContainer.css({"top": (modalOffset.top + this.options.slideDistance) + "px"});
                    animateProperties.top = coords.top;
                }

                this.modalContainer.animate( animateProperties, this.options.fadeInDuration);

				return this;
            }
    });<commit_msg>Fix for mobile Safari click event on modal blanket<commit_after>// Backbone.ModalDialog.js v0.3.2
//
// Copyright (C)2012 Gareth Elms
// Distributed under MIT License
//
// Documentation and full license availabe at:
// https://github.com/GarethElms/BackboneJSModalView

Backbone.ModalView =
    Backbone.View.extend(
    {
        name: "ModalView",
        modalBlanket: null,
        modalContainer: null,
        defaultOptions:
		{
			fadeInDuration:150,
			fadeOutDuration:150,
			showCloseButton:true,
			bodyOverflowHidden:false,
            setFocusOnFirstFormControl:true,
            targetContainer: document.body,
            slideFromAbove: false,
            slideFromBelow: false,
            slideDistance: 150,
			closeImageUrl: "close-modal.png",
			closeImageHoverUrl: "close-modal-hover.png",
			showModalAtScrollPosition: true,
			permanentlyVisible: false,
            backgroundClickClosesModal: true,
            pressingEscapeClosesModal: true,
            css:
            {
                "border": "2px solid #111",
			    "background-color": "#fff",
			    "-webkit-box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)",
			    "-moz-box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)",
			    "box-shadow": "0px 0px 15px 4px rgba(0, 0, 0, 0.5)",
                "-webkit-border-radius": "10px",
                "-moz-border-radius": "10px",
                "border-radius": "10px"
            }
		},

        initialize:
            function()
            {
            },
        events:
            {
            },

        showModalBlanket:
            function()
            {
                return this.ensureModalBlanket().fadeIn( this.options.fadeInDuration);
            },

        hideModalBlanket:
            function()
            {
                return this.modalBlanket.fadeOut( this.options.fadeOutDuration);
            },

        ensureModalContainer:
            function( target)
            {
                if( target != null)
                {
                    // A target is passed in, we need to re-render the modal container into the target.
                    if( this.modalContainer != null)
                    {
                        this.modalContainer.remove();
                        this.modalContainer = null;
                    }
                }

                if( this.modalContainer == null)
                {
                    this.modalContainer =
                        $("
")
                            .css({
                                "z-index":"99999",
                                "position":"relative",
                                "-webkit-border-radius": "6px",
                                "-moz-border-radius": "6px",
                                "border-radius": "6px"
                                })
                            .appendTo( target);
                }

                return this.modalContainer;
            },

        ensureModalBlanket:
            function()
            {
                this.modalBlanket = $("#modal-blanket");

                if( this.modalBlanket.length == 0)
                {
                    this.modalBlanket =
                        $("
")
                            .css(
                                {
                                    position: "absolute",
                                    top: 0,
                                    left: 0,
                                    height: $(document).height(), // Span the full document height...
                                    width: "100%", // ...and full width
                                    opacity: 0.5, // Make it slightly transparent
                                    backgroundColor: "#000",
                                    "z-index": 99900
                                })
                            .appendTo( document.body)
                            .hide();
                }
				else
                {
                    // Ensure the blanket spans the whole document, screen may have been updated.
                    this.modalBlanket.css(
                        {
                            height: $(document).height(), // Span the full document height...
                            width: "100%" // ...and full width
                        });
                }

                return this.modalBlanket;
            },

        keyup:
            function( event)
            {
                if( event.keyCode == 27 && this.options.pressingEscapeClosesModal)
                {
                    this.hideModal();
                }
            },

        click:
            function( event)
            {
                if( event.target.id == "modal-blanket" && this.options.backgroundClickClosesModal)
                {
                    this.hideModal();
                }
            },

        setFocusOnFirstFormControl:
            function()
            {
                var controls = $("input, select, email, url, number, range, date, month, week, time, datetime, datetime-local, search, color", $(this.el));
                if( controls.length > 0)
                {
                    $(controls[0]).focus();
                }
            },

        hideModal:
            function()
            {
                this.trigger( "closeModalWindow");

                this.hideModalBlanket();
                $(document.body).unbind( "keyup", this.keyup);
                this.modalBlanket.unbind( "click", this.click);

                if( this.options.bodyOverflowHidden === true)
                {
                    $(document.body).css( "overflow", this.originalBodyOverflowValue);
                }

                var container = this.modalContainer;
                $(this.modalContainer)
                    .fadeOut(
                        this.options.fadeOutDuration,
                        function()
                        {
                            container.remove();
                        });
            },

        getCoordinate:
            function( coordinate, css)
            {
                if( typeof( css[coordinate]) !== "undefined")
                {
                    var value = css[coordinate];
                    delete css[coordinate]; // Don't apply positioning to the $el, we apply it to the modal container. Remove it from options.css

                    return value;
                }
            },

		recenter:
			function()
			{
				return this.recentre();
			},

		recentre: // Re-centre the modal dialog after it has been displayed. Useful if the height changes after initial rendering eg; jquery ui tabs will hide tab sections
            function()
            {
                var $el = $(this.el);
                var coords = {
                    top: this.getCoordinate( "top", this.options.css),
                    left: this.getCoordinate( "left", this.options.css),
                    right: this.getCoordinate( "right", this.options.css),
                    bottom: this.getCoordinate( "bottom", this.options.css),
                    isEmpty: function(){return (this.top == null && this.left == null && this.right == null && this.bottom == null);}
                    };

                var offsets = this.getOffsets();
                var centreY = $(window).height() / 2;
                var centreX = $(window).width() / 2;
                var modalContainer = this.modalContainer;
                var positionY = centreY  - ($el.outerHeight() / 2);
                modalContainer.css({"top": (positionY + offsets.y) + "px"});

                var positionX = centreX - ($el.outerWidth() / 2);
                modalContainer.css({"left": (positionX + offsets.x) + "px"});

                return this;
            },

        getOffsets:
            function()
            {
                var offsetY = 0, offsetX = 0;
                if( this.options.showModalAtScrollPosition)
                {
                    offsetY = $(document).scrollTop(),
                    offsetX = $(document).scrollLeft()
                }

                return {x:offsetX, y:offsetY};
            },

        showModal:
            function( options)
            {
                this.defaultOptions.targetContainer = document.body;
                this.options = $.extend( true, {}, this.defaultOptions, options, this.options);

				if( this.options.permanentlyVisible)
                {
                    this.options.showCloseButton = false;
                    this.options.backgroundClickClosesModal = false;
                    this.options.pressingEscapeClosesModal = false;
                }

                //Set the center alignment padding + border see css style
                var $el = $(this.el);

				var centreY = $(window).height() / 2;
                var centreX = $(window).width() / 2;
                var modalContainer = this.ensureModalContainer( this.options.targetContainer).empty();

		        $el.addClass( "modal");

                var coords = {
                    top: this.getCoordinate( "top", this.options.css),
                    left: this.getCoordinate( "left", this.options.css),
                    right: this.getCoordinate( "right", this.options.css),
                    bottom: this.getCoordinate( "bottom", this.options.css),
                    isEmpty: function(){return (this.top == null && this.left == null && this.right == null && this.bottom == null);}
                    };

				$el.css( this.options.css);

                this.showModalBlanket();
                this.keyup = _.bind( this.keyup, this);
                this.click = _.bind( this.click, this);
                $(document.body).keyup( this.keyup); // This handler is unbound in hideModal()
                this.modalBlanket.click( this.click); // This handler is unbound in hideModal()

                if( this.options.bodyOverflowHidden === true)
                {
                    this.originalBodyOverflowValue = $(document.body).css( "overflow");
                    $(document.body).css( "overflow", "hidden");
                }

                modalContainer
                    .append( $el);

                modalContainer.css({
                        "opacity": 0,
                        "position": "absolute",
                        "z-index": 999999});

				var offsets = this.getOffsets();

                // Only apply default centre coordinates if no css positions have been supplied
                if( coords.isEmpty())
                {
                    var positionY = centreY  - ($el.outerHeight() / 2);
                    if( positionY < 10) positionY = 10;

					// Overriding the coordinates with explicit values if they are passed in
                    if( typeof( this.options.y) !== "undefined")
                    {
                        positionY = this.options.y;
                    }
                    else
                    {
                        positionY += offsets.y;
                    }

                    modalContainer.css({"top": positionY + "px"});

                    var positionX = centreX - ($el.outerWidth() / 2);
					// Overriding the coordinates with explicit values if they are passed in
                    if( typeof( this.options.x) !== "undefined")
                    {
                        positionX = this.options.x;
                    }
                    else
                    {
                        positionX += offsets.x;
                    }

                    modalContainer.css({"left": positionX + "px"});
                }
                else
                {
                    if( coords.top != null) modalContainer.css({"top": coords.top + offsets.y});
                    if( coords.left != null) modalContainer.css({"left": coords.left + offsets.x});
                    if( coords.right != null) modalContainer.css({"right": coords.right});
                    if( coords.bottom != null) modalContainer.css({"bottom": coords.bottom});
                }

                if( this.options.setFocusOnFirstFormControl)
                {
                    this.setFocusOnFirstFormControl();
                }

                if( this.options.showCloseButton)
                {
                    var view = this;
                    var image =
                        $(" ")
                            .css({
									"position":"absolute",
									"top":"-10px",
									"right":"-10px",
									"width":"32px",
									"height":"32px",
									"background":"transparent url(" + view.options.closeImageUrl + ") top left no-repeat",
									"text-decoration":"none"})
                            .appendTo( this.modalContainer)
                            .hover(
                                function()
                                {
                                    $(this).css( "background-image", "url(" + view.options.closeImageHoverUrl + ") !important");
                                },
                                function()
                                {
                                    $(this).css( "background-image", "url(" + view.options.closeImageUrl + ") !important");
                                })
                            .click(
                                function( event)
                                {
                                    event.preventDefault();
                                    view.hideModal();
                                });
                }

                var animateProperties = {opacity:1};
                var modalOffset = modalContainer.offset();

                if( this.options.slideFromAbove)
                {
                    modalContainer.css({"top": (modalOffset.top - this.options.slideDistance) + "px"});
                    animateProperties.top = coords.top;
                }

                if( this.options.slideFromBelow)
                {
                    modalContainer.css({"top": (modalOffset.top + this.options.slideDistance) + "px"});
                    animateProperties.top = coords.top;
                }

                this.modalContainer.animate( animateProperties, this.options.fadeInDuration);

				return this;
            }
    });<|endoftext|>


<commit_before>/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function(nums) {

    var result = [];
    var len = nums.length;

    nums.sort(function(a, b){
        return a - b;
    });

    helper(nums, 0, len-1, [], result);

    return result;
};

function helper(nums, start, end, curArr, result) {
    result.push(curArr);

    for(var i = start; i <= end; i++){
        curArr.push(nums[i]);
        helper(nums, i+1, end, curArr.concat(), result);
        curArr.pop();
    }
}
<commit_msg>Update Subsets.js<commit_after>/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var subsets = function(nums) {

    var result = [];
    var len = nums.length;

    helper(nums, 0, len-1, [], result);

    return result;
};

function helper(nums, start, end, curArr, result) {
    result.push(curArr);

    for(var i = start; i <= end; i++){
        curArr.push(nums[i]);
        helper(nums, i+1, end, curArr.concat(), result);
        curArr.pop();
    }
}
<|endoftext|>