<commit_before>define([
  'angular',
  'lodash',
  'app/core/utils/datemath',
  'moment',
  './directives',
  './queryCtrl',
],
function (angular, _, dateMath) {
  'use strict';

  var module = angular.module('grafana.services');

  module.factory('OpenTSDBDatasource', function($q, backendSrv, templateSrv) {

    function OpenTSDBDatasource(datasource) {
      this.type = 'opentsdb';
      this.url = datasource.url;
      this.name = datasource.name;
      this.supportMetrics = true;
    }

    // Called once per panel (graph)
    OpenTSDBDatasource.prototype.query = function(options) {
      var start = convertToTSDBTime(options.rangeRaw.from, false);
      var end = convertToTSDBTime(options.rangeRaw.to, true);
      var qs = [];

      _.each(options.targets, function(target) {
        if (!target.metric) { return; }
        qs.push(convertTargetToQuery(target, options));
      });

      var queries = _.compact(qs);

      // No valid targets, return the empty result to save a round trip.
      if (_.isEmpty(queries)) {
        var d = $q.defer();
        d.resolve({ data: [] });
        return d.promise;
      }

      var groupByTags = {};
      _.each(queries, function(query) {
        _.each(query.tags, function(val, key) {
          groupByTags[key] = true;
        });
      });

      return this.performTimeSeriesQuery(queries, start, end).then(function(response) {
        var metricToTargetMapping = mapMetricsToTargets(response.data, options);
        var result = _.map(response.data, function(metricData, index) {
          index = metricToTargetMapping[index];
          if (index === -1) {
            index = 0;
          }
          return transformMetricData(metricData, groupByTags, options.targets[index], options);
        });
        return { data: result };
      });
    };

    OpenTSDBDatasource.prototype.performTimeSeriesQuery = function(queries, start, end) {
      var reqBody = {
        start: start,
        queries: queries
      };

      // Relative queries (e.g. last hour) don't include an end time
      if (end) {
        reqBody.end = end;
      }

      var options = {
        method: 'POST',
        url: this.url + '/api/query',
        data: reqBody
      };

      return backendSrv.datasourceRequest(options);
    };

    OpenTSDBDatasource.prototype._performSuggestQuery = function(query, type) {
      return this._get('/api/suggest', {type: type, q: query, max: 1000}).then(function(result) {
        return result.data;
      });
    };

    OpenTSDBDatasource.prototype._performMetricKeyValueLookup = function(metric, key) {
      if(!metric || !key) {
        return $q.when([]);
      }

      var m = metric + "{" + key + "=*}";

      return this._get('/api/search/lookup', {m: m, limit: 3000}).then(function(result) {
        result = result.data.results;
        var tagvs = [];
        _.each(result, function(r) {
          if (tagvs.indexOf(r.tags[key]) === -1) {
            tagvs.push(r.tags[key]);
          }
        });
        return tagvs;
      });
    };

    OpenTSDBDatasource.prototype._performMetricKeyLookup = function(metric) {
      if(!metric) { return $q.when([]); }

      return this._get('/api/search/lookup', {m: metric, limit: 1000}).then(function(result) {
        result = result.data.results;
        var tagks = [];
        _.each(result, function(r) {
          _.each(r.tags, function(tagv, tagk) {
            if(tagks.indexOf(tagk) === -1) {
              tagks.push(tagk);
            }
          });
        });
        return tagks;
      });
    };

    OpenTSDBDatasource.prototype._get = function(relativeUrl, params) {
      return backendSrv.datasourceRequest({
        method: 'GET',
        url: this.url + relativeUrl,
        params: params,
      });
    };

    OpenTSDBDatasource.prototype.metricFindQuery = function(query) {
      if (!query) { return $q.when([]); }

      var interpolated;
      try {
        interpolated = templateSrv.replace(query);
      }
      catch (err) {
        return $q.reject(err);
      }

      var responseTransform = function(result) {
        return _.map(result, function(value) {
          return {text: value};
        });
      };

      var metrics_regex = /metrics\((.*)\)/;
      var tag_names_regex = /tag_names\((.*)\)/;
      var tag_values_regex = /tag_values\((.*),\s?(.*)\)/;
      var tag_names_suggest_regex = /suggest_tagk\((.*)\)/;
      var tag_values_suggest_regex = /suggest_tagv\((.*)\)/;

      var metrics_query = interpolated.match(metrics_regex);
      if (metrics_query) {
        return this._performSuggestQuery(metrics_query[1], 'metrics').then(responseTransform);
      }

      var tag_names_query = interpolated.match(tag_names_regex);
      if (tag_names_query) {
        return this._performMetricKeyLookup(tag_names_query[1]).then(responseTransform);
      }

      var tag_values_query = interpolated.match(tag_values_regex);
      if (tag_values_query) {
        return this._performMetricKeyValueLookup(tag_values_query[1], tag_values_query[2]).then(responseTransform);
      }

      var tag_names_suggest_query = interpolated.match(tag_names_suggest_regex);
      if (tag_names_suggest_query) {
        return this._performSuggestQuery(tag_names_suggest_query[1], 'tagk').then(responseTransform);
      }

      var tag_values_suggest_query = interpolated.match(tag_values_suggest_regex);
      if (tag_values_suggest_query) {
        return this._performSuggestQuery(tag_values_suggest_query[1], 'tagv').then(responseTransform);
      }

      return $q.when([{text: "wtf"}]);
    };

    OpenTSDBDatasource.prototype.testDatasource = function() {
      return this._performSuggestQuery('cpu', 'metrics').then(function () {
        return { status: "success", message: "Data source is working", title: "Success" };
      });
    };

    var aggregatorsPromise = null;
    OpenTSDBDatasource.prototype.getAggregators = function() {
      if (aggregatorsPromise) { return aggregatorsPromise; }

      aggregatorsPromise =  this._get('/api/aggregators').then(function(result) {
        if (result.data && _.isArray(result.data)) {
          return result.data.sort();
        }
        return [];
      });
      return aggregatorsPromise;
    };

    function transformMetricData(md, groupByTags, target, options) {
      var metricLabel = createMetricLabel(md, target, groupByTags, options);
      var dps = [];

      // TSDB returns datapoints has a hash of ts => value.
      // Can't use _.pairs(invert()) because it stringifies keys/values
      _.each(md.dps, function (v, k) {
        dps.push([v, k * 1000]);
      });

      return { target: metricLabel, datapoints: dps };
    }

    function createMetricLabel(md, target, groupByTags, options) {
      if (target.alias) {
        var scopedVars = _.clone(options.scopedVars || {});
        _.each(md.tags, function(value, key) {
          scopedVars['tag_' + key] = {value: value};
        });
        return templateSrv.replace(target.alias, scopedVars);
      }

      var label = md.metric;
      var tagData = [];

      if (!_.isEmpty(md.tags)) {
        _.each(_.pairs(md.tags), function(tag) {
          if (_.has(groupByTags, tag[0])) {
            tagData.push(tag[0] + "=" + tag[1]);
          }
        });
      }

      if (!_.isEmpty(tagData)) {
        label += "{" + tagData.join(", ") + "}";
      }

      return label;
    }

    function convertTargetToQuery(target, options) {
      if (!target.metric || target.hide) {
        return null;
      }

      var query = {
        metric: templateSrv.replace(target.metric, options.scopedVars),
        aggregator: "avg"
      };

      if (target.aggregator) {
        query.aggregator = templateSrv.replace(target.aggregator);
      }

      if (target.shouldComputeRate) {
        query.rate = true;
        query.rateOptions = {
          counter: !!target.isCounter
        };

        if (target.counterMax && target.counterMax.length) {
          query.rateOptions.counterMax = parseInt(target.counterMax);
        }

        if (target.counterResetValue && target.counterResetValue.length) {
          query.rateOptions.resetValue = parseInt(target.counterResetValue);
        }
      }

      if (!target.disableDownsampling) {
        var interval =  templateSrv.replace(target.downsampleInterval || options.interval);

        if (interval.match(/\.[0-9]+s/)) {
          interval = parseFloat(interval)*1000 + "ms";
        }

        query.downsample = interval + "-" + target.downsampleAggregator;
      }

      query.tags = angular.copy(target.tags);
      if(query.tags){
        for(var key in query.tags){
          query.tags[key] = templateSrv.replace(query.tags[key], options.scopedVars);
        }
      }

      return query;
    }

    function mapMetricsToTargets(metrics, options) {
      var interpolatedTagValue;
      return _.map(metrics, function(metricData) {
        return _.findIndex(options.targets, function(target) {
          return target.metric === metricData.metric &&
            _.all(target.tags, function(tagV, tagK) {
            interpolatedTagValue = templateSrv.replace(tagV, options.scopedVars);
            return metricData.tags[tagK] === interpolatedTagValue || interpolatedTagValue === "*";
          });
        });
      });
    }

    function convertToTSDBTime(date, roundUp) {
      if (date === 'now') {
        return null;
      }

      date = dateMath.parse(date, roundUp);
      return date.valueOf();
    }

    return OpenTSDBDatasource;
  });

});
<commit_msg>Cleaned the codebase :D<commit_after>define([
  'angular',
  'lodash',
  'app/core/utils/datemath',
  'moment',
  './directives',
  './queryCtrl',
],
function (angular, _, dateMath) {
  'use strict';

  var module = angular.module('grafana.services');

  module.factory('OpenTSDBDatasource', function($q, backendSrv, templateSrv) {

    function OpenTSDBDatasource(datasource) {
      this.type = 'opentsdb';
      this.url = datasource.url;
      this.name = datasource.name;
      this.supportMetrics = true;
    }

    // Called once per panel (graph)
    OpenTSDBDatasource.prototype.query = function(options) {
      var start = convertToTSDBTime(options.rangeRaw.from, false);
      var end = convertToTSDBTime(options.rangeRaw.to, true);
      var qs = [];

      _.each(options.targets, function(target) {
        if (!target.metric) { return; }
        qs.push(convertTargetToQuery(target, options));
      });

      var queries = _.compact(qs);

      // No valid targets, return the empty result to save a round trip.
      if (_.isEmpty(queries)) {
        var d = $q.defer();
        d.resolve({ data: [] });
        return d.promise;
      }

      var groupByTags = {};
      _.each(queries, function(query) {
        _.each(query.tags, function(val, key) {
          groupByTags[key] = true;
        });
      });

      return this.performTimeSeriesQuery(queries, start, end).then(function(response) {
        var metricToTargetMapping = mapMetricsToTargets(response.data, options);
        var result = _.map(response.data, function(metricData, index) {
          index = metricToTargetMapping[index];
          if (index === -1) {
            index = 0;
          }
          return transformMetricData(metricData, groupByTags, options.targets[index], options);
        });
        return { data: result };
      });
    };

    OpenTSDBDatasource.prototype.performTimeSeriesQuery = function(queries, start, end) {
      var reqBody = {
        start: start,
        queries: queries
      };

      // Relative queries (e.g. last hour) don't include an end time
      if (end) {
        reqBody.end = end;
      }

      var options = {
        method: 'POST',
        url: this.url + '/api/query',
        data: reqBody
      };

      return backendSrv.datasourceRequest(options);
    };

    OpenTSDBDatasource.prototype._performSuggestQuery = function(query, type) {
      return this._get('/api/suggest', {type: type, q: query, max: 1000}).then(function(result) {
        return result.data;
      });
    };

    OpenTSDBDatasource.prototype._performMetricKeyValueLookup = function(metric, key) {
      if(!metric || !key) {
        return $q.when([]);
      }

      var m = metric + "{" + key + "=*}";

      return this._get('/api/search/lookup', {m: m, limit: 3000}).then(function(result) {
        result = result.data.results;
        var tagvs = [];
        _.each(result, function(r) {
          if (tagvs.indexOf(r.tags[key]) === -1) {
            tagvs.push(r.tags[key]);
          }
        });
        return tagvs;
      });
    };

    OpenTSDBDatasource.prototype._performMetricKeyLookup = function(metric) {
      if(!metric) { return $q.when([]); }

      return this._get('/api/search/lookup', {m: metric, limit: 1000}).then(function(result) {
        result = result.data.results;
        var tagks = [];
        _.each(result, function(r) {
          _.each(r.tags, function(tagv, tagk) {
            if(tagks.indexOf(tagk) === -1) {
              tagks.push(tagk);
            }
          });
        });
        return tagks;
      });
    };

    OpenTSDBDatasource.prototype._get = function(relativeUrl, params) {
      return backendSrv.datasourceRequest({
        method: 'GET',
        url: this.url + relativeUrl,
        params: params,
      });
    };

    OpenTSDBDatasource.prototype.metricFindQuery = function(query) {
      if (!query) { return $q.when([]); }

      var interpolated;
      try {
        interpolated = templateSrv.replace(query);
      }
      catch (err) {
        return $q.reject(err);
      }

      var responseTransform = function(result) {
        return _.map(result, function(value) {
          return {text: value};
        });
      };

      var metrics_regex = /metrics\((.*)\)/;
      var tag_names_regex = /tag_names\((.*)\)/;
      var tag_values_regex = /tag_values\((.*),\s?(.*)\)/;
      var tag_names_suggest_regex = /suggest_tagk\((.*)\)/;
      var tag_values_suggest_regex = /suggest_tagv\((.*)\)/;

      var metrics_query = interpolated.match(metrics_regex);
      if (metrics_query) {
        return this._performSuggestQuery(metrics_query[1], 'metrics').then(responseTransform);
      }

      var tag_names_query = interpolated.match(tag_names_regex);
      if (tag_names_query) {
        return this._performMetricKeyLookup(tag_names_query[1]).then(responseTransform);
      }

      var tag_values_query = interpolated.match(tag_values_regex);
      if (tag_values_query) {
        return this._performMetricKeyValueLookup(tag_values_query[1], tag_values_query[2]).then(responseTransform);
      }

      var tag_names_suggest_query = interpolated.match(tag_names_suggest_regex);
      if (tag_names_suggest_query) {
        return this._performSuggestQuery(tag_names_suggest_query[1], 'tagk').then(responseTransform);
      }

      var tag_values_suggest_query = interpolated.match(tag_values_suggest_regex);
      if (tag_values_suggest_query) {
        return this._performSuggestQuery(tag_values_suggest_query[1], 'tagv').then(responseTransform);
      }

      return $q.when([]);
    };

    OpenTSDBDatasource.prototype.testDatasource = function() {
      return this._performSuggestQuery('cpu', 'metrics').then(function () {
        return { status: "success", message: "Data source is working", title: "Success" };
      });
    };

    var aggregatorsPromise = null;
    OpenTSDBDatasource.prototype.getAggregators = function() {
      if (aggregatorsPromise) { return aggregatorsPromise; }

      aggregatorsPromise =  this._get('/api/aggregators').then(function(result) {
        if (result.data && _.isArray(result.data)) {
          return result.data.sort();
        }
        return [];
      });
      return aggregatorsPromise;
    };

    function transformMetricData(md, groupByTags, target, options) {
      var metricLabel = createMetricLabel(md, target, groupByTags, options);
      var dps = [];

      // TSDB returns datapoints has a hash of ts => value.
      // Can't use _.pairs(invert()) because it stringifies keys/values
      _.each(md.dps, function (v, k) {
        dps.push([v, k * 1000]);
      });

      return { target: metricLabel, datapoints: dps };
    }

    function createMetricLabel(md, target, groupByTags, options) {
      if (target.alias) {
        var scopedVars = _.clone(options.scopedVars || {});
        _.each(md.tags, function(value, key) {
          scopedVars['tag_' + key] = {value: value};
        });
        return templateSrv.replace(target.alias, scopedVars);
      }

      var label = md.metric;
      var tagData = [];

      if (!_.isEmpty(md.tags)) {
        _.each(_.pairs(md.tags), function(tag) {
          if (_.has(groupByTags, tag[0])) {
            tagData.push(tag[0] + "=" + tag[1]);
          }
        });
      }

      if (!_.isEmpty(tagData)) {
        label += "{" + tagData.join(", ") + "}";
      }

      return label;
    }

    function convertTargetToQuery(target, options) {
      if (!target.metric || target.hide) {
        return null;
      }

      var query = {
        metric: templateSrv.replace(target.metric, options.scopedVars),
        aggregator: "avg"
      };

      if (target.aggregator) {
        query.aggregator = templateSrv.replace(target.aggregator);
      }

      if (target.shouldComputeRate) {
        query.rate = true;
        query.rateOptions = {
          counter: !!target.isCounter
        };

        if (target.counterMax && target.counterMax.length) {
          query.rateOptions.counterMax = parseInt(target.counterMax);
        }

        if (target.counterResetValue && target.counterResetValue.length) {
          query.rateOptions.resetValue = parseInt(target.counterResetValue);
        }
      }

      if (!target.disableDownsampling) {
        var interval =  templateSrv.replace(target.downsampleInterval || options.interval);

        if (interval.match(/\.[0-9]+s/)) {
          interval = parseFloat(interval)*1000 + "ms";
        }

        query.downsample = interval + "-" + target.downsampleAggregator;
      }

      query.tags = angular.copy(target.tags);
      if(query.tags){
        for(var key in query.tags){
          query.tags[key] = templateSrv.replace(query.tags[key], options.scopedVars);
        }
      }

      return query;
    }

    function mapMetricsToTargets(metrics, options) {
      var interpolatedTagValue;
      return _.map(metrics, function(metricData) {
        return _.findIndex(options.targets, function(target) {
          return target.metric === metricData.metric &&
            _.all(target.tags, function(tagV, tagK) {
            interpolatedTagValue = templateSrv.replace(tagV, options.scopedVars);
            return metricData.tags[tagK] === interpolatedTagValue || interpolatedTagValue === "*";
          });
        });
      });
    }

    function convertToTSDBTime(date, roundUp) {
      if (date === 'now') {
        return null;
      }

      date = dateMath.parse(date, roundUp);
      return date.valueOf();
    }

    return OpenTSDBDatasource;
  });

});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
/<commit_msg>Correcting style<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line<|endoftext|>


<commit_before>const mongoose = require('mongoose')
const Photo = require('mongoose').model('Photo')
const Album = require('mongoose').model('Album')
const Post = mongoose.model('Post')
const path = require('path')
const config = require('../config/config')['development']  // TODO: Set environment variable!
const multer = require('multer')

let publicDirPath = path.join(config.rootFolder, 'public')
let readFiles = multer({ dest: path.join(publicDirPath, 'uploads') }).array('uploadedPhotos')

module.exports = {
  allGet: (req, res) => {
    if (!req.user) {
      let returnUrl = '/user/uploadPhotos'
      req.session.returnUrl = returnUrl

      res.redirect('/user/login')
      return
    }

    res.render('user/uploadPhotos')
  },

  // function that handles photo uploads on the newsfeed
  uploadPhotosPost: (req, res) => {
    let albumName = 'newsfeed-photos-' + req.user._id
    // Try to find the user's album to add the picture to, otherwise create a new one
    Album.findOrCreateAlbum(albumName, req.user._id)  // custom function in Album.js
      .then(album => {
        readFiles(req, res, function () {  // middleware to parse the uploaded files to req.files
          // logic for the post
          let newPostArg = req.body
          let postPublicity = newPostArg.photocheck.toString() === 'publicvisible'
          let newPost = new Post({
            author: req.user._id,
            category: req.user.category,
            content: newPostArg.descriptionPostPhotos,
            public: postPublicity
          })
          if (newPost.content.length < 1) {
            // ERROR - Content is too short!
            // TODO: Attach an error message to req.session.errorMsg which will be displayed in the HTML
            req.session.failedPost = newPost  // attach the post content to be displayed on the redirect
            res.redirect('/')
            return
          }

          Post.create(newPost).then(post => {
            // Logic for the upload of photos
            // the newPostArgs hold the description for each photo, the key being their number. We start from 1 and for each photo increment
            let counter = 1

            // create a photo object for each uploaded photo
            req.files.forEach(function (photo) {
              let photoUp = new Photo({
                fieldname: photo.fieldname,
                originalname: photo.originalname,
                encoding: photo.encoding,
                mimetype: photo.mimetype,
                destination: photo.destination,
                filename: photo.filename,
                path: photo.path,
                size: photo.size,
                author: newPostArg.author,
                description: newPostArg[counter.toString()],
                album: album._id,
                post: post._id,
                classCss: album.classForCss,
                public: postPublicity
              })
              counter += 1

              Photo.create(photoUp).then(photo => {
                photo.prepareUploadSinglePhotos(photoUp.album)
                photo.prepareUploadInPost(photoUp.post)
              }
              )
            })
          })

          res.redirect('/')
        })
      })
  }
}
<commit_msg>Fixed a bug where you were not able to upload photos because of invalid author<commit_after>const mongoose = require('mongoose')
const Photo = mongoose.model('Photo')
const Album = mongoose.model('Album')
const Post = mongoose.model('Post')
const path = require('path')
const config = require('../config/config')['development']  // TODO: Set environment variable!
const multer = require('multer')

let publicDirPath = path.join(config.rootFolder, 'public')
let readFiles = multer({ dest: path.join(publicDirPath, 'uploads') }).array('uploadedPhotos')

module.exports = {
  allGet: (req, res) => {
    if (!req.user) {
      let returnUrl = '/user/uploadPhotos'
      req.session.returnUrl = returnUrl

      res.redirect('/user/login')
      return
    }

    res.render('user/uploadPhotos')
  },

  // function that handles photo uploads on the newsfeed
  uploadPhotosPost: (req, res) => {
    let albumName = 'newsfeed-photos-' + req.user._id
    // Try to find the user's album to add the picture to, otherwise create a new one
    Album.findOrCreateAlbum(albumName, req.user._id)  // custom function in Album.js
      .then(album => {
        readFiles(req, res, function () {  // middleware to parse the uploaded files to req.files
          // logic for the post
          let newPostArg = req.body
          let postPublicity = newPostArg.photocheck.toString() === 'publicvisible'
          let newPost = new Post({
            author: req.user._id,
            category: req.user.category,
            content: newPostArg.descriptionPostPhotos,
            public: postPublicity
          })
          if (newPost.content.length < 1) {
            // ERROR - Content is too short!
            // TODO: Attach an error message to req.session.errorMsg which will be displayed in the HTML
            req.session.failedPost = newPost  // attach the post content to be displayed on the redirect
            res.redirect('/')
            return
          }

          Post.create(newPost).then(post => {
            // Logic for the upload of photos
            // the newPostArgs hold the description for each photo, the key being their number. We start from 1 and for each photo increment
            let counter = 1

            // create a photo object for each uploaded photo
            req.files.forEach(function (photo) {
              let photoUp = new Photo({
                fieldname: photo.fieldname,
                originalname: photo.originalname,
                encoding: photo.encoding,
                mimetype: photo.mimetype,
                destination: photo.destination,
                filename: photo.filename,
                path: photo.path,
                size: photo.size,
                author: post.author,
                description: newPostArg[counter.toString()],
                album: album._id,
                post: post._id,
                classCss: album.classForCss,
                public: postPublicity
              })
              counter += 1

              Photo.create(photoUp).then(photo => {
                photo.prepareUploadSinglePhotos(photoUp.album)
                photo.prepareUploadInPost(photoUp.post)
              }
              )
            })
          })

          res.redirect('/')
        })
      })
  }
}
<|endoftext|>


<commit_before>export const getDefaultUserFields = () => ({
	name: 1,
	username: 1,
	emails: 1,
	status: 1,
	statusDefault: 1,
	statusText: 1,
	statusConnection: 1,
	bio: 1,
	avatarOrigin: 1,
	utcOffset: 1,
	language: 1,
	settings: 1,
	enableAutoAway: 1,
	idleTimeLimit: 1,
	roles: 1,
	active: 1,
	defaultRoom: 1,
	customFields: 1,
	requirePasswordChange: 1,
	requirePasswordChangeReason: 1,
	'services.github': 1,
	'services.gitlab': 1,
	'services.tokenpass': 1,
	'services.blockstack': 1,
	'services.password.bcrypt': 1,
	'services.totp.enabled': 1,
	'services.email2fa.enabled': 1,
	statusLivechat: 1,
	banners: 1,
	'oauth.authorizedClients': 1,
	_updatedAt: 1,
});
<commit_msg>[FIX] Avatar ETag missing from User (#18109)<commit_after>export const getDefaultUserFields = () => ({
	name: 1,
	username: 1,
	emails: 1,
	status: 1,
	statusDefault: 1,
	statusText: 1,
	statusConnection: 1,
	bio: 1,
	avatarOrigin: 1,
	utcOffset: 1,
	language: 1,
	settings: 1,
	enableAutoAway: 1,
	idleTimeLimit: 1,
	roles: 1,
	active: 1,
	defaultRoom: 1,
	customFields: 1,
	requirePasswordChange: 1,
	requirePasswordChangeReason: 1,
	'services.github': 1,
	'services.gitlab': 1,
	'services.tokenpass': 1,
	'services.blockstack': 1,
	'services.password.bcrypt': 1,
	'services.totp.enabled': 1,
	'services.email2fa.enabled': 1,
	statusLivechat: 1,
	banners: 1,
	'oauth.authorizedClients': 1,
	_updatedAt: 1,
	avatarETag: 1,
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'

export default () => (

    저작권 © 2017 niceb5y 모든 권리 보유.

)
<commit_msg>update footer<commit_after>import React, { Component } from 'react'

export default () => (

    저작권 © 2017-2018 niceb5y 모든 권리 보유.

)
<|endoftext|>


<commit_before>'use strict';

// Required args: id, column, loopend, loopstart
function chess_check_column(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][i][args['column']].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, column, dx, dy, loopstart, loopend, row
function chess_check_diagonal(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    let x = args['column'];
    let y = args['row'];

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        x += args['dx'];
        y += args['dy'];

        if(chess_games[args['id']]['board'][y][x].length === 1){
            return true;
        }
    }

    return false;
}

// Required args: id, loopend, loopstart, row
function chess_check_row(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][args['row']][i].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_move(args){
    if(!chess_games[args['id']]){
        return false;
    }

    const valid_move = chess_validate(args);
    if(valid_move){
        const piece_x = args['piece-x'] - 1;
        const piece_y = args['piece-y'] - 1;
        const piece = chess_games[args['id']]['board'][piece_y][piece_x];

        chess_games[args['id']]['board'][piece_y][piece_x] = '';
        chess_games[args['id']]['board'][args['target-y'] - 1][args['target-x'] - 1] = piece;
        chess_games[args['id']]['player'] = 1 - chess_games[args['id']]['player'];
    }
    return valid_move;
}

// Required args: id
function chess_new(args){
    chess_games[args['id']] = {
      'board': [
        [chess_pieces[1][3], chess_pieces[1][1], chess_pieces[1][2], chess_pieces[1][4], chess_pieces[1][5], chess_pieces[1][2], chess_pieces[1][1], chess_pieces[1][3],],
        [chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0],],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        [chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0],],
        [chess_pieces[0][3], chess_pieces[0][1], chess_pieces[0][2], chess_pieces[0][4], chess_pieces[0][5], chess_pieces[0][2], chess_pieces[0][1], chess_pieces[0][3],],
      ],
      'player': 0,
    };
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_validate(args){
    const piece_x = args['piece-x'] - 1;
    const piece_y = args['piece-y'] - 1;
    const target_x = args['target-x'] - 1;
    const target_y = args['target-y'] - 1;

    if(!chess_games[args['id']]
      || piece_x < 0 || piece_x > 7
      || piece_y < 0 || piece_y > 7
      || target_x < 0 || target_x > 7
      || target_y < 0 || target_y > 7){
        return false;
    }

    const player = chess_games[args['id']]['player'];
    const piece = chess_games[args['id']]['board'][piece_y][piece_x];
    if(piece.length === 0 || !chess_pieces[player].includes(piece)){
        return false;
    }

    const target_piece = chess_games[args['id']]['board'][target_y][target_x];
    if(chess_pieces[player].includes(target_piece)){
        return false;
    }
    const movement_x = Math.abs(piece_x - target_x);
    const movement_y = Math.abs(piece_y - target_y);

    switch(piece){
        // Pawn
        case chess_pieces[player][0]: {
            const direction = player === 0 ? -1 : 1;

            if(target_x !== piece_x){
                if(movement_x !== 1
                  || target_y - piece_y !== direction
                  || !chess_pieces[1 - player].includes(target_piece)){
                    return false;
                }

            }else if(target_piece.length === 0){
                if(piece_y === 6 - (player * 5)){
                    if(target_y !== piece_y + direction
                      && target_y !== piece_y + direction * 2){
                        return false;
                    }

                }else if(target_y !== piece_y + direction){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // Knight
        case chess_pieces[player][1]: {
            if(movement_x < 1 || movement_x > 2 || movement_y < 1 || movement_y > 2){
                return false;

            }else if((movement_x === 1 && movement_y !== 2)
              || (movement_x === 2 && movement_y !== 1)){
                return false;
            }

            break;
        }

        // Bishop
        case chess_pieces[player][2]: {
            if(movement_x === movement_y){
                if(movement_y > 1 && chess_check_diagonal({
                    'column': piece_x,
                    'dx': piece_x < target_x
                      ? 1
                      : -1,
                    'dy': piece_y < target_y
                      ? 1
                      : -1,
                    'id': args['id'],
                    'loopend': target_x,
                    'loopstart': piece_x,
                    'row': piece_y,
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // Rook
        case chess_pieces[player][3]: {
            if(target_x === piece_x){
                if(movement_y > 1 && chess_check_column({
                    'column': piece_x,
                    'id': args['id'],
                    'loopend': target_y,
                    'loopstart': piece_y,
                  })){
                    return false;
                }

            }else if(target_y === piece_y){
                if(movement_x > 1 && chess_check_row({
                    'id': args['id'],
                    'loopend': target_x,
                    'loopstart': piece_x,
                    'row': piece_y,
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // Queen
        case chess_pieces[player][4]: {
            if(movement_x === movement_y){
                if(movement_y > 1 && chess_check_diagonal({
                    'column': piece_x,
                    'dx': piece_x < target_x
                      ? 1
                      : -1,
                    'dy': piece_y < target_y
                      ? 1
                      : -1,
                    'id': args['id'],
                    'loopend': target_x,
                    'loopstart': piece_x,
                    'row': piece_y,
                  })){
                    return false;
                }

            }else if(target_x === piece_x){
                if(movement_y > 1 && chess_check_column({
                    'column': piece_x,
                    'id': args['id'],
                    'loopend': target_y,
                    'loopstart': piece_y,
                  })){
                    return false;
                }

            }else if(target_y === piece_y){
                if(movement_x > 1 && chess_check_row({
                    'id': args['id'],
                    'loopend': target_x,
                    'loopstart': piece_x,
                    'row': piece_y,
                  })){
                    return false;
                }

            }else{
                return false;
            }

            break;
        }

        // King
        case chess_pieces[player][5]: {
            if(movement_x > 1 || movement_y > 1){
                return false;
            }

            break;
        }

        default:
            return false;
    }
    return true;
}

globalThis.chess_games = {};
globalThis.chess_pieces = [
  ['♙', '♘', '♗', '♖', '♕', '♔'],
  ['♟', '♞', '♝', '♜', '♛', '♚'],
];
<commit_msg>added en-passant to chess_validate() return<commit_after>'use strict';

// Required args: id, column, loopend, loopstart
function chess_check_column(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][i][args['column']].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, column, dx, dy, loopstart, loopend, row
function chess_check_diagonal(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    let x = args['column'];
    let y = args['row'];

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        x += args['dx'];
        y += args['dy'];

        if(chess_games[args['id']]['board'][y][x].length === 1){
            return true;
        }
    }

    return false;
}

// Required args: id, loopend, loopstart, row
function chess_check_row(args){
    if(args['loopstart'] > args['loopend']){
        const temp = args['loopstart'];
        args['loopstart'] = args['loopend'];
        args['loopend'] = temp;
    }

    for(let i = args['loopstart'] + 1; i < args['loopend']; i++){
        if(chess_games[args['id']]['board'][args['row']][i].length === 1){
            return true;
        }
    }
    return false;
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_move(args){
    if(!chess_games[args['id']]){
        return false;
    }

    const validation = chess_validate(args);
    if(validation['valid']){
        const piece_x = args['piece-x'] - 1;
        const piece_y = args['piece-y'] - 1;
        const piece = chess_games[args['id']]['board'][piece_y][piece_x];

        chess_games[args['id']]['board'][piece_y][piece_x] = '';
        chess_games[args['id']]['en-passant'] = validation['en-passant'];
        chess_games[args['id']]['board'][args['target-y'] - 1][args['target-x'] - 1] = piece;
        chess_games[args['id']]['player'] = 1 - chess_games[args['id']]['player'];
    }
    return validation['valid'];
}

// Required args: id
function chess_new(args){
    chess_games[args['id']] = {
      'board': [
        [chess_pieces[1][3], chess_pieces[1][1], chess_pieces[1][2], chess_pieces[1][4], chess_pieces[1][5], chess_pieces[1][2], chess_pieces[1][1], chess_pieces[1][3],],
        [chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0], chess_pieces[1][0],],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        ['', '', '', '', '', '', '', '',],
        [chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0], chess_pieces[0][0],],
        [chess_pieces[0][3], chess_pieces[0][1], chess_pieces[0][2], chess_pieces[0][4], chess_pieces[0][5], chess_pieces[0][2], chess_pieces[0][1], chess_pieces[0][3],],
      ],
      'en-passant': -1,
      'player': 0,
    };
}

// Required args: id, piece-x, piece-y, target-x, target-y
function chess_validate(args){
    let en_passant = -1;
    let valid_move = true;
    const piece_x = args['piece-x'] - 1;
    const piece_y = args['piece-y'] - 1;
    const target_x = args['target-x'] - 1;
    const target_y = args['target-y'] - 1;

    if(!chess_games[args['id']]
      || piece_x < 0 || piece_x > 7
      || piece_y < 0 || piece_y > 7
      || target_x < 0 || target_x > 7
      || target_y < 0 || target_y > 7){
        valid_move = false;

    }else{
        const player = chess_games[args['id']]['player'];
        const piece = chess_games[args['id']]['board'][piece_y][piece_x];
        if(piece.length === 0 || !chess_pieces[player].includes(piece)){
            valid_move = false;

        }else{
            const target_piece = chess_games[args['id']]['board'][target_y][target_x];
            if(chess_pieces[player].includes(target_piece)){
                valid_move = false;

            }else{
                const movement_x = Math.abs(piece_x - target_x);
                const movement_y = Math.abs(piece_y - target_y);
                switch(piece){
                    // Pawn
                    case chess_pieces[player][0]: {
                        const direction = player === 0 ? -1 : 1;

                        if(target_x !== piece_x){
                            if(movement_x !== 1
                              || target_y - piece_y !== direction
                              || !chess_pieces[1 - player].includes(target_piece)){
                                valid_move = false;
                            }

                        }else if(target_piece.length === 0){
                            if(piece_y === 6 - (player * 5)){
                                if(target_y !== piece_y + direction
                                  && target_y !== piece_y + direction * 2){
                                    valid_move = false;

                                }else if(target_y === piece_y + direction * 2){
                                    en_passant = piece_x + 1;
                                }

                            }else if(target_y !== piece_y + direction){
                                valid_move = false;
                            }

                        }else{
                            valid_move = false;
                        }

                        break;
                    }

                    // Knight
                    case chess_pieces[player][1]: {
                        if(movement_x < 1 || movement_x > 2 || movement_y < 1 || movement_y > 2){
                            valid_move = false;

                        }else if((movement_x === 1 && movement_y !== 2)
                          || (movement_x === 2 && movement_y !== 1)){
                            valid_move = false;
                        }

                        break;
                    }

                    // Bishop
                    case chess_pieces[player][2]: {
                        if(movement_x === movement_y){
                            if(movement_y > 1 && chess_check_diagonal({
                                'column': piece_x,
                                'dx': piece_x < target_x
                                  ? 1
                                  : -1,
                                'dy': piece_y < target_y
                                  ? 1
                                  : -1,
                                'id': args['id'],
                                'loopend': target_x,
                                'loopstart': piece_x,
                                'row': piece_y,
                              })){
                                valid_move = false;
                            }

                        }else{
                            valid_move = false;
                        }

                        break;
                    }

                    // Rook
                    case chess_pieces[player][3]: {
                        if(target_x === piece_x){
                            if(movement_y > 1 && chess_check_column({
                                'column': piece_x,
                                'id': args['id'],
                                'loopend': target_y,
                                'loopstart': piece_y,
                              })){
                                valid_move = false;
                            }

                        }else if(target_y === piece_y){
                            if(movement_x > 1 && chess_check_row({
                                'id': args['id'],
                                'loopend': target_x,
                                'loopstart': piece_x,
                                'row': piece_y,
                              })){
                                valid_move = false;
                            }

                        }else{
                            valid_move = false;
                        }

                        break;
                    }

                    // Queen
                    case chess_pieces[player][4]: {
                        if(movement_x === movement_y){
                            if(movement_y > 1 && chess_check_diagonal({
                                'column': piece_x,
                                'dx': piece_x < target_x
                                  ? 1
                                  : -1,
                                'dy': piece_y < target_y
                                  ? 1
                                  : -1,
                                'id': args['id'],
                                'loopend': target_x,
                                'loopstart': piece_x,
                                'row': piece_y,
                              })){
                                valid_move = false;
                            }

                        }else if(target_x === piece_x){
                            if(movement_y > 1 && chess_check_column({
                                'column': piece_x,
                                'id': args['id'],
                                'loopend': target_y,
                                'loopstart': piece_y,
                              })){
                                valid_move = false;
                            }

                        }else if(target_y === piece_y){
                            if(movement_x > 1 && chess_check_row({
                                'id': args['id'],
                                'loopend': target_x,
                                'loopstart': piece_x,
                                'row': piece_y,
                              })){
                                valid_move = false;
                            }

                        }else{
                            valid_move = false;
                        }

                        break;
                    }

                    // King
                    case chess_pieces[player][5]: {
                        if(movement_x > 1 || movement_y > 1){
                            valid_move = false;
                        }

                        break;
                    }

                    default:
                        valid_move = false;
                }
            }
        }
    }

    return {
      'en-passant': en_passant,
      'valid': valid_move,
    };
}

globalThis.chess_games = {};
globalThis.chess_pieces = [
  ['♙', '♘', '♗', '♖', '♕', '♔'],
  ['♟', '♞', '♝', '♜', '♛', '♚'],
];
<|endoftext|>


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

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		event.preventDefault();
		var request = $(this).value;
		//var Classroom = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classroom);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				console.log("YAAASSS!!!!");
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<commit_msg>move Parse.initialize to top of script.js<commit_after>$(document).ready(function(){

	Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		event.preventDefault();
		var request = $(this).value;
		//var Classroom = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classroom);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				console.log("YAAASSS!!!!");
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		//Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<|endoftext|>


<commit_before>var gulp = require('gulp');
var minifyHTML = require('gulp-minify-html');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var changed = require('gulp-changed');
var imagemin = require('gulp-imagemin');
var autoprefix = require('gulp-autoprefixer');
var del = require('del');
var concat = require('gulp-concat');
var refresh = require('gulp-livereload');
var modRewrite = require('connect-modrewrite');
var RevAll = require('gulp-rev-all');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var gulpIf = require('gulp-if');
var gutil = require('gulp-util');
var plumber = require('gulp-plumber');

var paths = {
    dist: 'dist',
    jshint: [
        'app/scripts/**/*.js',
        'app/theme/**/*.js'
    ],
    html: 'app/**/*.html',
    misc: 'app/*.{htaccess,ico,xml}',
    scripts: [
        'app/scripts/config.js',
        'app/scripts/main.js',
        'app/scripts/**/init.js',
        'app/scripts/**/*.js'
    ],
    theme: {
        dist: 'dist/theme',
        styles: 'app/theme/styles/*.scss',
        // images, videos, fonts
        media: 'app/theme/**/*.{png,gif,jpg,jpeg,ico,svg,mp4,ogv,webm,pdf,eot,ttf,woff}',
        scripts: [
            'app/theme/lib/**/*.js',
            'app/theme/**/*.js'
        ]
    },
    lib: {
        dist: 'dist/lib',
        scripts: [
            'app/lib/jquery.min.js',
            'app/lib/angular.min.js',
            // NOTES:
            // no folder glob, or it would clobber .ie
            // also we are only moving minified files, so feel free to toss unminified reference files in the lib dir
            'app/lib/*.min.js'
        ],
        ie: 'app/lib/ie/*.min.js'
    }
};

var handleError = function(err) {
    gutil.log(gutil.colors.red('# Error in ' + err.plugin));
    if (err.fileName) {
        gutil.log('File: %s:%s', err.fileName, err.lineNumber);
    }
    gutil.log('Error Message: %s', err.message);
    gutil.beep();
}

var host = {
    port: '8080',
    lrPort: '35729'
};

var isProduction = false;

// Empties folders to start fresh
gulp.task('clean', function (cb) {
    return del(['dist/*', '!dist/media'], cb);
});

gulp.task('jshint', function () {
    return gulp.src(paths.jshint)
        .pipe(jshint())
        .pipe(jshint.reporter(require('jshint-stylish')));
});

gulp.task('html', function () {
    return gulp.src(paths.html)
        .pipe(changed(paths.dist))
        .pipe(minifyHTML({
            collapseWhitespace: true,
            collapseBooleanAttributes: true,
            removeCommentsFromCDATA: true,
            removeOptionalTags: true,
            conditionals: true,
            quotes: true,
            empty: true
        }))
        .pipe(gulp.dest(paths.dist));
});

gulp.task('robots-dev', function () {
    var robotPath = 'app/robots.dev.txt';
    gulp.src(robotPath)
        .pipe(rename('robots.txt'))
        .pipe(gulp.dest(paths.dist));

    return gulp.src(paths.misc)
        .pipe(gulp.dest(paths.dist));

});

gulp.task('robots-prod', function () {
    var robotPath = 'app/robots.prod.txt';
    gulp.src(robotPath)
        .pipe(rename('robots.txt'))
        .pipe(gulp.dest(paths.dist));

    return gulp.src(paths.misc)
        .pipe(gulp.dest(paths.dist));

});

gulp.task('scripts', function () {
    return gulp.src(paths.scripts)
        .pipe(sourcemaps.init())
        .pipe(plumber(handleError))
        .pipe(uglify({
            mangle: false
        }))
        .pipe(plumber.stop())
        .pipe(concat('main.js'))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(paths.dist + '/scripts'))
        .pipe(refresh());
});

gulp.task('theme.styles', function() {
    return gulp.src(paths.theme.styles)
        .pipe(sourcemaps.init())
        .pipe(plumber(handleError))
        .pipe(sass.sync({
            outputStyle: 'compressed',
            precision: 8,
        }))
        .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(plumber.stop())
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(paths.theme.dist + '/styles'))
        .pipe(refresh());
});

gulp.task('theme.scripts', function () {
    return gulp.src(paths.theme.scripts)
        .pipe(sourcemaps.init())
        .pipe(plumber(handleError))
        .pipe(uglify({
            mangle: false
        }))
        .pipe(plumber.stop())
        .pipe(concat('main.js'))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(paths.theme.dist))
        .pipe(refresh());
});

gulp.task('theme.media', function () {
    return gulp.src(paths.theme.media)
        .pipe(changed(paths.theme.dist))
        .pipe(gulpIf(isProduction, imagemin()))
        .pipe(gulp.dest(paths.theme.dist));
});

gulp.task('lib.scripts', function () {
    return gulp.src(paths.lib.scripts)
        .pipe(concat('lib.js'))
        .pipe(gulp.dest(paths.lib.dist));
});

// IE libs can stick together, but need to be separate from other libs
gulp.task('lib.ie', function() {
    return gulp.src(paths.lib.ie)
        .pipe(concat('ie-libs.js'))
        .pipe(gulp.dest(paths.lib.dist));
});

gulp.task('watch',function(){
    refresh.listen({ basePath: paths.dist });

    gulp.start('livereload');

    gulp.watch(["app/**/*.html"],['html']);
    gulp.watch(["app/**/*.scss","app/**/*.css"],['theme.styles']);
    gulp.watch(["app/scripts/**/*.js"],['scripts']);
    gulp.watch(["app/theme/**/*.js"],['theme.scripts']);
});

gulp.task('livereload', function(){
    var path = require('path');
    var express = require('express');
    var app = express();
    var staticFolder = path.join(__dirname, 'dist');

    app.use(modRewrite([
        '!\\. /index.html [L]'
    ]))
        .use(express.static(staticFolder));

    app.listen( host.port, function() {
        console.log('server started: http://localhost:' + host.port);
        return gulp;
    });
});

gulp.task('revision', function(){
    if(isProduction) {
        var revAll = new RevAll({
            dontUpdateReference: [/^((?!.js|.css).)*$/g],
            dontRenameFile: [/^((?!.js|.css).)*$/g]
        });

        gulp.src('dist/**')
            .pipe(revAll.revision())
            .pipe(gulp.dest('dist'));
    }
});

gulp.task('lib', ['lib.ie', 'lib.scripts']);
gulp.task('theme', [
    'theme.styles',
    'theme.scripts',
    'theme.media'
]);

// For production
gulp.task('build-prod', function(){
    isProduction=true;
    runSequence('clean', [
        'html',
        'robots-prod',
        'scripts',
        'theme',
        'lib'
    ], 'revision');
});

// For development
gulp.task('build', function(){
    // note: revision has a short circuit for dev
    runSequence('clean', [
        'html',
        'robots-dev',
        'scripts',
        'theme',
        'lib'
    ], 'revision');
});

// For development
gulp.task('serve', ['default']);
gulp.task('default', ['build'], function(){
    isProduction = false;
    gulp.start('watch');
});
<commit_msg>simplify the robots task<commit_after>var gulp = require('gulp');
var minifyHTML = require('gulp-minify-html');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var changed = require('gulp-changed');
var imagemin = require('gulp-imagemin');
var autoprefix = require('gulp-autoprefixer');
var del = require('del');
var concat = require('gulp-concat');
var refresh = require('gulp-livereload');
var modRewrite = require('connect-modrewrite');
var RevAll = require('gulp-rev-all');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var gulpIf = require('gulp-if');
var gutil = require('gulp-util');
var plumber = require('gulp-plumber');

var paths = {
    dist: 'dist',
    jshint: [
        'app/scripts/**/*.js',
        'app/theme/**/*.js'
    ],
    html: 'app/**/*.html',
    misc: 'app/*.{htaccess,ico,xml}',
    scripts: [
        'app/scripts/config.js',
        'app/scripts/main.js',
        'app/scripts/**/init.js',
        'app/scripts/**/*.js'
    ],
    theme: {
        dist: 'dist/theme',
        styles: 'app/theme/styles/*.scss',
        // images, videos, fonts
        media: 'app/theme/**/*.{png,gif,jpg,jpeg,ico,svg,mp4,ogv,webm,pdf,eot,ttf,woff}',
        scripts: [
            'app/theme/lib/**/*.js',
            'app/theme/**/*.js'
        ]
    },
    lib: {
        dist: 'dist/lib',
        scripts: [
            'app/lib/jquery.min.js',
            'app/lib/angular.min.js',
            // NOTES:
            // no folder glob, or it would clobber .ie
            // also we are only moving minified files, so feel free to toss unminified reference files in the lib dir
            'app/lib/*.min.js'
        ],
        ie: 'app/lib/ie/*.min.js'
    }
};

var handleError = function(err) {
    gutil.log(gutil.colors.red('# Error in ' + err.plugin));
    if (err.fileName) {
        gutil.log('File: %s:%s', err.fileName, err.lineNumber);
    }
    gutil.log('Error Message: %s', err.message);
    gutil.beep();
}

var host = {
    port: '8080',
    lrPort: '35729'
};

var isProduction = false;

// Empties folders to start fresh
gulp.task('clean', function (cb) {
    return del(['dist/*', '!dist/media'], cb);
});

gulp.task('jshint', function () {
    return gulp.src(paths.jshint)
        .pipe(jshint())
        .pipe(jshint.reporter(require('jshint-stylish')));
});

gulp.task('html', function () {
    return gulp.src(paths.html)
        .pipe(changed(paths.dist))
        .pipe(minifyHTML({
            collapseWhitespace: true,
            collapseBooleanAttributes: true,
            removeCommentsFromCDATA: true,
            removeOptionalTags: true,
            conditionals: true,
            quotes: true,
            empty: true
        }))
        .pipe(gulp.dest(paths.dist));
});

gulp.task('robots', function () {
    var robotPath = isProduction ? 'app/robots.prod.txt' : 'app/robots.dev.txt';
    gulp.src(robotPath)
        .pipe(rename('robots.txt'))
        .pipe(gulp.dest(paths.dist));

    return gulp.src(paths.misc)
        .pipe(gulp.dest(paths.dist));

});

gulp.task('scripts', function () {
    return gulp.src(paths.scripts)
        .pipe(sourcemaps.init())
        .pipe(plumber(handleError))
        .pipe(uglify({
            mangle: false
        }))
        .pipe(plumber.stop())
        .pipe(concat('main.js'))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(paths.dist + '/scripts'))
        .pipe(refresh());
});

gulp.task('theme.styles', function() {
    return gulp.src(paths.theme.styles)
        .pipe(sourcemaps.init())
        .pipe(plumber(handleError))
        .pipe(sass.sync({
            outputStyle: 'compressed',
            precision: 8,
        }))
        .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(plumber.stop())
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(paths.theme.dist + '/styles'))
        .pipe(refresh());
});

gulp.task('theme.scripts', function () {
    return gulp.src(paths.theme.scripts)
        .pipe(sourcemaps.init())
        .pipe(plumber(handleError))
        .pipe(uglify({
            mangle: false
        }))
        .pipe(plumber.stop())
        .pipe(concat('main.js'))
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest(paths.theme.dist))
        .pipe(refresh());
});

gulp.task('theme.media', function () {
    return gulp.src(paths.theme.media)
        .pipe(changed(paths.theme.dist))
        .pipe(gulpIf(isProduction, imagemin()))
        .pipe(gulp.dest(paths.theme.dist));
});

gulp.task('lib.scripts', function () {
    return gulp.src(paths.lib.scripts)
        .pipe(concat('lib.js'))
        .pipe(gulp.dest(paths.lib.dist));
});

// IE libs can stick together, but need to be separate from other libs
gulp.task('lib.ie', function() {
    return gulp.src(paths.lib.ie)
        .pipe(concat('ie-libs.js'))
        .pipe(gulp.dest(paths.lib.dist));
});

gulp.task('watch',function(){
    refresh.listen({ basePath: paths.dist });

    gulp.start('livereload');

    gulp.watch(["app/**/*.html"],['html']);
    gulp.watch(["app/**/*.scss","app/**/*.css"],['theme.styles']);
    gulp.watch(["app/scripts/**/*.js"],['scripts']);
    gulp.watch(["app/theme/**/*.js"],['theme.scripts']);
});

gulp.task('livereload', function(){
    var path = require('path');
    var express = require('express');
    var app = express();
    var staticFolder = path.join(__dirname, 'dist');

    app.use(modRewrite([
        '!\\. /index.html [L]'
    ]))
        .use(express.static(staticFolder));

    app.listen( host.port, function() {
        console.log('server started: http://localhost:' + host.port);
        return gulp;
    });
});

gulp.task('revision', function(){
    if(isProduction) {
        var revAll = new RevAll({
            dontUpdateReference: [/^((?!.js|.css).)*$/g],
            dontRenameFile: [/^((?!.js|.css).)*$/g]
        });

        gulp.src('dist/**')
            .pipe(revAll.revision())
            .pipe(gulp.dest('dist'));
    }
});

gulp.task('lib', ['lib.ie', 'lib.scripts']);
gulp.task('theme', [
    'theme.styles',
    'theme.scripts',
    'theme.media'
]);

// For production
gulp.task('build-prod', function(){
    isProduction=true;
    runSequence('clean', [
        'html',
        'robots',
        'scripts',
        'theme',
        'lib'
    ], 'revision');
});

// For development
gulp.task('build', function(){
    // note: revision has a short circuit for dev
    runSequence('clean', [
        'html',
        'robots',
        'scripts',
        'theme',
        'lib'
    ], 'revision');
});

// For development
gulp.task('serve', ['default']);
gulp.task('default', ['build'], function(){
    isProduction = false;
    gulp.start('watch');
});
<|endoftext|>


<commit_before>var Q = require('q'),
    loadModule = require('./module-loader').loadModule,
    inspect = require('util').inspect,

    dump = function dump(o) {
      return inspect(o, {depth: null});
    };

describe('fogbugz module', function () {

  describe('logon method', function () {

    it('should fail if error received', function (done) {
      var msg = 'error',
          request = jasmine.createSpy('request')
              .andCallFake(function (url, cb) {
                cb(msg);
              }),
          mocks = {
            request: request
          },
          fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.logon()
          .then(function () {
            expect(true).toBe(false);
          }, function (err) {
            expect(err).toBe(msg);
          })
          .finally(fogbugz.forgetToken)
          .finally(done);
    });

    it('should successfully login', function (done) {
      var token = 'capybara',
          xml = '<response><token><![CDATA[' + token +
                ']]></token></response>',
          request = jasmine.createSpy('request')
              .andCallFake(function (url, cb) {
                cb(null, null, xml);
              }),
          mocks = {
            request: request
          },
          fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;

      fogbugz.logon()
          .then(function (res) {
            expect(res.token).toBe(token);
            expect(res.cached).toBeFalsy();
          })
          .then(fogbugz.logon)
          .then(function (res) {
            expect(res.token).toBe(token);
            expect(res.cached).toBeTruthy();
          })
          .finally(fogbugz.forgetToken)
          .finally(done);
    });
  });

  describe('logoff method', function (done) {
    it('should fail w/o presence of token', function () {
      var mocks = {},
          fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.logoff()
          .then(function () {
            expect(true).toBe(false);
          }, function (err) {
            expect(err).toBe(fogbugz.MODULE_ERRORS.undefined_token);
          })
          .finally(fogbugz.forgetToken)
          .finally(done);
    });

    it('should fail if error received', function (done) {
      var msg = 'error',
          request = jasmine.createSpy('request')
              .andCallFake(function (url, cb) {
                cb(msg);
              }),
          mocks = {
            request: request
          },
          fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.logoff()
          .then(function () {
            expect(true).toBe(false);
          }, function (err) {
            expect(err).toBe(msg);
          })
          .finally(fogbugz.forgetToken)
          .finally(done);
    });

    it('should succeed if no error (?)', function (done) {
      var request = jasmine.createSpy('request')
              .andCallFake(function (url, cb) {
                cb();
              }),
          mocks = {
            request: request
          },
          fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.logoff()
          .then(function (res) {
            expect(res).toBe(true);
          })
          .finally(fogbugz.forgetToken)
          .finally(done);
    });

  });

  describe('listFilters method', function () {
    it('should get a list of available filters', function (done) {
      var filtersXml = '<response><filters><filter type="builtin" sFilter="ez">My Cases</filter><filter type="builtin" sFilter="inbox">Inbox</filter></filters></response>',
          request = jasmine.createSpy('request')
              .andCallFake(function (url, cb) {
                cb(null, null, filtersXml);
              }),
          mocks = {
            request: request
          },
          fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.listFilters()
          .then(function (res) {
            expect(res).toEqual([
              new fogbugz.Filter({"name": "My Cases", "type": "builtin", "id": "ez", "url": "https://zzz.fogbugz.com/default.asp?pgx=LF&ixFilter=ez"}),
              new fogbugz.Filter({"name": "Inbox", "type": "builtin", "id": "inbox", "url": "https://zzz.fogbugz.com/default.asp?pgx=LF&ixFilter=inbox"})
            ]);
          }, function () {
            expect(true).toBe(false);
          })
          .finally(fogbugz.forgetToken)
          .finally(done);
    });
  });

  describe('setCurrentFilter method', function () {
    it('shoud set the current filter', function (done) {
      var xml = '<response></response>',
          request = jasmine.createSpy('request')
              .andCallFake(function (url, cb) {
                cb(null, null, xml);
              }),
          mocks = {
            request: request
          },
          fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.setCurrentFilter('ez')
          .then(function (res) {
            expect(res).toBe(true);
          })
          .finally(fogbugz.forgetToken)
          .finally(done);
    });

  });

  describe('search method', function () {
    it('should perform a search', function (done) {
      var xml = '<response><cases count="7"><case ixBug="16006" operations="edit,assign,resolve,email,remind"><sTitle><![CDATA[AQ toolkit API: bar chart shown and selected for text]]></sTitle><sStatus><![CDATA[ Active ]]></sStatus></case></cases></response>',
          request = jasmine.createSpy('request')
              .andCallFake(function (url, cb) {
                cb(null, null, xml);
              }),
          fogbugz = loadModule('./index.js',
              {
                request: request
              }).module.exports;

      fogbugz.setToken('capybara');
      fogbugz.search('16227')
          .then(function (res) {
            expect(res).toEqual([
              new fogbugz.Case({"status": "Active", "title": "AQ toolkit API: bar chart shown and selected for text", "operations":
                      ["edit", "assign", "resolve", "email", "remind"
                      ], "id": "16006", url: "https://zzz.fogbugz.com/default.asp?16006"}
              )]);
          }, function (err) {
            console.error(err);
            expect(true).toBe(false);
          })
          .finally(fogbugz.forgetToken)
          .finally(done);

    });
  });

});
<commit_msg>fixing unit tests<commit_after>var Q = require('q'),
  loadModule = require('./module-loader').loadModule,
  inspect = require('util').inspect,

  dump = function dump(o) {
    return inspect(o, {depth: null});
  };

describe('fogbugz module', function () {

  describe('logon method', function () {

    it('should fail if error received', function (done) {
      var msg = 'error',
        request = jasmine.createSpy('request')
          .andCallFake(function (url, cb) {
            cb(msg);
          }),
        mocks = {
          request: request
        },
        fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.logon()
        .then(function () {
          expect(true).toBe(false);
        }, function (err) {
          expect(err).toBe(msg);
        })
        .finally(fogbugz.forgetToken)
        .finally(done);
    });

    it('should successfully login', function (done) {
      var token = 'capybara',
        xml = '<response><token><![CDATA[' + token +
              ']]></token></response>',
        request = jasmine.createSpy('request')
          .andCallFake(function (url, cb) {
            cb(null, null, xml);
          }),
        mocks = {
          request: request
        },
        fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;

      fogbugz.logon()
        .then(function (res) {
          expect(res.token).toBe(token);
          expect(res.cached).toBeFalsy();
        })
        .then(fogbugz.logon)
        .then(function (res) {
          expect(res.token).toBe(token);
          expect(res.cached).toBeTruthy();
        })
        .finally(fogbugz.forgetToken)
        .finally(done);
    });
  });

  describe('logoff method', function (done) {
    it('should fail w/o presence of token', function () {
      var mocks = {},
        fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.logoff()
        .then(function () {
          expect(true).toBe(false);
        }, function (err) {
          expect(err).toBe(fogbugz.MODULE_ERRORS.undefined_token);
        })
        .finally(fogbugz.forgetToken)
        .finally(done);
    });

    it('should fail if error received', function (done) {
      var msg = 'error',
        request = jasmine.createSpy('request')
          .andCallFake(function (url, cb) {
            cb(msg);
          }),
        mocks = {
          request: request
        },
        fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.logoff()
        .then(function () {
          expect(true).toBe(false);
        }, function (err) {
          expect(err).toBe(msg);
        })
        .finally(fogbugz.forgetToken)
        .finally(done);
    });

    it('should succeed if no error (?)', function (done) {
      var request = jasmine.createSpy('request')
          .andCallFake(function (url, cb) {
            cb();
          }),
        mocks = {
          request: request
        },
        fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.logoff()
        .then(function (res) {
          expect(res).toBe(true);
        })
        .finally(fogbugz.forgetToken)
        .finally(done);
    });

  });

  describe('listFilters method', function () {
    it('should get a list of available filters', function (done) {
      var filtersXml = '<response><filters><filter type="builtin" sFilter="ez">My Cases</filter><filter type="builtin" sFilter="inbox">Inbox</filter></filters></response>',
        request = jasmine.createSpy('request')
          .andCallFake(function (url, cb) {
            cb(null, null, filtersXml);
          }),
        mocks = {
          request: request
        },
        fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.listFilters()
        .then(function (res) {
          expect(res).toEqual([
            new fogbugz.Filter({"name": "My Cases", "type": "builtin", "id": "ez", "url": "https://zzz.fogbugz.com/default.asp?pgx=LF&ixFilter=ez"}),
            new fogbugz.Filter({"name": "Inbox", "type": "builtin", "id": "inbox", "url": "https://zzz.fogbugz.com/default.asp?pgx=LF&ixFilter=inbox"})
          ]);
        }, function () {
          expect(true).toBe(false);
        })
        .finally(fogbugz.forgetToken)
        .finally(done);
    });
  });

  describe('setCurrentFilter method', function () {
    it('shoud set the current filter', function (done) {
      var xml = '<response></response>',
        request = jasmine.createSpy('request')
          .andCallFake(function (url, cb) {
            cb(null, null, xml);
          }),
        mocks = {
          request: request
        },
        fogbugz;
      fogbugz = loadModule('./index.js', mocks).module.exports;
      fogbugz.setToken('capybara');
      fogbugz.setCurrentFilter('ez')
        .then(function (res) {
          expect(res).toBe(true);
        })
        .finally(fogbugz.forgetToken)
        .finally(done);
    });

  });

  describe('search method', function () {
    it('should perform a search', function (done) {
      var xml = '<response><cases count="7"><case ixBug="16006" operations="edit,assign,resolve,email,remind"><sTitle><![CDATA[AQ toolkit API: bar chart shown and selected for text]]></sTitle><sFixFor><![CDATA[whenever]]></sFixFor><sStatus><![CDATA[ Active ]]></sStatus></case></cases></response>',
        request = jasmine.createSpy('request')
          .andCallFake(function (url, cb) {
            cb(null, null, xml);
          }),
        fogbugz = loadModule('./index.js',
          {
            request: request
          }).module.exports;

      fogbugz.setToken('capybara');
      fogbugz.search('16227')
        .then(function (res) {
          expect(res).toEqual(
            new fogbugz.Case({
                status: "Active",
                title: "AQ toolkit API: bar chart shown and selected for text",
                operations: ["edit", "assign", "resolve", "email", "remind"],
                id: "16006",
                url: "https://zzz.fogbugz.com/default.asp?16006",
                fixFor: "whenever"
              }
            ));
        }, function (err) {
          console.error(err);
          expect(true).toBe(false);
        })
        .finally(fogbugz.forgetToken)
        .finally(done);

    });
  });

});
<|endoftext|>


<commit_before>'use strict';

var Chance = require('chance'),
    chance = new Chance();

class ProjectsPage {

  constructor () {
  }

  get () {
    browser.get(global.defaultCommunity.url);
  }

  getPlusEl () {
    var platform = global.isDesktop ? 'desktop' : 'mobile';
    return element(by.css('.plus-' + platform + ' button'));
  }

  goToNew () {
    var newEl = this.getPlusEl();
    browser.wait(protractor.ExpectedConditions.visibilityOf(newEl));
    newEl.click();
  }
}

class ProjectPage {

  constructor () {
    this.titleEl = element(by.model('project.title'));

    this.menuEl = element(by.css('.project-' + global.media + ' [ui-turn-on="dropdownProjectMenu"]'));

    this.padEl = element(by.model('project.pad'));

    this.joinEl = element(by.css('button[join]'));

    this.joinEmailEl = element(by.model('message.email'));
    this.joinTextEl = element(by.model('message.text'));
    this.joinSendEl = element(by.css('[ng-click="$ctrl.send()"]'));

    this.joinStartEl = element(by.css('.project-join-success [join]'));

    this.leaveEl = element(by.css('.project-' + global.media + ' [join-copy-off="project.menu.join"]'));

    this.participantListEl = element(by.css('[avatars="project._participants"]'));
  }

  fetch (id) {
    browser.get(global.defaultCommunity.url + '/teems/fetch/' + id);
  }

  join (options) {
    // Default parameter values should be supported in node 6.x
    // join (options = { email: chance.email(), text: chance.sentence() }) {
    if (! options) {
      options = {};
    }

    if (! options.hasOwnProperty('email')) {
      options.email = chance.email();
    }

    if (! options.hasOwnProperty('text')) {
      options.text = chance.sentence();
    }

    browser.wait(protractor.ExpectedConditions.visibilityOf(this.joinEl));
    this.joinEl.click();

    this.joinEmailEl.sendKeys(options.email);

    // Don't touch the field if there is not text
    if (options.text) {
      this.joinTextEl.sendKeys(options.text);
    }

    this.joinSendEl.click();

    this.joinStartEl.click();
  }

  leave () {
    this.menuEl.click();
    this.leaveEl.click();
  }

  getTitle () {
    return this.titleEl.getAttribute('value');
  }

  getPadText () {
    return this.padEl.getText();
  }

  getParticipants () {
    browser.wait(protractor.ExpectedConditions.presenceOf(this.participantListEl));
    return this.participantListEl.all(by.css('img')).getAttribute('title');
  }

  getParticipantsFromModel () {
    return browser.executeScript(function() {
      return angular.element('[project-people]').scope().project._participants.map(participant => participant.split('@')[0]);
    });
  }
}

class NewProjectPage {

  constructor () {
    this.title = chance.sentence({ words: 5 });

    // Remove trailing period
    this.title = this.title.substring(0, this.title.length - 1);

    this.padText = chance.paragraph();

    this.titleInputEl = element(by.model('project.title'));

    this.nextBtn = element(by.css('[ng-click="goToNextForm()"]'));

    this.padEl = element(by.css('.wave-editor-on'));
    this.padCheckBtn = element(by.css('.pad-check'));
  }

  create () {
    // Image
    this.nextBtn.click();

    // Title
    this.titleInputEl.sendKeys(this.title);

    this.nextBtn.click();

    // Invite
    this.nextBtn.click();

    // Share
    this.nextBtn.click();

    this.padEl.click();

    this.padEl.sendKeys(this.padText);

    if (! isDesktop) {
      this.padCheckBtn.click();
    }
  }
}

module.exports = {
  ProjectsPage,
  ProjectPage,
  NewProjectPage
};
<commit_msg>Click on empty pad tip in tests<commit_after>'use strict';

var Chance = require('chance'),
    chance = new Chance();

class ProjectsPage {

  constructor () {
  }

  get () {
    browser.get(global.defaultCommunity.url);
  }

  getPlusEl () {
    var platform = global.isDesktop ? 'desktop' : 'mobile';
    return element(by.css('.plus-' + platform + ' button'));
  }

  goToNew () {
    var newEl = this.getPlusEl();
    browser.wait(protractor.ExpectedConditions.visibilityOf(newEl));
    newEl.click();
  }
}

class ProjectPage {

  constructor () {
    this.titleEl = element(by.model('project.title'));

    this.menuEl = element(by.css('.project-' + global.media + ' [ui-turn-on="dropdownProjectMenu"]'));

    this.padEl = element(by.model('project.pad'));

    this.joinEl = element(by.css('button[join]'));

    this.joinEmailEl = element(by.model('message.email'));
    this.joinTextEl = element(by.model('message.text'));
    this.joinSendEl = element(by.css('[ng-click="$ctrl.send()"]'));

    this.joinStartEl = element(by.css('.project-join-success [join]'));

    this.leaveEl = element(by.css('.project-' + global.media + ' [join-copy-off="project.menu.join"]'));

    this.participantListEl = element(by.css('[avatars="project._participants"]'));
  }

  fetch (id) {
    browser.get(global.defaultCommunity.url + '/teems/fetch/' + id);
  }

  join (options) {
    // Default parameter values should be supported in node 6.x
    // join (options = { email: chance.email(), text: chance.sentence() }) {
    if (! options) {
      options = {};
    }

    if (! options.hasOwnProperty('email')) {
      options.email = chance.email();
    }

    if (! options.hasOwnProperty('text')) {
      options.text = chance.sentence();
    }

    browser.wait(protractor.ExpectedConditions.visibilityOf(this.joinEl));
    this.joinEl.click();

    this.joinEmailEl.sendKeys(options.email);

    // Don't touch the field if there is not text
    if (options.text) {
      this.joinTextEl.sendKeys(options.text);
    }

    this.joinSendEl.click();

    this.joinStartEl.click();
  }

  leave () {
    this.menuEl.click();
    this.leaveEl.click();
  }

  getTitle () {
    return this.titleEl.getAttribute('value');
  }

  getPadText () {
    return this.padEl.getText();
  }

  getParticipants () {
    browser.wait(protractor.ExpectedConditions.presenceOf(this.participantListEl));
    return this.participantListEl.all(by.css('img')).getAttribute('title');
  }

  getParticipantsFromModel () {
    return browser.executeScript(function() {
      return angular.element('[project-people]').scope().project._participants.map(participant => participant.split('@')[0]);
    });
  }
}

class NewProjectPage {

  constructor () {
    this.title = chance.sentence({ words: 5 });

    // Remove trailing period
    this.title = this.title.substring(0, this.title.length - 1);

    this.padText = chance.paragraph();

    this.titleInputEl = element(by.model('project.title'));

    this.nextBtn = element(by.css('[ng-click="goToNextForm()"]'));

    this.padEmptyTipCloseBtn = element(by.css('[ng-click="closePadEmptyTip()"]'));

    this.padEl = element(by.css('.wave-editor-on'));
    this.padCheckBtn = element(by.css('.pad-check'));
  }

  create () {
    // Image
    this.nextBtn.click();

    // Title
    this.titleInputEl.sendKeys(this.title);

    this.nextBtn.click();

    // Invite
    this.nextBtn.click();

    // Share
    this.nextBtn.click();

    this.padEmptyTipCloseBtn.click();

    // pad should be focused now
    // this.padEl.click();

    this.padEl.sendKeys(this.padText);

    if (! isDesktop) {
      this.padCheckBtn.click();
    }
  }
}

module.exports = {
  ProjectsPage,
  ProjectPage,
  NewProjectPage
};
<|endoftext|>


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

  // if ('serviceWorker' in navigator) {
  //   navigator.serviceWorker.register('/service-worker.js', { scope: '/' });
  // }

  var content = document.getElementById('content'),
      txt = document.getElementsByClassName('txt')[0];

  function getContent(pageToFetch) {
    fetch(pageToFetch)
      .then(function(response) {
        return response.text();
      }).then(function (text) {
        highlightUpdatedContent();
        content.setAttribute('markdown', text);
      });
  }

  function highlightUpdatedContent() {
    txt.classList.add('changed');
    setTimeout(function() {
      txt.classList.remove('changed');
    }, 800);
  }

  page('/', function() {
    getContent('content/next-event.md');
  });

  page('/about', function() {
    getContent('content/about.md');
  });

  page('/past', function() {
    getContent('content/past-events.md');
  });

  page({hashbang: true});
})();
<commit_msg>register SW<commit_after>(function() {
  'use strict';

  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js', { scope: '/' });
  }

  var content = document.getElementById('content'),
      txt = document.getElementsByClassName('txt')[0];

  function getContent(pageToFetch) {
    fetch(pageToFetch)
      .then(function(response) {
        return response.text();
      }).then(function (text) {
        highlightUpdatedContent();
        content.setAttribute('markdown', text);
      });
  }

  function highlightUpdatedContent() {
    txt.classList.add('changed');
    setTimeout(function() {
      txt.classList.remove('changed');
    }, 800);
  }

  page('/', function() {
    getContent('content/next-event.md');
  });

  page('/about', function() {
    getContent('content/about.md');
  });

  page('/past', function() {
    getContent('content/past-events.md');
  });

  page({hashbang: true});
})();
<|endoftext|>


<commit_before> /**
  * @ngdoc directive
  * @memberOf 'view.file'
  * @name view-object
  * @description
  *   Angular directive for including HTML object tag dynamically.
  *
  * @attr {String}    data          Required. Url of file to be viewed. Url must be trusted upfront.
  * @attr {String}    type          Optional. Mime-type of file to be viewed.
  * @attr {String}    height        Optional. Height value to be applied to object tag.
  * @attr {String}    width         Optional. Width value to be applied to object tag.
  *
  * @example
  * <view-object data="ctrl.viewUri" type="ctrl.contentType" height="'600px'" width="'100%'"></view-object>
  */

(function () {
  'use strict';

  angular.module('view.file')
    .directive('viewObject', function() {
      return {
        restrict: 'E',
        transclude: true,
        link: function(scope, element, attrs) {
          var data = ' data="' + scope.$eval(attrs.data) + '"';
          var type = attrs.type ? (' type="' + scope.$eval(attrs.type) + '"') : '';
          var height = attrs.height ? (' height="' + scope.$eval(attrs.height) + '"') : '';
          var width = attrs.width ? (' width="' + scope.$eval(attrs.width) + '"') : '';
          element.append('<object " ' + height + width + type + data + ' ng-transclude></object>');
        }
      };
    });

}());<commit_msg>Fixed #11: fixed transclusion in view-object directive<commit_after> /**
  * @ngdoc directive
  * @memberOf 'view.file'
  * @name view-object
  * @description
  *   Angular directive for including HTML object tag dynamically.
  *
  * @attr {String}    data          Required. Url of file to be viewed. Url must be trusted upfront.
  * @attr {String}    type          Optional. Mime-type of file to be viewed.
  * @attr {String}    height        Optional. Height value to be applied to object tag.
  * @attr {String}    width         Optional. Width value to be applied to object tag.
  *
  * @example
  * <view-object data="ctrl.viewUri" type="ctrl.contentType" height="'600px'" width="'100%'"></view-object>
  */

(function () {
  'use strict';

  angular.module('view.file')
    .directive('viewObject', ['$compile', function($compile) {
      return {
        restrict: 'E',
        link: function(scope, element, attrs) {
          // prepare object tag attributes
          var data = ' data="' + scope.$eval(attrs.data) + '"';
          var type = attrs.type ? (' type="' + scope.$eval(attrs.type) + '"') : '';
          var height = attrs.height ? (' height="' + scope.$eval(attrs.height) + '"') : '';
          var width = attrs.width ? (' width="' + scope.$eval(attrs.width) + '"') : '';

          // tried transclude before, but that didn't seem to work..
          var innerHtml = element.html();
          element.html('<object " ' + height + width + type + data + '>' + innerHtml + '</object>');
          $compile(element.contents())(scope);
        }
      };
    }]);

}());<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', mes<commit_msg>Updated the readme again<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', mess<|endoftext|>