<commit_before>import {
  StyleSheet,
  Dimensions,
} from 'react-native';

export default styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  app: {
    flex: 6,
    width: Dimensions.get('window').width,
  },
  welcome: {
    fontSize: 60,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  buttonView:{
    flex: 1,
  },
  takePicture: {
    height: 100,
    width: 100,
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
    height: Dimensions.get('window').height,
    width: Dimensions.get('window').width
  },
  navigation: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    flex: 1,
    width: Dimensions.get('window').width,
    margin: 0,
    backgroundColor: 'deepskyblue',
    justifyContent: 'center',
  },

  glyphicon: {
    flexDirection: 'row',
    height: 60,
    width: 60,
    padding: 5,
    marginRight: 60,
  },

  navigationahover: {
    backgroundColor: 'deepskyblue',
  },

// @media all and (max-width: 800px) {
//   .navigation {
//     justify-content: space-around;
//   }
// }

// @media all and (max-width: 600px) {
//   .navigation {
//     -webkit-flex-flow: column wrap;
//     flex-flow: column wrap;
//     padding: 0;
//   }

//   .navigation a {
//     text-align: center;
//     padding: 10px;
//     border-top: 1px solid rgba(255,255,255,0.3);
//     border-bottom: 1px solid rgba(0,0,0,0.1);
//   }

//   .navigation li:last-of-type a {
//     border-bottom: none;
//   }

});<commit_msg>added styling for search bar and search bar button<commit_after>import {
  StyleSheet,
  Dimensions,
} from 'react-native';

export default styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  app: {
    flex: 6,
    width: Dimensions.get('window').width,
  },
  welcome: {
    fontSize: 60,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  buttonView:{
    flex: 1,
  },
  takePicture: {
    height: 100,
    width: 100,
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
    height: Dimensions.get('window').height,
    width: Dimensions.get('window').width
  },
  navigation: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    flex: 1,
    width: Dimensions.get('window').width,
    margin: 0,
    backgroundColor: 'deepskyblue',
    justifyContent: 'center',
  },

  glyphicon: {
    flexDirection: 'row',
    height: 60,
    width: 60,
    padding: 5,
    marginRight: 60,
  },

  navigationahover: {
    backgroundColor: 'deepskyblue',
  },

  searchBarPicture: {
    height: 100,
    width: 100,
  },

   searchBarPictureFrame: {
    flex: 1,
    justifyContent: 'flex-end',
  },

  searchBar: {
    height: 40,
    width: 200,
    borderColor: 'gray',
    borderWidth: 1,
  }

// @media all and (max-width: 800px) {
//   .navigation {
//     justify-content: space-around;
//   }
// }

// @media all and (max-width: 600px) {
//   .navigation {
//     -webkit-flex-flow: column wrap;
//     flex-flow: column wrap;
//     padding: 0;
//   }

//   .navigation a {
//     text-align: center;
//     padding: 10px;
//     border-top: 1px solid rgba(255,255,255,0.3);
//     border-bottom: 1px solid rgba(0,0,0,0.1);
//   }

//   .navigation li:last-of-type a {
//     border-bottom: none;
//   }

});<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import Props from '../utils/Props';
import Box from './Box';
import CSSClassnames from '../utils/CSSClassnames';

const CLASS_ROOT = CSSClassnames.TILE;
const NAMESPACE = CSSClassnames.NAMESPACE;

export default class Tile extends Component {

  render () {
    const { children, className, onClick, wide, status, selected,
      hoverStyle, hoverColorIndex, hoverBorder, hoverBorderSize } = this.props;
    const restProps = Props.omit(this.props, Object.keys(Box.propTypes));

    if (selected) {
      console.warn('Selected option has been deprecated, please use ' +
        'selected option at the Tiles level.');
    }

    const statusClass = status ? status.toLowerCase() : undefined;
    // if Tiles flush is true, default borderSize to small (1px)
    let borderSize = (hoverBorder) ?
      ((hoverBorderSize) ? hoverBorderSize : 'large') : 'small';

    const classes = classnames(
      CLASS_ROOT,
      className,
      {
        [`${CLASS_ROOT}--status-${statusClass}`]: status,
        [`${CLASS_ROOT}--wide`]: wide,
        [`${CLASS_ROOT}--selectable`]: onClick,
        [`${CLASS_ROOT}--selected`]: selected,
        [`${NAMESPACE}${hoverStyle}${(hoverStyle == 'border') ?
          ((borderSize) ? `-${borderSize}` : '-medium') : ''
        }-hover-color-index-${hoverColorIndex}`]: hoverStyle,
        [`${CLASS_ROOT}--hover-border-${borderSize}`]: borderSize
      }
    );

    const boxProps = Props.pick(this.props, Object.keys(Box.propTypes));

    return (
      <Box {...restProps} {...boxProps} className={classes}>
        {children}
      </Box>
    );
  }

}

Tile.propTypes = {
  selected: PropTypes.bool,
  wide: PropTypes.bool,
  hoverStyle: PropTypes.oneOf(['border', 'background', 'none']),
  hoverColorIndex: PropTypes.string,
  hoverBorderSize: PropTypes.oneOf(['small', 'medium', 'large']),
  ...Box.propTypes
};

Tile.defaultProps = {
  pad: 'none',
  direction: 'column',
  align: 'center',
  hoverStyle: 'none',
  hoverColorIndex: 'disabled'
};
<commit_msg>resolving unknown props React warning https://github.com/grommet/grommet/issues/679<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import classnames from 'classnames';
import Props from '../utils/Props';
import Box from './Box';
import CSSClassnames from '../utils/CSSClassnames';

const CLASS_ROOT = CSSClassnames.TILE;
const NAMESPACE = CSSClassnames.NAMESPACE;

export default class Tile extends Component {

  render () {
    const { children, className, onClick, wide, status, selected,
      hoverStyle, hoverColorIndex, hoverBorder, hoverBorderSize } = this.props;
    const restProps = Props.omit(this.props, Object.keys(Box.propTypes));
    delete restProps.hoverStyle;
    delete restProps.hoverColorIndex;
    delete restProps.hoverBorder;
    delete restProps.hoverBorderSize;

    if (selected) {
      console.warn('Selected option has been deprecated, please use ' +
        'selected option at the Tiles level.');
    }

    const statusClass = status ? status.toLowerCase() : undefined;
    // if Tiles flush is true, default borderSize to small (1px)
    let borderSize = (hoverBorder) ?
      ((hoverBorderSize) ? hoverBorderSize : 'large') : 'small';

    const classes = classnames(
      CLASS_ROOT,
      className,
      {
        [`${CLASS_ROOT}--status-${statusClass}`]: status,
        [`${CLASS_ROOT}--wide`]: wide,
        [`${CLASS_ROOT}--selectable`]: onClick,
        [`${CLASS_ROOT}--selected`]: selected,
        [`${NAMESPACE}${hoverStyle}${(hoverStyle == 'border') ?
          ((borderSize) ? `-${borderSize}` : '-medium') : ''
        }-hover-color-index-${hoverColorIndex}`]: hoverStyle,
        [`${CLASS_ROOT}--hover-border-${borderSize}`]: borderSize
      }
    );

    const boxProps = Props.pick(this.props, Object.keys(Box.propTypes));

    return (
      <Box {...restProps} {...boxProps} className={classes}>
        {children}
      </Box>
    );
  }

}

Tile.propTypes = {
  selected: PropTypes.bool,
  wide: PropTypes.bool,
  hoverStyle: PropTypes.oneOf(['border', 'background', 'none']),
  hoverColorIndex: PropTypes.string,
  hoverBorderSize: PropTypes.oneOf(['small', 'medium', 'large']),
  ...Box.propTypes
};

Tile.defaultProps = {
  pad: 'none',
  direction: 'column',
  align: 'center',
  hoverStyle: 'none',
  hoverColorIndex: 'disabled'
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');
var AuthApi = require('../auth/auth_api');

module.exports = function authenticatedRequest (userDatabaseService, forceToBeAuthenticated = false) {
    return function authenticatedRequestMiddleware (req, res, next) {
        req.profiler.start('sqlapi.job');
        req.profiler.done('init');

        const params = _.extend({}, res.locals, req.query, req.body);
        const { user } = res.locals;
        const authApi = new AuthApi(req, res, params);

        userDatabaseService.getConnectionParams(authApi, user, function (err, dbParams, authDbParams, userLimits) {
            req.profiler.done('setDBAuth');

            if (err) {
                return next(err);
            }

            if (forceToBeAuthenticated && !dbParams.authenticated) {
                return next(new Error('permission denied'));
            }

            res.locals.userDbParams = dbParams;
            res.locals.authDbParams = authDbParams;
            res.locals.userLimits = userLimits;

            next();
        });
    };
};
<commit_msg>Do not use underscore<commit_after>const AuthApi = require('../auth/auth_api');

module.exports = function authenticatedRequest (userDatabaseService, forceToBeAuthenticated = false) {
    return function authenticatedRequestMiddleware (req, res, next) {
        const params = Object.assign({}, res.locals, req.query, req.body);
        const { user } = res.locals;
        const authApi = new AuthApi(req, res, params);

        userDatabaseService.getConnectionParams(authApi, user, function (err, dbParams, authDbParams, userLimits) {
            if (req.profiler) {
                req.profiler.done('setDBAuth');
            }

            if (err) {
                return next(err);
            }

            if (forceToBeAuthenticated && !dbParams.authenticated) {
                return next(new Error('permission denied'));
            }

            res.locals.userDbParams = dbParams;
            res.locals.authDbParams = authDbParams;
            res.locals.userLimits = userLimits;

            next();
        });
    };
};
<|endoftext|>


<commit_before>// MySQL SchemaGrammar
// -------
var _           = require('underscore');
var grammar           = require('./grammar').grammar;
var baseSchemaGrammar = require('../../base/schemagrammar').baseSchemaGrammar;

// Grammar for the schema builder.
exports.schemaGrammar = _.defaults({

  // The possible column modifiers.
  modifiers: ['Unsigned', 'Nullable', 'Default', 'Increment', 'After', 'Comment'],

  // Dialect specific `getBindings`.
  getBindings: function(builder) {
    var bindings = grammar.getBindings(builder);
    if (builder.type === 'tableExists') {
      bindings.unshift(builder.client.connectionSettings.database);
    }
    if (builder.type === 'columnExists') bindings.shift();
    return bindings;
  },

  // Ensures the response is returned in the same format as other clients.
  handleResponse: function(builder, resp) {
    resp = resp[0];
    if (builder.type === 'tableExists') return resp[0].length > 0;
    if (builder.type === 'columnExists') return resp[0].length > 0;
    return resp;
  },

  // Compile a create table command.
  compileCreateTable: function(builder, command) {
    var sql  = baseSchemaGrammar.compileCreateTable.call(this, builder, command);
    var conn = builder.client.connectionSettings;

    if (builder.flags.charset || conn.charset) sql += ' default character set ' + (builder.flags.charset || conn.charset);
    if (builder.flags.collation || conn.collation) sql += ' collate ' + (builder.flags.collation || conn.collation);
    if (builder.flags.engine) {
      sql += ' engine = ' + builder.flags.engine;
    }

    // Checks if the table is commented
    var isCommented = this.getCommandByName(builder, 'comment');

    // TODO: Handle max comment length.
    var maxTableCommentLength = 60;
    if (isCommented) {
      sql += " comment = '" + isCommented.comment + "'";
    }

    return sql;
  },

  // Compile the query to determine if a table exists.
  compileTableExists: function(builder) {
    return 'select * from information_schema.tables where table_schema = ? and table_name = ?';
  },

  // Compile a query to determine if a column exists.
  compileColumnExists: function(builder) {
    return 'show columns from ' + this.wrapTable(builder) + ' like ?';
  },

  // Compile an add command.
  compileAdd: function(builder) {
    var columns = this.prefixArray('add', this.getColumns(builder));
    return 'alter table ' + this.wrapTable(builder) + ' ' + columns.join(', ');
  },

  // Compile a primary key command.
  compilePrimary: function(builder, command) {
    return this.compileKey(builder, command, 'primary key');
  },

  // Compile a unique key command.
  compileUnique: function(builder, command) {
    return this.compileKey(builder, command, 'unique');
  },

  // Compile a plain index key command.
  compileIndex: function(builder, command) {
    return this.compileKey(builder, command, 'index');
  },

  // Compile an index creation command.
  compileKey: function(builder, command, type) {
    var columns = this.columnize(command.columns);
    var table = this.wrapTable(builder);
    return 'alter table ' + table + " add " + type + " " + command.index + "(" + columns + ")";
  },

  // Compile a drop column command.
  compileDropColumn: function(builder, command) {
    var columns = this.prefixArray('drop', this.wrapArray(command.columns));
    return 'alter table ' + this.wrapTable(builder) + ' ' + columns.join(', ');
  },

  // Compile a drop primary key command.
  compileDropPrimary: function(builder) {
    return 'alter table ' + this.wrapTable(builder) + ' drop primary key';
  },

  // Compile a drop unique key command.
  compileDropUnique: function(builder, command) {
    return this.compileDropIndex(builder, command);
  },

  // Compile a drop index command.
  compileDropIndex: function(builder, command) {
    return 'alter table ' + this.wrapTable(builder) + ' drop index ' + command.index;
  },

  // Compile a drop foreign key command.
  compileDropForeign: function(builder, command) {
    return 'alter table ' + this.wrapTable(builder) + " drop foreign key " + command.index;
  },

  // Compile a rename table command.
  compileRenameTable: function(builder, command) {
    return 'rename table ' + this.wrapTable(builder) + ' to ' + this.wrapTable(command.to);
  },

  // Compile a rename column command.
  compileRenameColumn: function(builder, command) {
    return 'alter table ' + this.wrapTable(builder) + ' change ' +
      this.wrapTable(command.from) + ' ' + this.wrapTable(command.to) + ' __datatype__';
  },

  // Compiles the comment on the table.
  compileComment: function(builder, command) {
    // Handled on create table...
  },

  // Create the column definition for a text type.
  typeText: function(column) {
    switch (column.length) {
      case 'medium':
      case 'mediumtext':
        return 'mediumtext';
      case 'long':
      case 'longtext':
        return 'longtext';
      default:
        return 'text';
    }
  },

  // Create the column type definition for a bigint type.
  typeBigInteger: function() {
    return 'bigint';
  },

  // Create the column definition for a integer type.
  typeInteger: function(column) {
    return 'int(' + column.length + ')';
  },

  // Create the column definition for a float type.
  typeFloat: function(column) {
    return 'float(' + column.total + ',' + column.places + ')';
  },

  // Create the column definition for a decimal type.
  typeDecimal: function(column) {
    return 'decimal(' + column.precision + ', ' + column.scale + ')';
  },

  // Create the column definition for a boolean type.
  typeBoolean: function() {
    return 'tinyint(1)';
  },

  // Create the column definition for a enum type.
  typeEnum: function(column) {
    return "enum('" + column.allowed.join("', '")  + "')";
  },

  // Create the column definition for a date-time type.
  typeDateTime: function() {
    return 'datetime';
  },

  // Create the column definition for a timestamp type.
  typeTimestamp: function() {
    return 'timestamp';
  },

  // Create the column definition for a bit type.
  typeBit: function(column) {
    return column.length !== false ? 'bit(' + column.length + ')' : 'bit';
  },

  // Get the SQL for an unsigned column modifier.
  modifyUnsigned: function(builder, column) {
    if (column.isUnsigned) return ' unsigned';
  },

  // Get the SQL for a default column modifier.
  modifyDefault: function(builder, column) {
    // TODO - no default on blob/text
    if (column.defaultValue != void 0 && column.type != 'blob' && column.type.indexOf('text') === -1) {
      return " default '" + this.getDefaultValue(column.defaultValue) + "'";
    }
  },

  // Get the SQL for an auto-increment column modifier.
  modifyIncrement: function(builder, column) {
    if (column.autoIncrement && (column.type == 'integer' || column.type == 'bigInteger')) {
      return ' not null auto_increment primary key';
    }
  },

  // Get the SQL for an "after" column modifier.
  modifyAfter: function(builder, column) {
    if (column.isAfter) {
      return ' after ' + this.wrap(column.isAfter);
    }
  },

  // Get the SQL for a comment column modifier.
  modifyComment: function(builder, column) {
    // TODO: Look into limiting this length.
    var maxColumnCommentLength = 255;
    if (column.isCommented && _.isString(column.isCommented)) {
      return " comment '" + column.isCommented + "'";
    }
  }

}, baseSchemaGrammar, grammar);<commit_msg>fix incorrect values passed to typeFloat in mysql<commit_after>// MySQL SchemaGrammar
// -------
var _           = require('underscore');
var grammar           = require('./grammar').grammar;
var baseSchemaGrammar = require('../../base/schemagrammar').baseSchemaGrammar;

// Grammar for the schema builder.
exports.schemaGrammar = _.defaults({

  // The possible column modifiers.
  modifiers: ['Unsigned', 'Nullable', 'Default', 'Increment', 'After', 'Comment'],

  // Dialect specific `getBindings`.
  getBindings: function(builder) {
    var bindings = grammar.getBindings(builder);
    if (builder.type === 'tableExists') {
      bindings.unshift(builder.client.connectionSettings.database);
    }
    if (builder.type === 'columnExists') bindings.shift();
    return bindings;
  },

  // Ensures the response is returned in the same format as other clients.
  handleResponse: function(builder, resp) {
    resp = resp[0];
    if (builder.type === 'tableExists') return resp[0].length > 0;
    if (builder.type === 'columnExists') return resp[0].length > 0;
    return resp;
  },

  // Compile a create table command.
  compileCreateTable: function(builder, command) {
    var sql  = baseSchemaGrammar.compileCreateTable.call(this, builder, command);
    var conn = builder.client.connectionSettings;

    if (builder.flags.charset || conn.charset) sql += ' default character set ' + (builder.flags.charset || conn.charset);
    if (builder.flags.collation || conn.collation) sql += ' collate ' + (builder.flags.collation || conn.collation);
    if (builder.flags.engine) {
      sql += ' engine = ' + builder.flags.engine;
    }

    // Checks if the table is commented
    var isCommented = this.getCommandByName(builder, 'comment');

    // TODO: Handle max comment length.
    var maxTableCommentLength = 60;
    if (isCommented) {
      sql += " comment = '" + isCommented.comment + "'";
    }

    return sql;
  },

  // Compile the query to determine if a table exists.
  compileTableExists: function(builder) {
    return 'select * from information_schema.tables where table_schema = ? and table_name = ?';
  },

  // Compile a query to determine if a column exists.
  compileColumnExists: function(builder) {
    return 'show columns from ' + this.wrapTable(builder) + ' like ?';
  },

  // Compile an add command.
  compileAdd: function(builder) {
    var columns = this.prefixArray('add', this.getColumns(builder));
    return 'alter table ' + this.wrapTable(builder) + ' ' + columns.join(', ');
  },

  // Compile a primary key command.
  compilePrimary: function(builder, command) {
    return this.compileKey(builder, command, 'primary key');
  },

  // Compile a unique key command.
  compileUnique: function(builder, command) {
    return this.compileKey(builder, command, 'unique');
  },

  // Compile a plain index key command.
  compileIndex: function(builder, command) {
    return this.compileKey(builder, command, 'index');
  },

  // Compile an index creation command.
  compileKey: function(builder, command, type) {
    var columns = this.columnize(command.columns);
    var table = this.wrapTable(builder);
    return 'alter table ' + table + " add " + type + " " + command.index + "(" + columns + ")";
  },

  // Compile a drop column command.
  compileDropColumn: function(builder, command) {
    var columns = this.prefixArray('drop', this.wrapArray(command.columns));
    return 'alter table ' + this.wrapTable(builder) + ' ' + columns.join(', ');
  },

  // Compile a drop primary key command.
  compileDropPrimary: function(builder) {
    return 'alter table ' + this.wrapTable(builder) + ' drop primary key';
  },

  // Compile a drop unique key command.
  compileDropUnique: function(builder, command) {
    return this.compileDropIndex(builder, command);
  },

  // Compile a drop index command.
  compileDropIndex: function(builder, command) {
    return 'alter table ' + this.wrapTable(builder) + ' drop index ' + command.index;
  },

  // Compile a drop foreign key command.
  compileDropForeign: function(builder, command) {
    return 'alter table ' + this.wrapTable(builder) + " drop foreign key " + command.index;
  },

  // Compile a rename table command.
  compileRenameTable: function(builder, command) {
    return 'rename table ' + this.wrapTable(builder) + ' to ' + this.wrapTable(command.to);
  },

  // Compile a rename column command.
  compileRenameColumn: function(builder, command) {
    return 'alter table ' + this.wrapTable(builder) + ' change ' +
      this.wrapTable(command.from) + ' ' + this.wrapTable(command.to) + ' __datatype__';
  },

  // Compiles the comment on the table.
  compileComment: function(builder, command) {
    // Handled on create table...
  },

  // Create the column definition for a text type.
  typeText: function(column) {
    switch (column.length) {
      case 'medium':
      case 'mediumtext':
        return 'mediumtext';
      case 'long':
      case 'longtext':
        return 'longtext';
      default:
        return 'text';
    }
  },

  // Create the column type definition for a bigint type.
  typeBigInteger: function() {
    return 'bigint';
  },

  // Create the column definition for a integer type.
  typeInteger: function(column) {
    return 'int(' + column.length + ')';
  },

  // Create the column definition for a float type.
  typeFloat: function(column) {
    return 'float(' + column.precision + ',' + column.scale + ')';
  },

  // Create the column definition for a decimal type.
  typeDecimal: function(column) {
    return 'decimal(' + column.precision + ', ' + column.scale + ')';
  },

  // Create the column definition for a boolean type.
  typeBoolean: function() {
    return 'tinyint(1)';
  },

  // Create the column definition for a enum type.
  typeEnum: function(column) {
    return "enum('" + column.allowed.join("', '")  + "')";
  },

  // Create the column definition for a date-time type.
  typeDateTime: function() {
    return 'datetime';
  },

  // Create the column definition for a timestamp type.
  typeTimestamp: function() {
    return 'timestamp';
  },

  // Create the column definition for a bit type.
  typeBit: function(column) {
    return column.length !== false ? 'bit(' + column.length + ')' : 'bit';
  },

  // Get the SQL for an unsigned column modifier.
  modifyUnsigned: function(builder, column) {
    if (column.isUnsigned) return ' unsigned';
  },

  // Get the SQL for a default column modifier.
  modifyDefault: function(builder, column) {
    // TODO - no default on blob/text
    if (column.defaultValue != void 0 && column.type != 'blob' && column.type.indexOf('text') === -1) {
      return " default '" + this.getDefaultValue(column.defaultValue) + "'";
    }
  },

  // Get the SQL for an auto-increment column modifier.
  modifyIncrement: function(builder, column) {
    if (column.autoIncrement && (column.type == 'integer' || column.type == 'bigInteger')) {
      return ' not null auto_increment primary key';
    }
  },

  // Get the SQL for an "after" column modifier.
  modifyAfter: function(builder, column) {
    if (column.isAfter) {
      return ' after ' + this.wrap(column.isAfter);
    }
  },

  // Get the SQL for a comment column modifier.
  modifyComment: function(builder, column) {
    // TODO: Look into limiting this length.
    var maxColumnCommentLength = 255;
    if (column.isCommented && _.isString(column.isCommented)) {
      return " comment '" + column.isCommented + "'";
    }
  }

}, baseSchemaGrammar, grammar);<|endoftext|>


<commit_before>/* global describe it before beforeEach after afterEach */
var assert = require('assert')
var Doclet = require('../lib/models/doclet')
var env = require('../lib/env')
var mongoose = require('mongoose')
var Bull = require('bull')
var fs = require('fs')
var fse = require('fs-extra')
var path = require('path')
var docWorker = require('../lib/doc-worker')
var repo = require('../lib/repo')
var sinon = require('sinon')
var User = require('../lib/models/user')
var Repo = require('../lib/models/repo')
var async = require('async')

var loadGitHubEvent = function (eventDir) {
  var payload = fs.readFileSync(path.join(__dirname, '../fixtures/events', eventDir, 'payload.json'))
  return JSON.parse(payload)
}

var tmpPath = path.join(__dirname, 'git-temp')

describe('The doc-worker module', function () {
  this.timeout(120000)
  this.slow(8000)
  var inbox
  var failed
  var sandbox
  var getRepoEvents

  before(function (done) {
    getRepoEvents = sinon.stub(repo, 'getRepoEvents')
    getRepoEvents.yields(null, [])
    inbox = new Bull('inbox', env.redis.port, env.redis.host)
    failed = new Bull('failed', env.redis.port, env.redis.host)
    inbox.clean(200).then(function () {
      console.log('inbox queue clean')
      failed.clean(200).then(function () {
        console.log('failed queue clean')
        docWorker.init(tmpPath, done)
      })
    })
  })

  after(function (done) {
    fse.removeSync(tmpPath)
    getRepoEvents.restore()
    mongoose.connection.close(done)
  })

  beforeEach(function (done) {
    sandbox = sinon.sandbox.create()
    Doclet.remove({}, done)
  })

  afterEach(function () {
    sandbox.restore()
  })

  it('a push event will create a doclet', function (done) {
    var event = loadGitHubEvent('acme-push')
    inbox.add(event)
    setTimeout(function () {
      Doclet.findById('lipp/acme-jsdoc-example/master', function (err, doclet) {
        if (err) {
          done(err)
        } else {
          assert(doclet)
          inbox.count().then(function (count) {
            assert.equal(count, 0)
            done()
          })
        }
      })
    }, 5000)
  })

  it('a failing repo.checkout is handled', function (done) {
    var event = loadGitHubEvent('acme-push')
    failed.process(function (job, jobDone) {
      assert.equal(job.data.ref, event.ref)
      jobDone()
      inbox.count().then(function (count) {
        assert.equal(count, 0)
        done()
      })
      failed.close()
    })
    inbox.add(event)
    sandbox.stub(repo, 'checkout').throws('some error')
  })

  it('a failing Doclet.createFromGitHubEvent is handled', function (done) {
    var event = loadGitHubEvent('acme-push')
    var failed = new Bull('failed', env.redis.port, env.redis.host)
    failed.on('ready', function () {
      inbox.add(event)
      failed.process(function (job, jobDone) {
        assert.equal(job.data.ref, event.ref)
        jobDone()
        inbox.count().then(function (count) {
          assert.equal(count, 0)
          done()
        })
        failed.close()
      })
    })
    sandbox.stub(Doclet, 'createFromGitHubEvent').yields('some error')
  })

  it('a tag event will create a doclet', function (done) {
    var event = loadGitHubEvent('acme-tag')
    inbox.add(event)
    setTimeout(function () {
      Doclet.findById('lipp/acme-jsdoc-example/v1.0.11', function (err, doclet) {
        if (err) {
          done(err)
        } else {
          assert(doclet)
          inbox.count().then(function (count) {
            assert.equal(count, 0)
            done()
          })
        }
      })
    }, 5000)
  })

  it('pushing a trash event to the inbox will not create a doclet', function (done) {
    var event = {a: 123}
    sandbox.stub(Doclet, 'createFromGitHubEvent')
    var failed = new Bull('failed', env.redis.port, env.redis.host)
    failed.on('ready', function () {
      inbox.add(event)
      failed.process(function (job, jobDone) {
        assert.equal(job.data.a, 123)
        jobDone()
        failed.close().then(done)
      })
    })
  })

  it('pushing a push event with non branch head ref will not create a doclet', function (done) {
    var event = loadGitHubEvent('acme-push')
    event.ref = 'refs/foo/master'
    sandbox.stub(Doclet, 'createFromGitHubEvent')
    inbox.add(event)
    setTimeout(function () {
      assert(!Doclet.createFromGitHubEvent.called)
      inbox.count().then(function (count) {
        assert.equal(count, 0)
        done()
      })
    }, 100)
  })

  describe('with node-jet (get) events', function () {
    var events

    before(function () {
      events = JSON.parse(fs.readFileSync(path.join(__dirname, '../fixtures/node-jet_getevents.json')))
    })

    it('getTags(events)', function () {
      var tags = docWorker.getTags(events)
      assert(Array.isArray(tags))
      assert.equal(tags.length, 0)
    })

    it('getLastPushPerBranch(events) returns only latest master', function () {
      var lppb = docWorker.getLastPushPerBranch(events)
      assert(Array.isArray(lppb))
      assert.equal(lppb.length, 1)
      assert.equal(lppb[0].id, '3646551386')
      assert.equal(lppb[0].payload.ref, 'refs/heads/master')
    })
  })

  describe('with node-jet (get) events', function () {
    var events

    before(function () {
      events = JSON.parse(fs.readFileSync(path.join(__dirname, '../fixtures/acme-jsdoc-example_getevents.json')))
    })

    it('getTags(events)', function () {
      var tags = docWorker.getTags(events)
      assert(Array.isArray(tags))
      assert.equal(tags.length, 7)
      assert.equal(tags[0].id, 3636958336)
      assert.equal(tags[0].payload.ref, 'test-tag')
      assert.equal(tags[6].id, 3453845284)
      assert.equal(tags[6].payload.ref, 'v1.0.0')
    })

    it('getLastPushPerBranch(events) returns only latest master', function () {
      var lppb = docWorker.getLastPushPerBranch(events)
      assert(Array.isArray(lppb))
      assert.equal(lppb.length, 1)
      assert.equal(lppb[0].id, '3644279032')
      assert.equal(lppb[0].payload.ref, 'refs/heads/master')
    })
  })

  describe('catchup tests', function () {
    var events

    before(function () {
      events = JSON.parse(fs.readFileSync(path.join(__dirname, '../fixtures/acme-jsdoc-example_getevents.json')))
    })

    afterEach(function (done) {
      async.series([
        User.remove.bind(User, {}),
        Repo.remove.bind(Repo, {})
      ], done)
    })

    beforeEach(function (done) {
      var user = new User({
        _id: 'lipp',
        token: 12345
      })
      var repo1 = new Repo({
        _id: 'lipp/acme-jsdoc-example',
        name: 'acme-jsdoc-example',
        owner: 'lipp',
        _owner: 'lipp',
        webhook: {active: true}
      })
      var repo2 = new Repo({
        _id: 'lipp/bar2',
        name: 'bar2',
        owner: 'lipp',
        _owner: 'lipp',
        webhook: false
      })
      async.series([
        User.remove.bind(User, {}),
        Repo.remove.bind(Repo, {}),
        user.save.bind(user),
        repo1.save.bind(repo1),
        repo2.save.bind(repo2)
      ], done)
    })

    it('catchUpRepoEvents with no events', function (done) {
      getRepoEvents.yields(null, [])
      docWorker.catchUpRepoEvents(function () {
        assert('should not be called')
      }, done)
    })

    it('catchUpRepoEvents with events produces events able to create Doclets', function (done) {
      getRepoEvents.yields(null, events)
      var count = 0
      docWorker.catchUpRepoEvents(function (webhookEvent) {
        Doclet.createFromGitHubEvent(webhookEvent, [], function (err) {
          assert(!err)
          ++count
          if (count === 8) { // 7 tags and 1 branch
            done()
          }
        })
      })
    })
  })
})
<commit_msg>even higher timeouts<commit_after>/* global describe it before beforeEach after afterEach */
var assert = require('assert')
var Doclet = require('../lib/models/doclet')
var env = require('../lib/env')
var mongoose = require('mongoose')
var Bull = require('bull')
var fs = require('fs')
var fse = require('fs-extra')
var path = require('path')
var docWorker = require('../lib/doc-worker')
var repo = require('../lib/repo')
var sinon = require('sinon')
var User = require('../lib/models/user')
var Repo = require('../lib/models/repo')
var async = require('async')

var loadGitHubEvent = function (eventDir) {
  var payload = fs.readFileSync(path.join(__dirname, '../fixtures/events', eventDir, 'payload.json'))
  return JSON.parse(payload)
}

var tmpPath = path.join(__dirname, 'git-temp')

describe('The doc-worker module', function () {
  this.timeout(150000)
  this.slow(8000)
  var inbox
  var failed
  var sandbox
  var getRepoEvents

  before(function (done) {
    getRepoEvents = sinon.stub(repo, 'getRepoEvents')
    getRepoEvents.yields(null, [])
    inbox = new Bull('inbox', env.redis.port, env.redis.host)
    failed = new Bull('failed', env.redis.port, env.redis.host)
    inbox.clean(1000).then(function () {
      console.log('inbox queue clean')
      failed.clean(1000).then(function () {
        console.log('failed queue clean')
        docWorker.init(tmpPath, done)
      })
    })
  })

  after(function (done) {
    fse.removeSync(tmpPath)
    getRepoEvents.restore()
    mongoose.connection.close(done)
  })

  beforeEach(function (done) {
    sandbox = sinon.sandbox.create()
    Doclet.remove({}, done)
  })

  afterEach(function () {
    sandbox.restore()
  })

  it('a push event will create a doclet', function (done) {
    var event = loadGitHubEvent('acme-push')
    inbox.add(event)
    setTimeout(function () {
      Doclet.findById('lipp/acme-jsdoc-example/master', function (err, doclet) {
        if (err) {
          done(err)
        } else {
          assert(doclet)
          inbox.count().then(function (count) {
            assert.equal(count, 0)
            done()
          })
        }
      })
    }, 5000)
  })

  it('a failing repo.checkout is handled', function (done) {
    var event = loadGitHubEvent('acme-push')
    failed.process(function (job, jobDone) {
      assert.equal(job.data.ref, event.ref)
      jobDone()
      inbox.count().then(function (count) {
        assert.equal(count, 0)
        done()
      })
      failed.close()
    })
    inbox.add(event)
    sandbox.stub(repo, 'checkout').throws('some error')
  })

  it('a failing Doclet.createFromGitHubEvent is handled', function (done) {
    var event = loadGitHubEvent('acme-push')
    var failed = new Bull('failed', env.redis.port, env.redis.host)
    failed.on('ready', function () {
      inbox.add(event)
      failed.process(function (job, jobDone) {
        assert.equal(job.data.ref, event.ref)
        jobDone()
        inbox.count().then(function (count) {
          assert.equal(count, 0)
          done()
        })
        failed.close()
      })
    })
    sandbox.stub(Doclet, 'createFromGitHubEvent').yields('some error')
  })

  it('a tag event will create a doclet', function (done) {
    var event = loadGitHubEvent('acme-tag')
    inbox.add(event)
    setTimeout(function () {
      Doclet.findById('lipp/acme-jsdoc-example/v1.0.11', function (err, doclet) {
        if (err) {
          done(err)
        } else {
          assert(doclet)
          inbox.count().then(function (count) {
            assert.equal(count, 0)
            done()
          })
        }
      })
    }, 5000)
  })

  it('pushing a trash event to the inbox will not create a doclet', function (done) {
    var event = {a: 123}
    sandbox.stub(Doclet, 'createFromGitHubEvent')
    var failed = new Bull('failed', env.redis.port, env.redis.host)
    failed.on('ready', function () {
      inbox.add(event)
      failed.process(function (job, jobDone) {
        assert.equal(job.data.a, 123)
        jobDone()
        failed.close().then(done)
      })
    })
  })

  it('pushing a push event with non branch head ref will not create a doclet', function (done) {
    var event = loadGitHubEvent('acme-push')
    event.ref = 'refs/foo/master'
    sandbox.stub(Doclet, 'createFromGitHubEvent')
    inbox.add(event)
    setTimeout(function () {
      assert(!Doclet.createFromGitHubEvent.called)
      inbox.count().then(function (count) {
        assert.equal(count, 0)
        done()
      })
    }, 100)
  })

  describe('with node-jet (get) events', function () {
    var events

    before(function () {
      events = JSON.parse(fs.readFileSync(path.join(__dirname, '../fixtures/node-jet_getevents.json')))
    })

    it('getTags(events)', function () {
      var tags = docWorker.getTags(events)
      assert(Array.isArray(tags))
      assert.equal(tags.length, 0)
    })

    it('getLastPushPerBranch(events) returns only latest master', function () {
      var lppb = docWorker.getLastPushPerBranch(events)
      assert(Array.isArray(lppb))
      assert.equal(lppb.length, 1)
      assert.equal(lppb[0].id, '3646551386')
      assert.equal(lppb[0].payload.ref, 'refs/heads/master')
    })
  })

  describe('with node-jet (get) events', function () {
    var events

    before(function () {
      events = JSON.parse(fs.readFileSync(path.join(__dirname, '../fixtures/acme-jsdoc-example_getevents.json')))
    })

    it('getTags(events)', function () {
      var tags = docWorker.getTags(events)
      assert(Array.isArray(tags))
      assert.equal(tags.length, 7)
      assert.equal(tags[0].id, 3636958336)
      assert.equal(tags[0].payload.ref, 'test-tag')
      assert.equal(tags[6].id, 3453845284)
      assert.equal(tags[6].payload.ref, 'v1.0.0')
    })

    it('getLastPushPerBranch(events) returns only latest master', function () {
      var lppb = docWorker.getLastPushPerBranch(events)
      assert(Array.isArray(lppb))
      assert.equal(lppb.length, 1)
      assert.equal(lppb[0].id, '3644279032')
      assert.equal(lppb[0].payload.ref, 'refs/heads/master')
    })
  })

  describe('catchup tests', function () {
    var events

    before(function () {
      events = JSON.parse(fs.readFileSync(path.join(__dirname, '../fixtures/acme-jsdoc-example_getevents.json')))
    })

    afterEach(function (done) {
      async.series([
        User.remove.bind(User, {}),
        Repo.remove.bind(Repo, {})
      ], done)
    })

    beforeEach(function (done) {
      var user = new User({
        _id: 'lipp',
        token: 12345
      })
      var repo1 = new Repo({
        _id: 'lipp/acme-jsdoc-example',
        name: 'acme-jsdoc-example',
        owner: 'lipp',
        _owner: 'lipp',
        webhook: {active: true}
      })
      var repo2 = new Repo({
        _id: 'lipp/bar2',
        name: 'bar2',
        owner: 'lipp',
        _owner: 'lipp',
        webhook: false
      })
      async.series([
        User.remove.bind(User, {}),
        Repo.remove.bind(Repo, {}),
        user.save.bind(user),
        repo1.save.bind(repo1),
        repo2.save.bind(repo2)
      ], done)
    })

    it('catchUpRepoEvents with no events', function (done) {
      getRepoEvents.yields(null, [])
      docWorker.catchUpRepoEvents(function () {
        assert('should not be called')
      }, done)
    })

    it('catchUpRepoEvents with events produces events able to create Doclets', function (done) {
      getRepoEvents.yields(null, events)
      var count = 0
      docWorker.catchUpRepoEvents(function (webhookEvent) {
        Doclet.createFromGitHubEvent(webhookEvent, [], function (err) {
          assert(!err)
          ++count
          if (count === 8) { // 7 tags and 1 branch
            done()
          }
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>/**
 * @fileoveview This Connector make connection between Uploader and html5 file api.
 * @author NHN Ent. FE Development Team <dl_javascript@nhnent.com>
 */
var utils = require('../utils');

/**
 * The modules will be mixed in connector by type.
 */
var Local = {/** @lends ne.component.Uploader.Local */
    /**
     * A result array to save file to send.
     */
    _result : null,
    /**
     * Add Request, save files to array.
     * @param data
     */
    addRequest: function(data) {
        var isValidPool = utils.isSupportFormData(),
            result = this._saveFile(isValidPool);
        data.success({
            items: result
        });
    },

    /**
     * Save file to pool
     * @param {boolean} isSupportAjax Whether FormData is supported or not
     * @private
     */
    _saveFile: function(isSupportAjax) {
        var uploader = this._uploader,
            inputView = uploader.inputView,
            fileEl = inputView.$input[0],
            result = [];

        if (!this._result) {
            this._result = [];
        }

        if (isSupportAjax) {
            ne.util.forEach(fileEl.files, function(item) {
                if (ne.util.isObject(item)) {
                    result.push(item);
                }
            }, this);
        } else {
            result.push({
                name: fileEl.value,
                element: fileEl
            });
        }

        this._result = this._result.concat(result);

        return result;
    },

    /**
     * Make form data to send POST(FormDate supported case)
     * @returns {*}
     * @private
     */
    _makeFormData : function() {
        var uploader = this._uploader,
            form = new window.FormData();

        ne.util.forEach(this._result, function(item) {
            form.append(uploader.fileField, item);
        });
        return form;
    },

    /**
     * Remove file form result array
     * @param {object} info The information set to remove file
     */
    removeRequest: function(info) {
        var data = info.data;
        this._result = ne.util.filter(this._result, function(el) {
            return el.name !== data.filename;
        });

        info.success({
            action: 'remove',
            name: data.filename
        });
    },

    /**
     * Send files in a batch.
     * @param callback
     */
    submit: function(callback) {
        var form = this._makeFormData();
        $.ajax({
            url: this._uploader.url.send,
            type: 'POST',
            data: form,
            success: callback,
            processData: false,
            contentType: false
        });
    }
};

module.exports = Local;<commit_msg>files<commit_after>/**
 * @fileoveview This Connector make connection between Uploader and html5 file api.
 * @author NHN Ent. FE Development Team <dl_javascript@nhnent.com>
 */
var utils = require('../utils');

/**
 * The modules will be mixed in connector by type.
 */
var Local = {/** @lends ne.component.Uploader.Local */
    /**
     * A result array to save file to send.
     */
    _result : null,
    /**
     * Add Request, save files to array.
     * @param data
     */
    addRequest: function(data) {
        var isValidPool = utils.isSupportFormData(),
            result = this._saveFile(isValidPool);
        data.success({
            items: result
        });
    },

    /**
     * Save file to pool
     * @param {boolean} isSupportAjax Whether FormData is supported or not
     * @private
     */
    _saveFile: function(isSupportAjax) {
        var uploader = this._uploader,
            inputView = uploader.inputView,
            fileEl = inputView.$input[0],
            result = [];

        if (!this._result) {
            this._result = [];
        }

        if (isSupportAjax) {
            ne.util.forEach(fileEl.files, function(item) {
                if (ne.util.isObject(item)) {
                    result.push(item);
                }
            }, this);
        } else {
            result.push({
                name: fileEl.value,
                element: fileEl
            });
        }

        this._result = this._result.concat(result);

        return result;
    },

    /**
     * Make form data to send POST(FormDate supported case)
     * @returns {*}
     * @private
     */
    _makeFormData : function() {
        var field = this._uploader.fileField,
            form = new window.FormData();

        ne.util.forEach(this._result, function(item) {
            form.append(field, item);
        });
        return form;
    },

    /**
     * Remove file form result array
     * @param {object} info The information set to remove file
     */
    removeRequest: function(info) {
        var data = info.data;
        this._result = ne.util.filter(this._result, function(el) {
            return el.name !== data.filename;
        });

        info.success({
            action: 'remove',
            name: data.filename
        });
    },

    /**
     * Send files in a batch.
     * @param callback
     */
    submit: function(callback) {
        var form = this._makeFormData();
        $.ajax({
            url: this._uploader.url.send,
            type: 'POST',
            data: form,
            success: callback,
            processData: false,
            contentType: false
        });
    }
};

module.exports = Local;<|endoftext|>


<commit_before>// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// 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.

goog.provide('goog.debug.FpsDisplayTest');
goog.setTestOnly('goog.debug.FpsDisplayTest');

goog.require('goog.Timer');
goog.require('goog.debug.FpsDisplay');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.jsunit');

var fpsDisplay;

function setUpPage() {
  goog.testing.TestCase.getActiveTestCase().promiseTimeout = 5000; // 5s
}

function setUp() {
  fpsDisplay = new goog.debug.FpsDisplay();
}

function tearDown() {
  goog.dispose(fpsDisplay);
}

function testRendering() {
  fpsDisplay.render();

  var elem = fpsDisplay.getElement();
  assertHTMLEquals('', elem.innerHTML);

  return goog.Timer.promise(2000).then(function() {
    var fps = parseInt(elem.innerHTML, 10);
    assertTrue('FPS of ' + fps + ' should be non-negative', fps >= 0);
    assertTrue('FPS of ' + fps + ' too big', fps < 1000);
  });
}
<commit_msg>Disable fpsdisplay_test on external testing infra. See bug for context. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=109912662<commit_after>// Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// 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.

goog.provide('goog.debug.FpsDisplayTest');
goog.setTestOnly('goog.debug.FpsDisplayTest');

goog.require('goog.Timer');
goog.require('goog.debug.FpsDisplay');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.jsunit');

var fpsDisplay;

function shouldRunTests() {
  // Disable tests when being run as a part of open-source repo as the test
  // mysteriously times out way before 5s. See http://b/26132213.
  return !(/closure\/goog\/ui/.test(location.pathname));
}

function setUpPage() {
  goog.testing.TestCase.getActiveTestCase().promiseTimeout = 5000; // 5s
}

function setUp() {
  fpsDisplay = new goog.debug.FpsDisplay();
}

function tearDown() {
  goog.dispose(fpsDisplay);
}

function testRendering() {
  fpsDisplay.render();

  var elem = fpsDisplay.getElement();
  assertHTMLEquals('', elem.innerHTML);

  return goog.Timer.promise(2000).then(function() {
    var fps = parseInt(elem.innerHTML, 10);
    assertTrue('FPS of ' + fps + ' should be non-negative', fps >= 0);
    assertTrue('FPS of ' + fps + ' too big', fps < 1000);
  });
}
<|endoftext|>


<commit_before>const absol98sk = [
	"If you're a trainer, talk with Pokemon!!"
];

const amiy = [
	"went to find people to flop on.",
	"got swallowed whole by a Snorlax."
];

const anrindas = [
	"went back to the Dragon's Den."
];

const axtheefrost = [
	"went to aliment Wobbuffet."
];

const bidoofftw = [
	"was forced onto bed by Kingdom of Tea."
];

const ctfrm = [
	"is better than Christos."
];

const christs = [
	"is everyone's favourite moderator."
];

const darklight1999 = [
	"returns back to darkness."
];

const darkshadow6 = [
	"Never Give Up"
];

const f4n = [
	"evoluciona a Pichu Tipo Hada."
];

const hannumikkola = [
	"is stealing your food now."
];

const indiancharizard = [
	"was struck by Dragon Slayer Anrin's dark magic."
];

const kingdomoftea = [
	"retreats to get more tea."
];

const srinator = [
	"elfs smells too much, ima leave"
];

const wolf = [
	"howls to the moon.",
	"runs off into a forest."
];

const zincoxide = [
	"reacts with the cosmos and vanishes."
];

exports.commands = {
	d: 'poof',
	cpoof: 'poof',
	poof: function (target, room, user) {
		if (Config.poofOff) return this.sendReply("Poof is currently disabled.");
		if (!this.canTalk(message)) return false;
		var userid = user.name
		userid = userid.replace(/[^\x00-\x7F]/g, "");
		if (userid.toUpperCase() === 'WOLF') {
			var message = target || wolf[Math.floor(Math.random() * wolf.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'ABSOL98SK') {
			var message = target || absol98sk[Math.floor(Math.random() * absol98sk.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'AMIY' || userid.toUpperCase() === 'KIMISUMI') {
			var message = target || amiy[Math.floor(Math.random() * amiy.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'ANRIN DAS' || userid.toUpperCase() === 'ANRIN N') {
			var message = target || anrindas[Math.floor(Math.random() * anrindas.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'AXTHEEFROST' || userid.toUpperCase() === 'ANDY VENUS') {
			var message = target || axtheefrost[Math.floor(Math.random() * axtheefrost.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'BIDOOF FTW') {
			var message = target || bidoofftw[Math.floor(Math.random() * bidoofftw.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'CTFRM') {
			var message = target || ctfrm[Math.floor(Math.random() * ctfrm.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'CHRISTS') {
			var message = target || christs[Math.floor(Math.random() * christs.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'DARK LIGHT1999') {
			var message = target || darklight1999[Math.floor(Math.random() * darklight1999.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'DARK SHADOW 6') {
			var message = target || darkshadow6[Math.floor(Math.random() * darkshadow6.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'F4N') {
			var message = target || f4n[Math.floor(Math.random() * f4n.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'HANNU MIKKOLA') {
			var message = target || hannumikkola[Math.floor(Math.random() * hannumikkola.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'INDIANCHARIZARD#' || userid.toUpperCase() === 'ASTRAEA') {
			var message = target || indiancharizard[Math.floor(Math.random() * indiancharizard.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'KINGDOM OF TEA') {
			var message = target || kingdomoftea[Math.floor(Math.random() * kingdomoftea.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'SRINATOR') {
			var message = target || srinator[Math.floor(Math.random() * srinator.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'ZINC OXIDE') {
			var message = target || zincoxide[Math.floor(Math.random() * zincoxide.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
	},

	poofoff: 'nopoof',
	nopoof: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = true;
		return this.sendReply("Poof is now disabled.");
	},

	poofon: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = false;
		return this.sendReply("Poof is now enabled.");
	}
};
<commit_msg>Update poof.js<commit_after>const absol98sk = [
	"If you're a trainer, talk with Pokemon!!"
];

const amiy = [
	"went to find people to flop on.",
	"got swallowed whole by a Snorlax."
];

const anrindas = [
	"went back to the Dragon's Den."
];

const axtheefrost = [
	"went to aliment Wobbuffet."
];

const bidoofftw = [
	"was forced onto bed by Kingdom of Tea."
];

const ctfrm = [
	"is better than Christos."
];

const christs = [
	"is everyone's favourite moderator."
];

const darklight1999 = [
	"returns back to darkness."
];

const darkshadow6 = [
	"Never Give Up"
];

const f4n = [
	"evoluciona a Pichu Tipo Hada."
];

const hannumikkola = [
	"is stealing your food now."
];

const indiancharizard = [
	"was struck by Dragon Slayer Anrin's dark magic."
];

const kingdomoftea = [
	"retreats to get more tea."
];

const srinator = [
	"elfs smells too much, ima leave"
];

const wolf = [
	"howls to the moon.",
	"runs off into a forest."
];

const zincoxide = [
	"reacts with the cosmos and vanishes."
];

exports.commands = {
	d: 'poof',
	cpoof: 'poof',
	poof: function (target, room, user) {
		if (Config.poofOff) return this.sendReply("Poof is currently disabled.");
		if (!this.canTalk(message)) return false;
		var userid = user.name
		userid = userid.replace(/[^\x00-\x7F]/g, "");
		if (userid.toUpperCase() === 'WOLF') {
			var message = target || wolf[Math.floor(Math.random() * wolf.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'ABSOL98SK') {
			var message = target || absol98sk[Math.floor(Math.random() * absol98sk.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'AMIY' || userid.toUpperCase() === 'KIMISUMI') {
			var message = target || amiy[Math.floor(Math.random() * amiy.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'ANRIN DAS' || userid.toUpperCase() === 'ANRIN N') {
			var message = target || anrindas[Math.floor(Math.random() * anrindas.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'AXTHEEFROST' || userid.toUpperCase() === 'ANDY VENUS') {
			var message = target || axtheefrost[Math.floor(Math.random() * axtheefrost.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'BIDOOF FTW') {
			var message = target || bidoofftw[Math.floor(Math.random() * bidoofftw.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'CTFRM') {
			var message = target || ctfrm[Math.floor(Math.random() * ctfrm.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'CHRISTS') {
			var message = target || christs[Math.floor(Math.random() * christs.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'DARK LIGHT1999') {
			var message = target || darklight1999[Math.floor(Math.random() * darklight1999.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'DARK SHADOW 6') {
			var message = target || darkshadow6[Math.floor(Math.random() * darkshadow6.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'F4N') {
			var message = target || f4n[Math.floor(Math.random() * f4n.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'HANNU MIKKOLA') {
			var message = target || hannumikkola[Math.floor(Math.random() * hannumikkola.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'INDIANCHARIZARD#' || userid.toUpperCase() === 'ASTRAEA') {
			var message = target || indiancharizard[Math.floor(Math.random() * indiancharizard.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'KINGDOM OF TEA') {
			var message = target || kingdomoftea[Math.floor(Math.random() * kingdomoftea.length)];
			if (message.indexOf('{{user}}') < 0) {
				message = '{{user}} ' + message;
			}
			message = message.replace(/{{user}}/g, user.name);

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'SRINATOR') {
			var message = target || srinator[Math.floor(Math.random() * srinator.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		} else if (userid.toUpperCase() === 'ZINC OXIDE') {
			var message = target || zincoxide[Math.floor(Math.random() * zincoxide.length)];

			var colour = '#' + [1, 1, 1].map(function () {
				var part = Math.floor(Math.random() * 0xaa);
				return (part < 0x10 ? '0' : '') + part.toString(16);
			}).join('');

			room.addRaw('~~ ' + Tools.escapeHTML(message) + ' ~~');
			user.disconnectAll();
		}
	},

	poofoff: 'nopoof',
	nopoof: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = true;
		return this.sendReply("Poof is now disabled.");
	},

	poofon: function () {
		if (!this.can('poofoff')) return false;
		Config.poofOff = false;
		return this.sendReply("Poof is now enabled.");
	}
};
<|endoftext|>


<commit_before>(function() {
    'use strict';

    angular
        .module('app.core')
        .factory('AppService', appService);

    appService.$inject = ['$location', '$timeout', '$window'];

    function appService($location, $timeout, $window) {
        var timer;
        return {
            togglePanel: function(active) {
                if (this.panel.navigationActive === active) {
                    if (this.panel.viewActive) {
                        if (this.panel.viewVisible) {
                            this.panel.viewVisible = false;
                        } else {
                            this.panel.viewVisible = true;
                            this.panel.navigationActive = "";
                        }
                    } else {
                        this.panel.navigationActive = "";
                    }
                } else {
                    this.panel.navigationActive = active;
                    this.panel.viewVisible = false;
                }
            },
            replacePoints: function() {
                $timeout.cancel(timer);
                angular.element("#m-map-container").css({
                    cursor: "wait"
                });
                angular.element("body").find(".projects").addClass("is-resizing");
                timer = $timeout(function() {
                    angular.element("#m-map-container").css({
                        cursor: "move"
                    });
                    angular.element("body").find(".projects").removeClass("is-resizing")
                }, 1000)
            },
            setBreakpoint: function() {
                var isBreakpoint, width = $window.innerWidth;
                //return isBreakpoint = width >= 960 ? "desktop" : width >= 600 ? "tablet" : "mobile", isBreakpoint !== this.states.isBreakpoint ? (this.replacePoints(), this.states.isBreakpoint = isBreakpoint, !0) : !1
                isBreakpoint = width >= 960 ? "desktop" : width >= 600 ? "tablet" : "mobile";

                if (isBreakpoint !== this.states.isBreakpoint) {
                    this.replacePoints();
                    this.states.isBreakpoint = isBreakpoint;
                    return true;
                }

                return false;

            },
            openView: function(id) {
                var url = "/karta/projekt/" + id;
                url !== $location.path() ? $location.path(url) : (this.panel.navigationActive = "", this.panel.viewVisible = true)
            },
            closeView: function() {
                this.panel.viewActive = false;
                $location.path("/karta/");
            },
            openProject: function(id) {
                $location.path("/karta/projekt/" + id);
                this.panel.navigationActive = "";
            },
            logo:"聚贸·国家馆 JUMORE•National Pavilion",
            pavilions: {
                national:"国家馆",
                provincial: "省馆",
                brand: "品牌馆"
            },
            panel: {
                navigationActive: "",
                viewActive: false,
                viewVisible: false,
                mobilePopupItems: []
            },
            elements: {
                navigationBar: true,//false,
                backToStart: false,
                mobilePopup: false,
                scrollHelp: {
                    visible: false,
                    show: true
                }
            },
            filter: {
                selected: {
                    countries: {},
                    themes: {}
                },
                themes: [{
                    theme_id: 4,
                    name: "Hållbar försörjning"
                }, {
                    theme_id: 5,
                    name: "Mänskliga rättigheter"
                }, {
                    theme_id: 6,
                    name: "Rätten till hälsa"
                }, {
                    theme_id: 7,
                    name: "Tro och lärande"
                }, {
                    theme_id: 8,
                    name: "Katastrof"
                }]
            },
            states: {
                isScrollable: !1,
                isFiltered: !1,
                isFiltering: !1,
                isInit: false,
                isTouch: !1,
                isMobileNav: !1,
                isScrollhelpShowed: !1,
                isBreakpoint: ""
            },
            window: {
                width: 0,
                height: 0
            }
        }
    }

    angular
        .module('app.core')
        .factory("RemoteCallService", function() {
            return {
                get: function(req) {
                    if ("undefined" == typeof req.type && (req.type = "GET"), req.xhrFields = {
                            withCredentials: false
                        }, jQuery.support.cors = true, window.XDomainRequest) {
                        var defer = new jQuery.Deferred;
                        defer.done(req.success), defer.fail(req.error);
                        var xdomainReq = new XDomainRequest,
                            param = "";
                        return req.data && (param = "?" + jQuery.param(req.data)), xdomainReq.onprogress = function() {}, xdomainReq.onload = function() {
                            defer.resolve("application/json" === xdomainReq.contentType ? jQuery.parseJSON(xdomainReq.responseText) : xdomainReq.responseText)
                        }, xdomainReq.onerror = function() {
                            defer.reject(xdomainReq)
                        }, xdomainReq.open(req.type, req.url + param), xdomainReq.send(), defer
                    }
                    return jQuery.ajax(req)
                }
            }
        })

    angular
        .module('app.core')
        .factory("GetProjectOfTheMonthService", ["RemoteCallService", function(RemoteCallService) {
            return {
                get: function(formatDate, callback) {
                    RemoteCallService.get({
                        url: "mocks/manadensProjekt.json",
                        type: "GET",
                        crossDomain: true,
                        dataType: "json",
                        success: function(response) {
                            for (var project = {}, i = 0; i < response.value.length; i++) project.id = response.value[i].insamlingsprojektID;
                            callback(project)
                        },
                        error: function() {
                            var project = {};
                            callback(project.id = 0)
                        }
                    })
                }
            }
        }])

    angular
        .module('app.core')
        .factory("GetProjectService", ["RemoteCallService", function(a) {
            return {
                get: function(b, c) {
                    a.get({
                        url: "mocks/projektkartanprojekt.json",
                        type: "GET",
                        crossDomain: !0,
                        dataType: "json",
                        success: function(a) {
                            for (var b = {}, d = 0; d < a.value.length; d++) {
                                b.id = a.value[d].insamlingsprojektID, b.title = a.value[d].rubrik, b.type_id = a.value[d].projekttyp.projekttypID, b.type_name = a.value[d].projekttyp.namn, b.country_id = a.value[d].land.landID, b.country_name = a.value[d].land.namn, b.theme = a.value[d].tema.namn, b.theme_id = a.value[d].tema.temaID, b.city = a.value[d].ort, b.lat = a.value[d].latitud, b.lon = a.value[d].longitud, b.has_position = 0 == b.lon && 0 == b.lat, b.project_number = a.value[d].projektkod;
                                var e = a.value[d].insamlingsmal;
                                b.fund_goal = e.toString().replace(/(\d)(?=(\d{3})+$)/g, "$1 "), b.slug = a.value[d].slug, b.video = a.value[d].filmUrl, b.text = a.value[d].ingress, b.text_extended = a.value[d].beskrivning, b.link = a.value[d].projektsidaUrl, b.keywords = new Array;
                                for (var f = 0; f < a.value[d].insamlingsprojektNyckelord.length; f++) b.keywords.push(a.value[d].insamlingsprojektNyckelord[f].nyckelord.namn)
                            }
                            c(b)
                        }
                    })
                }
            }
        }])

    angular
        .module('app.core')
        .factory("GetProjectsService", ["RemoteCallService", function(RemoteCallService) {
            return {
                get: function(id, callback) {
                    RemoteCallService.get({
                        type: "GET",
                        url: "mocks/projektkartanprojekts.json",
                        crossDomain: !0,
                        dataType: "json",
                        success: function(response) {
                            for (var arr = new Array, i = 0; i < response.value.length; i++) {
                                var project = {};
                                project.id = response.value[i].insamlingsprojektID, project.projectOfTheMonth = project.id === id, project.title = response.value[i].rubrik, project.type_id = response.value[i].projekttyp.projekttypID, project.type_name = response.value[i].projekttyp.namn, project.country_id = response.value[i].land.landID, project.country_name = response.value[i].land.namn, project.theme = response.value[i].tema.namn, project.theme_id = response.value[i].tema.temaID, project.city = response.value[i].ort, project.lat = response.value[i].latitud, project.lon = response.value[i].longitud, project.has_position = null !== project.lon && null !== project.lat, project.project_number = response.value[i].projektkod, project.video = response.value[i].filmUrl, project.slug = response.value[i].slug, project.image_query = response.value[i].bildApiSearchQueryUrl, project.keywords = new Array;
                                for (var j = 0; j < response.value[i].insamlingsprojektNyckelord.length; j++) project.keywords.push(response.value[i].insamlingsprojektNyckelord[j].nyckelord.namn);
                                arr.push(project)
                            }
                            callback(arr)
                        }
                    })
                }
            }
        }])

})();

<commit_msg>remove unused code<commit_after>(function() {
    'use strict';

    angular
        .module('app.core')
        .factory('AppService', appService);

    appService.$inject = ['$location', '$timeout', '$window'];

    function appService($location, $timeout, $window) {
        var timer;
        return {
            togglePanel: function(active) {
                if (this.panel.navigationActive === active) {
                    if (this.panel.viewActive) {
                        if (this.panel.viewVisible) {
                            this.panel.viewVisible = false;
                        } else {
                            this.panel.viewVisible = true;
                            this.panel.navigationActive = "";
                        }
                    } else {
                        this.panel.navigationActive = "";
                    }
                } else {
                    this.panel.navigationActive = active;
                    this.panel.viewVisible = false;
                }
            },
            replacePoints: function() {
                $timeout.cancel(timer);
                angular.element("#m-map-container").css({
                    cursor: "wait"
                });
                angular.element("body").find(".projects").addClass("is-resizing");
                timer = $timeout(function() {
                    angular.element("#m-map-container").css({
                        cursor: "move"
                    });
                    angular.element("body").find(".projects").removeClass("is-resizing")
                }, 1000)
            },
            setBreakpoint: function() {
                var isBreakpoint, width = $window.innerWidth;
                isBreakpoint = width >= 960 ? "desktop" : width >= 600 ? "tablet" : "mobile";

                if (isBreakpoint !== this.states.isBreakpoint) {
                    this.replacePoints();
                    this.states.isBreakpoint = isBreakpoint;
                    return true;
                }

                return false;

            },
            openView: function(id) {
                var url = "/karta/projekt/" + id;
                url !== $location.path() ? $location.path(url) : (this.panel.navigationActive = "", this.panel.viewVisible = true)
            },
            closeView: function() {
                this.panel.viewActive = false;
                $location.path("/karta/");
            },
            openProject: function(id) {
                $location.path("/karta/projekt/" + id);
                this.panel.navigationActive = "";
            },
            logo:"聚贸·国家馆 JUMORE•National Pavilion",
            pavilions: {
                national:"国家馆",
                provincial: "省馆",
                brand: "品牌馆"
            },
            panel: {
                navigationActive: "",
                viewActive: false,
                viewVisible: false,
                mobilePopupItems: []
            },
            elements: {
                navigationBar: true,//false,
                backToStart: false,
                mobilePopup: false,
                scrollHelp: {
                    visible: false,
                    show: true
                }
            },
            filter: {
                selected: {
                    countries: {},
                    themes: {}
                },
                themes: [{
                    theme_id: 4,
                    name: "Hållbar försörjning"
                }, {
                    theme_id: 5,
                    name: "Mänskliga rättigheter"
                }, {
                    theme_id: 6,
                    name: "Rätten till hälsa"
                }, {
                    theme_id: 7,
                    name: "Tro och lärande"
                }, {
                    theme_id: 8,
                    name: "Katastrof"
                }]
            },
            states: {
                isScrollable: !1,
                isFiltered: !1,
                isFiltering: !1,
                isInit: false,
                isTouch: !1,
                isMobileNav: !1,
                isScrollhelpShowed: !1,
                isBreakpoint: ""
            },
            window: {
                width: 0,
                height: 0
            }
        }
    }

    angular
        .module('app.core')
        .factory("RemoteCallService", function() {
            return {
                get: function(req) {
                    if ("undefined" == typeof req.type && (req.type = "GET"), req.xhrFields = {
                            withCredentials: false
                        }, jQuery.support.cors = true, window.XDomainRequest) {
                        var defer = new jQuery.Deferred;
                        defer.done(req.success), defer.fail(req.error);
                        var xdomainReq = new XDomainRequest,
                            param = "";
                        return req.data && (param = "?" + jQuery.param(req.data)), xdomainReq.onprogress = function() {}, xdomainReq.onload = function() {
                            defer.resolve("application/json" === xdomainReq.contentType ? jQuery.parseJSON(xdomainReq.responseText) : xdomainReq.responseText)
                        }, xdomainReq.onerror = function() {
                            defer.reject(xdomainReq)
                        }, xdomainReq.open(req.type, req.url + param), xdomainReq.send(), defer
                    }
                    return jQuery.ajax(req)
                }
            }
        })

    angular
        .module('app.core')
        .factory("GetProjectOfTheMonthService", ["RemoteCallService", function(RemoteCallService) {
            return {
                get: function(formatDate, callback) {
                    RemoteCallService.get({
                        url: "mocks/manadensProjekt.json",
                        type: "GET",
                        crossDomain: true,
                        dataType: "json",
                        success: function(response) {
                            for (var project = {}, i = 0; i < response.value.length; i++) project.id = response.value[i].insamlingsprojektID;
                            callback(project)
                        },
                        error: function() {
                            var project = {};
                            callback(project.id = 0)
                        }
                    })
                }
            }
        }])

    angular
        .module('app.core')
        .factory("GetProjectService", ["RemoteCallService", function(a) {
            return {
                get: function(b, c) {
                    a.get({
                        url: "mocks/projektkartanprojekt.json",
                        type: "GET",
                        crossDomain: !0,
                        dataType: "json",
                        success: function(a) {
                            for (var b = {}, d = 0; d < a.value.length; d++) {
                                b.id = a.value[d].insamlingsprojektID, b.title = a.value[d].rubrik, b.type_id = a.value[d].projekttyp.projekttypID, b.type_name = a.value[d].projekttyp.namn, b.country_id = a.value[d].land.landID, b.country_name = a.value[d].land.namn, b.theme = a.value[d].tema.namn, b.theme_id = a.value[d].tema.temaID, b.city = a.value[d].ort, b.lat = a.value[d].latitud, b.lon = a.value[d].longitud, b.has_position = 0 == b.lon && 0 == b.lat, b.project_number = a.value[d].projektkod;
                                var e = a.value[d].insamlingsmal;
                                b.fund_goal = e.toString().replace(/(\d)(?=(\d{3})+$)/g, "$1 "), b.slug = a.value[d].slug, b.video = a.value[d].filmUrl, b.text = a.value[d].ingress, b.text_extended = a.value[d].beskrivning, b.link = a.value[d].projektsidaUrl, b.keywords = new Array;
                                for (var f = 0; f < a.value[d].insamlingsprojektNyckelord.length; f++) b.keywords.push(a.value[d].insamlingsprojektNyckelord[f].nyckelord.namn)
                            }
                            c(b)
                        }
                    })
                }
            }
        }])

    angular
        .module('app.core')
        .factory("GetProjectsService", ["RemoteCallService", function(RemoteCallService) {
            return {
                get: function(id, callback) {
                    RemoteCallService.get({
                        type: "GET",
                        url: "mocks/projektkartanprojekts.json",
                        crossDomain: true,
                        dataType: "json",
                        success: function(response) {
                            for (var arr = new Array, i = 0; i < response.value.length; i++) {
                                var project = {};
                                project.id = response.value[i].insamlingsprojektID, project.projectOfTheMonth = project.id === id, project.title = response.value[i].rubrik, project.type_id = response.value[i].projekttyp.projekttypID, project.type_name = response.value[i].projekttyp.namn, project.country_id = response.value[i].land.landID, project.country_name = response.value[i].land.namn, project.theme = response.value[i].tema.namn, project.theme_id = response.value[i].tema.temaID, project.city = response.value[i].ort, project.lat = response.value[i].latitud, project.lon = response.value[i].longitud, project.has_position = null !== project.lon && null !== project.lat, project.project_number = response.value[i].projektkod, project.video = response.value[i].filmUrl, project.slug = response.value[i].slug, project.image_query = response.value[i].bildApiSearchQueryUrl, project.keywords = new Array;
                                for (var j = 0; j < response.value[i].insamlingsprojektNyckelord.length; j++) project.keywords.push(response.value[i].insamlingsprojektNyckelord[j].nyckelord.namn);
                                arr.push(project)
                            }
                            callback(arr)
                        }
                    })
                }
            }
        }])

})();

<|endoftext|>


<commit_before>/* Seen command
 * by jd and panpawn
 */

'use strict';

if (typeof Gold === 'undefined') global.Gold = {};

const fs = require('fs');
const moment = require('moment');

let seenData = {};
function loadData() {
	try {
		seenData = JSON.parse(fs.readFileSync('config/seenData.json', 'utf8'));
	} catch (e) {
		seenData = {};
	}
}
loadData();

function saveData() {
	fs.writeFileSync('config/seenData.json', JSON.stringify(seenData));
}

function updateSeen(userid) {
	if (!userid) return false;
	seenData[toId(userid)] = Date.now();
	saveData();
}

global.updateSeen = updateSeen;
Gold.seenData = seenData;

exports.commands = {
	lastseen: 'seen',
	seen: function (target, room, user) {
		try {
			switch (target) {
			case 'obj':
				if (!this.runBroadcast()) return;
				this.sendReplyBox("There have been " + Object.size(seenData) + " user names recorded in this database.");
				break;
			default:
				if (!this.runBroadcast()) return;
				let userid = toId(target);
				if (toId(target).length > 18) return this.errorReply("Usernames cannot be over 18 characters.");
				if (userid.length < 1) return this.errorReply("/seen - Please specify a name.");
				let userName = '' + Gold.nameColor(target, false) + '';
				if (Users(target) && Users(target).connected) return this.sendReplyBox(userName + ' is currently online.');
				if (!seenData[userid]) return this.sendReplyBox(userName + ' has never been seen online on this server.');
				let userLastSeen = moment(seenData[userid]).format("MMMM Do YYYY, h:mm:ss a");
				let userLastSeenLabel = userLastSeen.substr(-2).toUpperCase(); //AM or PM
				this.sendReplyBox(userName + ' was last seen online on ' + userLastSeen.substring(0, userLastSeen.length - 2) + userLastSeenLabel + ' EST. (' + moment(seenData[userid]).fromNow() + ')');
				break;
			}
		} catch (e) {
			return this.sendReply("Something failed: \n" + e.stack);
		}
	},
};
<commit_msg>Clean up the seen output code a bit<commit_after>/* Seen command
 * by jd and panpawn
 */

'use strict';

if (typeof Gold === 'undefined') global.Gold = {};

const fs = require('fs');
const moment = require('moment');

let seenData = {};
function loadData() {
	try {
		seenData = JSON.parse(fs.readFileSync('config/seenData.json', 'utf8'));
	} catch (e) {
		seenData = {};
	}
}
loadData();

function saveData() {
	fs.writeFileSync('config/seenData.json', JSON.stringify(seenData));
}

function updateSeen(userid) {
	if (!userid) return false;
	seenData[toId(userid)] = Date.now();
	saveData();
}

global.updateSeen = updateSeen;
Gold.seenData = seenData;

exports.commands = {
	lastseen: 'seen',
	seen: function (target, room, user) {
		try {
			switch (target) {
			case 'obj':
				if (!this.runBroadcast()) return;
				this.sendReplyBox("There have been " + Object.size(seenData) + " user names recorded in this database.");
				break;
			default:
				if (!this.runBroadcast()) return;
				let userid = toId(target);
				if (toId(target).length > 18) return this.errorReply("Usernames cannot be over 18 characters.");
				if (userid.length < 1) return this.errorReply("/seen - Please specify a name.");
				let userName = '' + Gold.nameColor(target, false) + '';
				if (Users(target) && Users(target).connected) return this.sendReplyBox(userName + ' is currently online.');
				if (!seenData[userid]) return this.sendReplyBox(userName + ' has never been seen online on this server.');
				let userLastSeen = moment(seenData[userid]).format("MMMM Do YYYY, h:mm:ss A");
				this.sendReplyBox(userName + ' was last seen online on ' + userLastSeen + ' EST. (' + moment(seenData[userid]).fromNow() + ')');
				break;
			}
		} catch (e) {
			return this.sendReply("Something failed: \n" + e.stack);
		}
	},
};
<|endoftext|>