<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guys does the other half of energy collection. The miner gets it from the source, and the helper does the
 * transportation. We don't want them just going for the nearest source, as that means that if we have more than one
 * miner, all the helpers will only go for the first miner. To counter this, we assign them to a miner the same way
 * we assign a miner to a source
 */

var helper = {
    parts: [
        [MOVE, CARRY, MOVE, CARRY],
        [MOVE, CARRY, MOVE, CARRY, MOVE, CARRY]
    ],

    assignMiner: function () {
        var creep = this.creep;

        var miner = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (miner) {
                if (miner.memory.role == 'miner' && miner.memory.helpers.length < miner.memory.helpersNeeded)
                    return true;

                return false;
            }
        });

        if (miner == undefined)
            return;

        creep.memory.miner = miner.id;
        miner.memory.helpers.push(creep.id);
    },

    /**
     * @TODO: Make helpers smarter about avoiding miners, instead of just waiting till they're 5 tiles away
     * @TODO: When spawns are at .25, and extensions have >= 200, help builders before filling shit up
     */
    action: function () {
        var creep = this.creep;

        if (creep.memory.courier !== undefined && creep.memory.courier == true) {
            creep.memory.courier = false;
            return;
        }

        //If this helper isn't assigned to a miner, find one and assign him to it. If it is assigned to a miner,
        //then find that miner by his id
        if (creep.memory.miner == undefined)
            this.assignMiner();

        var miner = Game.getObjectById(creep.memory.miner);

        if (miner == null) {
            creep.suicide();
            return;
        }

        //If we can still pick up energy, let's do that
        if (creep.energy < creep.energyCapacity) {
            if (creep.pos.isNearTo(miner)) {
                var energy = creep.pos.findInRange(FIND_DROPPED_ENERGY, 1)[0];
                creep.pickup(energy);
            }
            else {
                if (miner.memory.isNearSource)
                    creep.moveTo(miner);
            }

            return;
        }

        var target = null;

        //Okay, everything below is for dropping energy off

        if (!target) {
            var spawn = creep.pos.findClosestByPath(FIND_MY_SPAWNS);

            //If we found it, set it as our target
            if (spawn)
                target = spawn;
        }

        //Let's get the direction we want to go in
        var targetDirection = creep.pos.findPathTo(target, { ignoreCreeps: true })[0].direction;

        //Let's look for a courier in that direction. We'll check on making sure they're the right
        //role, if they can hold any energy, if they're in range and if they're in the same direction
        var leftDir = targetDirection - 1;
        var rightDir = targetDirection + 1;

        if (leftDir < 1)
            leftDir += 8;
        if (leftDir > 8)
            leftDir -= 8;

        if (rightDir < 1)
            rightDir += 8;
        if (rightDir > 8)
            rightDir -= 8;

        var courier = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (possibleTarget) {
                return (
                    possibleTarget.memory.role == creep.memory.role
//					&& possibleTarget.memory.miner == creep.memory.miner
                    && possibleTarget.energy < possibleTarget.energyCapacity
                    && creep.pos.inRangeTo(possibleTarget, 1)
                    && (
                        creep.pos.getDirectionTo(possibleTarget) == targetDirection
                        || creep.pos.getDirectionTo(possibleTarget) == leftDir
                        || creep.pos.getDirectionTo(possibleTarget) == rightDir
                    )
                );
            }
        });

        //If we found a courier, make that courier our new target
        if (courier !== null && !creep.pos.isNearTo(target)) {
            target = courier;
            target.memory.courier = true;
        }

        //If we're near to the target, either give it our energy or drop it
        if (creep.pos.isNearTo(target)) {
            if (target.energy < target.energyCapacity) {
                creep.transfer(target, RESOURCE_ENERGY);
            }
            else
                creep.drop(RESOURCE_ENERGY);
        }
        //Let's do the moving
        else {
            creep.moveTo(target);
        }
    }
};

module.exports = helper;<commit_msg>Fixing miner<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guys does the other half of energy collection. The miner gets it from the source, and the helper does the
 * transportation. We don't want them just going for the nearest source, as that means that if we have more than one
 * miner, all the helpers will only go for the first miner. To counter this, we assign them to a miner the same way
 * we assign a miner to a source
 */

var helper = {
    parts: [
        [MOVE, CARRY],
        [MOVE, CARRY, MOVE, CARRY],
        [MOVE, CARRY, MOVE, CARRY, MOVE, CARRY]
    ],

    assignMiner: function () {
        var creep = this.creep;

        var miner = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (miner) {
                if (miner.memory.role == 'miner' && miner.memory.helpers.length < miner.memory.helpersNeeded)
                    return true;

                return false;
            }
        });

        if (miner == undefined)
            return;

        creep.memory.miner = miner.id;
        miner.memory.helpers.push(creep.id);
    },

    /**
     * @TODO: Make helpers smarter about avoiding miners, instead of just waiting till they're 5 tiles away
     * @TODO: When spawns are at .25, and extensions have >= 200, help builders before filling shit up
     */
    action: function () {
        var creep = this.creep;

        if (creep.memory.courier !== undefined && creep.memory.courier == true) {
            creep.memory.courier = false;
            return;
        }

        //If this helper isn't assigned to a miner, find one and assign him to it. If it is assigned to a miner,
        //then find that miner by his id
        if (creep.memory.miner == undefined)
            this.assignMiner();

        var miner = Game.getObjectById(creep.memory.miner);

        if (miner == null) {
            creep.suicide();
            return;
        }

        //If we can still pick up energy, let's do that
        if (creep.energy < creep.energyCapacity) {
            if (creep.pos.isNearTo(miner)) {
                var energy = creep.pos.findInRange(FIND_DROPPED_ENERGY, 1)[0];
                creep.pickup(energy);
            }
            else {
                if (miner.memory.isNearSource)
                    creep.moveTo(miner);
            }

            return;
        }

        var target = null;

        //Okay, everything below is for dropping energy off

        if (!target) {
            var spawn = creep.pos.findClosestByPath(FIND_MY_SPAWNS);

            //If we found it, set it as our target
            if (spawn)
                target = spawn;
        }

        //Let's get the direction we want to go in
        var targetDirection = creep.pos.findPathTo(target, { ignoreCreeps: true })[0].direction;

        //Let's look for a courier in that direction. We'll check on making sure they're the right
        //role, if they can hold any energy, if they're in range and if they're in the same direction
        var leftDir = targetDirection - 1;
        var rightDir = targetDirection + 1;

        if (leftDir < 1)
            leftDir += 8;
        if (leftDir > 8)
            leftDir -= 8;

        if (rightDir < 1)
            rightDir += 8;
        if (rightDir > 8)
            rightDir -= 8;

        var courier = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
            filter: function (possibleTarget) {
                return (
                    possibleTarget.memory.role == creep.memory.role
//					&& possibleTarget.memory.miner == creep.memory.miner
                    && possibleTarget.energy < possibleTarget.energyCapacity
                    && creep.pos.inRangeTo(possibleTarget, 1)
                    && (
                        creep.pos.getDirectionTo(possibleTarget) == targetDirection
                        || creep.pos.getDirectionTo(possibleTarget) == leftDir
                        || creep.pos.getDirectionTo(possibleTarget) == rightDir
                    )
                );
            }
        });

        //If we found a courier, make that courier our new target
        if (courier !== null && !creep.pos.isNearTo(target)) {
            target = courier;
            target.memory.courier = true;
        }

        //If we're near to the target, either give it our energy or drop it
        if (creep.pos.isNearTo(target)) {
            if (target.energy < target.energyCapacity) {
                creep.transfer(target, RESOURCE_ENERGY);
            }
            else
                creep.drop(RESOURCE_ENERGY);
        }
        //Let's do the moving
        else {
            creep.moveTo(target);
        }
    }
};

module.exports = helper;<|endoftext|>


<commit_before>const express = require('express');
const User = require(__dirname + '/../models/user');
const jsonParser = require('body-parser').json();
const handleDBError = require(__dirname + '/../lib/handleDBError');
const basicHTTP = require(__dirname + '/../lib/basic_http');
const saveUserDB = require(__dirname + '/../lib/save_new_user');
const emailValidation = require(__dirname + '/../lib/email_validation.js');

var authRouter = module.exports = exports = express.Router();

authRouter.post('/signup', jsonParser, (req, res) => {

  if (!(req.body.email || '').length && emailValidation(req.body.email)) return res.status(200).json( { msg: 'Please enter a email' } );

  if (!(req.body.username || '').length) return res.status(200).json( { msg: 'Please enter a user name' } );

  if (!(req.body.password || '').length > 7) return res.status(200).json( { msg: 'Please enter password' } );

  User.find({ $or: [ { 'username': req.body.username }, { 'email': req.body.email } ] }, (err, data) => {
    if (err) return handleDBError(err, res);
    if (data.length) return res.status(200).json( { msg: 'user already exist; plese sign in this site' } );
    saveUserDB(req, res);
  });
});

authRouter.post('/signin', basicHTTP, (req, res) => {

  User.findOne( { 'authentication.email': req.basicHTTP.email }, (err, user) => {
    if (err) {
      console.log(err);
      return res.status(401).json( { msg: 'invalid username or password' } );
    }

    if (!user) return res.status(401).json( { msg: 'invalid username or password' } );

    if (!user.comparePassword(req.basicHTTP.password)) return res.status(401).json( { msg: 'invalid username or password' } );

    res.json( { token: user.generateToken() } );
  });
});
<commit_msg>add signup user unique check<commit_after>const express = require('express');
const User = require(__dirname + '/../models/user');
const jsonParser = require('body-parser').json();
const handleDBError = require(__dirname + '/../lib/handleDBError');
const basicHTTP = require(__dirname + '/../lib/basic_http');
const saveUserDB = require(__dirname + '/../lib/save_new_user');
const emailValidation = require(__dirname + '/../lib/email_validation.js');

var authRouter = module.exports = exports = express.Router();

authRouter.post('/signup', jsonParser, (req, res) => {

  if (!(req.body.email || '').length && !emailValidation(req.body.email)) return res.status(200).json( { msg: 'Please enter a email' } );

  if(!emailValidation(req.body.email)) return res.status(200).json( { msg: 'Please enter a valid email' } );

  if (!(req.body.username || '').length) return res.status(200).json( { msg: 'Please enter a user name' } );

  if (!((req.body.password || '').length > 7)) return res.status(200).json( { msg: 'Please enter password of length more than 7' } );

  User.find({ $or: [ { 'username': req.body.username }, { 'email': req.body.email } ] }, (err, data) => {
    if (err) return handleDBError(err, res);
    if (data.length) return res.status(200).json( { msg: 'user already exist; please sign in this site' } );
    saveUserDB(req, res);
  });
});

authRouter.post('/signin', basicHTTP, (req, res) => {

  User.findOne( { 'authentication.email': req.basicHTTP.email }, (err, user) => {
    if (err) return handleDBError(err, res);

    if (!user) return res.status(401).json( { msg: 'no user exist ' } );

    if (!user.comparePassword(req.basicHTTP.password)) return res.status(401).json( { msg: 'incorrect password' } );

    res.json( { token: user.generateToken() } );
  });
});
<|endoftext|>


<commit_before>const uuidv4 = require('uuid/v4')
const slack = require('./slackNotify')
const moment = require('moment')

const Event = function(init_obj){

  console.log(init_obj)
  //required attributes
  this.id = uuidv4()
  this.title = init_obj.title
  this.slug = this.title.toLowerCase().replace(/ /g,"-")

  if(init_obj.hasOwnProperty('description')){
    this.description = init_obj.description
  }
  if(init_obj.hasOwnProperty('brief_description')){
    this.brief_description = init_obj.brief_description
  }
  if(init_obj.hasOwnProperty('admission_fee')){
    this.admission_fee = init_obj.admission_fee
  }

  this.date = init_obj.date
  this.time_start = init_obj.time_start
  this.time_end = init_obj.time_end

  this.multi_day = init_obj.multi_day;
  if(init_obj.hasOwnProperty('additional_dates')){
    this.additional_dates = init_obj.additional_dates;
  }

  // this.when = moment(this.date).format('dddd, MMMM Do, YYYY') +"
 "+ moment(this.time_start).format('h:mma') +" - "+ moment(this.time_end).format('h:mma')

  //venue specific attributes
  if(init_obj.hasOwnProperty('address')){
    this.address = init_obj.address
  }
  if(init_obj.hasOwnProperty('map_link')){
    this.map_link = init_obj.map_link
  }
  if(init_obj.hasOwnProperty('venue_id')){
    this.venue_id = init_obj.venue_id
  }

  // Organizer info -- will add more for venue submitting own event case
  if(init_obj.hasOwnProperty('organizers')){
    this.organizers = init_obj.organizers
  }
  if(init_obj.hasOwnProperty('organizer_contact')){
    this.organizer_contact = init_obj.organizer_contact
  }
  else{
    this.organizer_contact = "no organizers :("
  }

  // Optional info
  if(init_obj.hasOwnProperty('ticket_link')){
    if(init_obj.ticket_link === ""){
      this.ticket_link = "none"
    }
    else{
      this.ticket_link = init_obj.ticket_link
    }
  }

  if(init_obj.hasOwnProperty('fb_event_link')){
    if(init_obj.fb_event_link === ""){
      this.fb_event_link = "none"
    }
    else{
      this.fb_event_link = init_obj.fb_event_link
    }
  }

  /*
    TODO (CAW) Seems like this would be better handled in display logic,
     persisting none as a string can complicate query logic down the road,
     better to just leave it empty
   */
  if(init_obj.hasOwnProperty('eventbrite_link')){
    if(init_obj.eventbrite_link === ""){
      this.eventbrite_link = "none"
    }
    else{
      this.eventbrite_link = init_obj.eventbrite_link
    }
  }

  if(init_obj.hasOwnProperty('website_link')){
    if(init_obj.website_link === ""){
      this.website_link = "none"
    }
    else{
      this.website_link = init_obj.website_link
    }
  }

}

Event.prototype.Notify = function(){
  // TODO (CAW) Why copy all this over to a string like this, can we just use stringify?
  var event_payload = `\n\{
        "id":"${this.id}",
        "title":"${this.title}",
        "slug":"${this.slug}",
        "time_start":"${this.time_start}",
        "time_end": "${this.time_end}",
        "multi_day": "${this.multi_day}",
        "additional_dates": "${this.additional_dates}",
        "website_link": "${this.website_link}",
        "image":"${this.image}",
        "social_image":"${this.social_image}",
        "venues":["${this.venues}"],
        "admission_fee": "${this.admission_fee}",
        "address": "${this.address}",
        "organizers":["${this.organizers}"],
        "map_link":"${this.map_link}",
        "brief_description":"${this.brief_description}",
        "description":"${this.description}",
        "links":["none"],
        "ticket_link":"${this.ticket_link}",
        "fb_event_link":"${this.fb_event_link}",
        "eventbrite_link":"${this.eventbrite_link}",
        "bitly_link":"${this.bitly_link}",
        "tags":["not-yet-implemented"]
      \}`;

      let slack_channel = process.env.ENV == 'prod' ? 'submission' : 'test'
      slack.Notify(slack_channel,"Review Me. Copy Me. Paste Me. Deploy Me." + event_payload + "\n Contact: "+this.organizer_contact);
}

// Event.prototype.AddSocialImage = function(id, server_url, bucket_url){
//   this.social_image = server_url + bucket_url + "/uploads/social/" + id + "_social.jpg";
// }
//
// Event.prototype.AddHeroImage = function(id, server_url, bucket_url){
//   this.image = server_url + bucket_url + "/uploads/" + id + ".jpg";
// }

module.exports = Event
<commit_msg>reduced complexity/redundancy in event notify<commit_after>const uuidv4 = require('uuid/v4')
const slack = require('./slackNotify')
const moment = require('moment')

const Event = function(init_obj){

  console.log(init_obj)
  //required attributes
  this.id = uuidv4()
  this.title = init_obj.title
  this.slug = this.title.toLowerCase().replace(/ /g,"-")

  if(init_obj.hasOwnProperty('description')){
    this.description = init_obj.description
  }
  if(init_obj.hasOwnProperty('brief_description')){
    this.brief_description = init_obj.brief_description
  }
  if(init_obj.hasOwnProperty('admission_fee')){
    this.admission_fee = init_obj.admission_fee
  }

  this.date = init_obj.date
  this.time_start = init_obj.time_start
  this.time_end = init_obj.time_end

  this.multi_day = init_obj.multi_day;
  if(init_obj.hasOwnProperty('additional_dates')){
    this.additional_dates = init_obj.additional_dates;
  }

  // this.when = moment(this.date).format('dddd, MMMM Do, YYYY') +"
 "+ moment(this.time_start).format('h:mma') +" - "+ moment(this.time_end).format('h:mma')

  //venue specific attributes
  if(init_obj.hasOwnProperty('address')){
    this.address = init_obj.address
  }
  if(init_obj.hasOwnProperty('venue_id')){
    this.venue_id = init_obj.venue_id
  }

  // Organizer info -- will add more for venue submitting own event case
  if(init_obj.hasOwnProperty('organizer_contact')){
    this.organizer_contact = init_obj.organizer_contact
  }
  else{
    this.organizer_contact = "no organizers :("
  }

  // Optional info
  if(init_obj.hasOwnProperty('ticket_link')){
    if(init_obj.ticket_link === ""){
      this.ticket_link = "none"
    }
    else{
      this.ticket_link = init_obj.ticket_link
    }
  }

  if(init_obj.hasOwnProperty('fb_event_link')){
    if(init_obj.fb_event_link === ""){
      this.fb_event_link = "none"
    }
    else{
      this.fb_event_link = init_obj.fb_event_link
    }
  }

  /*
    TODO (CAW) Seems like this would be better handled in display logic,
     persisting none as a string can complicate query logic down the road,
     better to just leave it empty
   */
  if(init_obj.hasOwnProperty('eventbrite_link')){
    if(init_obj.eventbrite_link === ""){
      this.eventbrite_link = "none"
    }
    else{
      this.eventbrite_link = init_obj.eventbrite_link
    }
  }

  if(init_obj.hasOwnProperty('website_link')){
    if(init_obj.website_link === ""){
      this.website_link = "none"
    }
    else{
      this.website_link = init_obj.website_link
    }
  }

}

Event.prototype.Notify = function(){
  var event_payload = JSON.stringify(this, null, "\t")

  let slack_channel = process.env.ENV == 'prod' ? 'submission' : 'test'
  slack.Notify(slack_channel,"Review Me. Copy Me. Paste Me. Deploy Me.\n" + event_payload + "\n Contact: "+this.organizer_contact);
}

// Event.prototype.AddSocialImage = function(id, server_url, bucket_url){
//   this.social_image = server_url + bucket_url + "/uploads/social/" + id + "_social.jpg";
// }
//
// Event.prototype.AddHeroImage = function(id, server_url, bucket_url){
//   this.image = server_url + bucket_url + "/uploads/" + id + ".jpg";
// }

module.exports = Event
<|endoftext|>


<commit_before>const keystone = require('keystone');

function normalizeProduct(product) {
    const {name, description, price, externalImages, image0} = product;

    return {
        name,
        description,
        price,
        image: externalImages.length !== 0 ? externalImages[0] : image0
    };
}

function onInitView(locals, next) {
    keystone
        .list('Product')
        .model
        .find()
        .limit(3)
        .select('name description price externalImages image0')
        .exec((err, products) => {
            if (!err) {
                Object.assign(locals, {products: products.map(normalizeProduct)});
            }
            next(err);
        });
}

exports = module.exports = (req, res) => {
    const view = new keystone.View(req, res);
    const {locals} = res;

    view.on('init', next => onInitView(locals, next));

    view.render('index');
};
<commit_msg>index view - fix image0<commit_after>const keystone = require('keystone');

function normalizeProduct(product) {
    const {name, description, price, externalImages, image0} = product;

    return {
        name,
        description,
        price,
        image: externalImages.length !== 0 ? externalImages[0] : '/product/images/' + image0.filename
    };
}

function onInitView(locals, next) {
    keystone
        .list('Product')
        .model
        .find()
        .limit(3)
        .select('name description price externalImages image0')
        .exec((err, products) => {
            if (!err) {
                Object.assign(locals, {products: products.map(normalizeProduct)});
            }
            next(err);
        });
}

exports = module.exports = (req, res) => {
    const view = new keystone.View(req, res);
    const {locals} = res;

    view.on('init', next => onInitView(locals, next));

    view.render('index');
};
<|endoftext|>


<commit_before>$(document).ready(function() {
	oh.campaign_read(function(campaigns){

		$("#loadinganimation").hide();

		var filter = getURLParameter("filter") || ".";
		var pattern = new RegExp(filter, "i");
		var allcampaigns = [];
		var nexturl = getURLParameter("next") || ".";

		campaigns.forEach(function(o){
			if(pattern.test(o)){
				allcampaigns.push(o);
				$("#campaignlist").append('
' + o + '
');
			}
		});

		if(allcampaigns.length == 0){
			alert('No "' + filter + '" campaigns found for the current ohmage user.')
		}
	});
});

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}<commit_msg>sort campaigns<commit_after>$(document).ready(function() {
	oh.campaign_read(function(campaigns){

		$("#loadinganimation").hide();

		var filter = getURLParameter("filter") || ".";
		var pattern = new RegExp(filter, "i");
		var allcampaigns = [];
		var nexturl = getURLParameter("next") || ".";

		campaigns.sort().forEach(function(o){
			if(pattern.test(o)){
				allcampaigns.push(o);
				$("#campaignlist").append('
' + o + '
');
			}
		});

		if(allcampaigns.length == 0){
			alert('No "' + filter + '" campaigns found for the current ohmage user.')
		}
	});
});

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
<|endoftext|>


<commit_before>//var games = [];

showMyGames();

function showMyGames(){
    /*$("#mygames").empty();

    for(var game in games){
        appendGame("#mygames", games, game);
    }*/
    $("#mygames").empty();

    var text_to_append = '

';

    for(var game in games){
        text_to_append += appendGame("#mygames", games, game);
    }

    text_to_append += "

";

    $('#mygames').append(text_to_append);

    for(var game in games){
        setEvents("#mygames", games, game);
    }
}

function showCommunityGames(){
    $("#community").empty();

    var text_to_append = '

';

    for(var game in games){
        if(games[game].public) text_to_append += appendGame("#community", games, game);
    }

    text_to_append += "

";

    $('#community').append(text_to_append);

    for(var game in games){
        if(games[game].public) setEvents("#community", games, game);
    }
}

function appendGame(parent, games, index){
    var url = gameTypeToUrl(games[index].type) + ".php?id=" + games[index].id;

    var game = `

${games[index].name} - ${games[index].type}

${games[index].description}

                                <input data-index="${index}" class="pubpriv-toggle" type="checkbox" data-toggle="toggle" data-on="Public" data-off="Private" ${games[index].public?"checked":""}>

`;

    return game;
}

function setEvents(parent, games, index) {
    $('.pubpriv-toggle').bootstrapToggle();

    $('.pubpriv-toggle').change(function() {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            games[index].public = $(this).prop('checked');
            savePlot(games[index]);
            showCommunityGames();
        }
    });

    $(".gamerow .gameinfo").on('click', function(e) {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            var action = $(e.target).hasClass('fa-trash') ? "remove" : "";
            action = $(e.target).hasClass('fa-pencil') ? "edit" : action;
            action = $(e.target).hasClass('fa-copy') ? "duplicate" : action;

            if(action != "edit") e.preventDefault();

            gameOnClick(this, gameNumber, action);
        }
    });
}

$("body").find("[aria-controls='mygames']").on('click', function(e) {
    showMyGames();
});

$("body").find("[aria-controls='community']").on('click', function(e) {
    showCommunityGames();
});

function gameOnClick(parent, gameNumber, action){
    if(action == "remove"){
        showRemoveWarning(parent, gameNumber);
    }else if(action == "edit"){
    }else if(action == "duplicate"){
        var copy = games[gameNumber].copy();
        games.push(copy);
        duplicatePlot(copy, function(id){
            copy.id = id;
            reorderPlots();
        });
    }
}

function reorderPlots(){
    showMyGames();
    showCommunityGames();
}

function showRemoveWarning(parent, gameNumber){
    $("#remove-warning").modal('show');
    $(".warning-action-remove").click(function(){
        $(parent).remove();
        removePlot(games[gameNumber]);
        games.splice(gameNumber, 1);
        reorderPlots();
        $("#remove-warning").modal('hide');
    });
    $(".warning-action-cancel").click(function(){
        $("#remove-warning").modal('hide');
    });
}<commit_msg>Fixet problem with plot removing and duplicating<commit_after>//var games = [];

showMyGames();

function showMyGames(){
    /*$("#mygames").empty();

    for(var game in games){
        appendGame("#mygames", games, game);
    }*/
    $("#mygames").empty();

    var text_to_append = '

';

    for(var game in games){
        text_to_append += appendGame("#mygames", games, game);
    }

    text_to_append += "

";

    $('#mygames').append(text_to_append);

    for(var game in games){
        setEvents("#mygames", games, game);
    }
}

function showCommunityGames(){
    $("#community").empty();

    var text_to_append = '

';

    for(var game in games){
        if(games[game].public) text_to_append += appendGame("#community", games, game);
    }

    text_to_append += "

";

    $('#community').append(text_to_append);

    for(var game in games){
        if(games[game].public) setEvents("#community", games, game);
    }
}

function appendGame(parent, games, index){
    var url = gameTypeToUrl(games[index].type) + ".php?id=" + games[index].id;

    var game = `

${games[index].name} - ${games[index].type}

${games[index].description}

                                <input data-index="${index}" class="pubpriv-toggle" type="checkbox" data-toggle="toggle" data-on="Public" data-off="Private" ${games[index].public?"checked":""}>

`;

    return game;
}

function setEvents(parent, games, index) {
    $('.pubpriv-toggle').bootstrapToggle();

    $('.pubpriv-toggle').change(function() {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            games[index].public = $(this).prop('checked');
            savePlot(games[index]);
            showCommunityGames();
        }
    });

    $(".gamerow .gameinfo").on('click', function(e) {
        var gameNumber = parseInt($(this).attr("data-index"));
        if(gameNumber == index) {
            var action = $(e.target).hasClass('fa-trash') ? "remove" : "";
            action = $(e.target).hasClass('fa-pencil') ? "edit" : action;
            action = $(e.target).hasClass('fa-copy') ? "duplicate" : action;

            if(action != "edit") e.preventDefault();

            gameOnClick(this, gameNumber, action);
        }
    });
}

$("body").find("[aria-controls='mygames']").on('click', function(e) {
    showMyGames();
});

$("body").find("[aria-controls='community']").on('click', function(e) {
    showCommunityGames();
});

function gameOnClick(parent, gameNumber, action){
    if(action == "remove"){
        showRemoveWarning(parent, gameNumber);
    }else if(action == "edit"){
    }else if(action == "duplicate"){
        var copy = games[gameNumber].copy();
        games.push(copy);
        duplicatePlot(copy, function(id){
            copy.id = id;
            window.location="?tab=community"
        });
    }
}

function reorderPlots(){
    showMyGames();
    showCommunityGames();
}

function showRemoveWarning(parent, gameNumber){
    $("#remove-warning").modal('show');
    $(".warning-action-remove").click(function() {
        $(parent).parent().remove();
        removePlot(games[gameNumber]);
        games.splice(gameNumber, 1);
        //reorderPlots();
        $("#remove-warning").modal('hide');
    });
    $(".warning-action-cancel").click(function(){
        $("#remove-warning").modal('hide');
    });
}<|endoftext|>


<commit_before>'use strict';

const fs = require('fs-extra');
const pkgUp = require('pkg-up');
const getDistTags = require('./fetch-dist-tags');
const calcDistTag = require('./calc-dist-tag');

module.exports = async function autoDistTag(cwd, options) {
  let pkgPath = await pkgUp(cwd);
  let pkg = await fs.readJson(pkgPath);
  let tags = await getDistTags(pkg.name);
  let tag = await calcDistTag(pkg.version, tags);

  if (
    options && options.write &&
    // skip writing to `package.json if an explicit publishConfig.tag is set
    !('publishConfig' in pkg && 'tag' in pkg.publishConfig) &&
    // skip writing to `package.json if the calculated tag is "latest" because it's the default anyway
    tag !== 'latest'
  ) {
    pkg.publishConfig = pkg.publishConfig || {};
    pkg.publishConfig.tag = tag;
    fs.writeJson(pkgPath, pkg, {spaces: 2});
  }

  return tag;
};
<commit_msg>package-json: Use async import<commit_after>'use strict';

const fs = require('fs-extra');
const getDistTags = require('./fetch-dist-tags');
const calcDistTag = require('./calc-dist-tag');

module.exports = async function autoDistTag(cwd, options) {
  const { pkgUp } = await import('pkg-up');

  let pkgPath = await pkgUp(cwd);
  let pkg = await fs.readJson(pkgPath);
  let tags = await getDistTags(pkg.name);
  let tag = await calcDistTag(pkg.version, tags);

  if (
    options && options.write &&
    // skip writing to `package.json if an explicit publishConfig.tag is set
    !('publishConfig' in pkg && 'tag' in pkg.publishConfig) &&
    // skip writing to `package.json if the calculated tag is "latest" because it's the default anyway
    tag !== 'latest'
  ) {
    pkg.publishConfig = pkg.publishConfig || {};
    pkg.publishConfig.tag = tag;
    fs.writeJson(pkgPath, pkg, {spaces: 2});
  }

  return tag;
};
<|endoftext|>


<commit_before>/*
Copyright 2018 New Vector Ltd

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

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

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

/** @module auto-discovery */

import Promise from 'bluebird';
const logger = require("./logger");
import { URL as NodeURL } from "url";

// Dev note: Auto discovery is part of the spec.
// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery

/**
 * Description for what an automatically discovered client configuration
 * would look like. Although this is a class, it is recommended that it
 * be treated as an interface definition rather than as a class.
 *
 * Additional properties than those defined here may be present, and
 * should follow the Java package naming convention.
 */
class DiscoveredClientConfig { // eslint-disable-line no-unused-vars
    // Dev note: this is basically a copy/paste of the .well-known response
    // object as defined in the spec. It does have additional information,
    // however. Overall, this exists to serve as a place for documentation
    // and not functionality.
    // See https://matrix.org/docs/spec/client_server/r0.4.0.html#get-well-known-matrix-client

    constructor() {
        /**
         * The homeserver configuration the client should use. This will
         * always be present on the object.
         * @type {{state: string, base_url: string}} The configuration.
         */
        this["m.homeserver"] = {
            /**
             * The lookup result state. If this is anything other than
             * AutoDiscovery.SUCCESS then base_url may be falsey. Additionally,
             * if this is not AutoDiscovery.SUCCESS then the client should
             * assume the other properties in the client config (such as
             * the identity server configuration) are not valid.
             */
            state: AutoDiscovery.PROMPT,

            /**
             * If the state is AutoDiscovery.FAIL_ERROR or .FAIL_PROMPT
             * then this will contain a human-readable (English) message
             * for what went wrong. If the state is none of those previously
             * mentioned, this will be falsey.
             */
            error: "Something went wrong",

            /**
             * The base URL clients should use to talk to the homeserver,
             * particularly for the login process. May be falsey if the
             * state is not AutoDiscovery.SUCCESS.
             */
            base_url: "https://matrix.org",
        };

        /**
         * The identity server configuration the client should use. This
         * will always be present on teh object.
         * @type {{state: string, base_url: string}} The configuration.
         */
        this["m.identity_server"] = {
            /**
             * The lookup result state. If this is anything other than
             * AutoDiscovery.SUCCESS then base_url may be falsey.
             */
            state: AutoDiscovery.PROMPT,

            /**
             * The base URL clients should use for interacting with the
             * identity server. May be falsey if the state is not
             * AutoDiscovery.SUCCESS.
             */
            base_url: "https://vector.im",
        };
    }
}

/**
 * Utilities for automatically discovery resources, such as homeservers
 * for users to log in to.
 */
export class AutoDiscovery {
    // Dev note: the constants defined here are related to but not
    // exactly the same as those in the spec. This is to hopefully
    // translate the meaning of the states in the spec, but also
    // support our own if needed.

    /**
     * The auto discovery failed. The client is expected to communicate
     * the error to the user and refuse logging in.
     * @return {string}
     * @constructor
     */
    static get FAIL_ERROR() { return "FAIL_ERROR"; }

    /**
     * The auto discovery failed, however the client may still recover
     * from the problem. The client is recommended to that the same
     * action it would for PROMPT while also warning the user about
     * what went wrong. The client may also treat this the same as
     * a FAIL_ERROR state.
     * @return {string}
     * @constructor
     */
    static get FAIL_PROMPT() { return "FAIL_PROMPT"; }

    /**
     * The auto discovery didn't fail but did not find anything of
     * interest. The client is expected to prompt the user for more
     * information, or fail if it prefers.
     * @return {string}
     * @constructor
     */
    static get PROMPT() { return "PROMPT"; }

    /**
     * The auto discovery was successful.
     * @return {string}
     * @constructor
     */
    static get SUCCESS() { return "SUCCESS"; }

    /**
     * Attempts to automatically discover client configuration information
     * prior to logging in. Such information includes the homeserver URL
     * and identity server URL the client would want. Additional details
     * may also be discovered, and will be transparently included in the
     * response object unaltered.
     * @param {string} domain The homeserver domain to perform discovery
     * on. For example, "matrix.org".
     * @return {Promise<DiscoveredClientConfig>} Resolves to the discovered
     * configuration, which may include error states. Rejects on unexpected
     * failure, not when discovery fails.
     */
    static async findClientConfig(domain) {
        if (!domain || typeof(domain) !== "string" || domain.length === 0) {
            throw new Error("'domain' must be a string of non-zero length");
        }

        // We use a .well-known lookup for all cases. According to the spec, we
        // can do other discovery mechanisms if we want such as custom lookups
        // however we won't bother with that here (mostly because the spec only
        // supports .well-known right now).
        //
        // By using .well-known, we need to ensure we at least pull out a URL
        // for the homeserver. We don't really need an identity server configuration
        // but will return one anyways (with state PROMPT) to make development
        // easier for clients. If we can't get a homeserver URL, all bets are
        // off on the rest of the config and we'll assume it is invalid too.

        // We default to an error state to make the first few checks easier to
        // write. We'll update the properties of this object over the duration
        // of this function.
        const clientConfig = {
            "m.homeserver": {
                state: AutoDiscovery.FAIL_ERROR,
                error: "Invalid homeserver discovery response",
                base_url: null,
            },
            "m.identity_server": {
                // Technically, we don't have a problem with the identity server
                // config at this point.
                state: AutoDiscovery.PROMPT,
                error: null,
                base_url: null,
            },
        };

        // Step 1: Actually request the .well-known JSON file and make sure it
        // at least has a homeserver definition.
        const wellknown = await this._fetchWellKnownObject(
            `https://${domain}/.well-known/matrix/client`,
        );
        if (!wellknown || wellknown.action !== "SUCCESS"
            || !wellknown.raw["m.homeserver"]
            || !wellknown.raw["m.homeserver"]["base_url"]) {
            logger.error("No m.homeserver key in well-known response");
            if (wellknown.reason) logger.error(wellknown.reason);
            if (wellknown.action === "IGNORE") {
                clientConfig["m.homeserver"] = {
                    state: AutoDiscovery.PROMPT,
                    error: null,
                    base_url: null,
                };
            } else {
                // this can only ever be FAIL_PROMPT at this point.
                clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
                clientConfig["m.homeserver"].error =
                    "Failed to get autodiscovery configuration from server";
            }
            return Promise.resolve(clientConfig);
        }

        // Step 2: Make sure the homeserver URL is valid *looking*. We'll make
        // sure it points to a homeserver in Step 3.
        const hsUrl = this._sanitizeWellKnownUrl(
            wellknown.raw["m.homeserver"]["base_url"],
        );
        if (!hsUrl) {
            logger.error("Invalid base_url for m.homeserver");
            clientConfig["m.homeserver"].error = "Invalid base_url for m.homeserver";
            return Promise.resolve(clientConfig);
        }

        // Step 3: Make sure the homeserver URL points to a homeserver.
        const hsVersions = await this._fetchWellKnownObject(
            `${hsUrl}/_matrix/client/versions`,
        );
        if (!hsVersions || !hsVersions.raw["versions"]) {
            logger.error("Invalid /versions response");
            clientConfig["m.homeserver"].error =
                "Homeserver URL does not appear to be a valid Matrix homeserver";
            return Promise.resolve(clientConfig);
        }

        // Step 4: Now that the homeserver looks valid, update our client config.
        clientConfig["m.homeserver"] = {
            state: AutoDiscovery.SUCCESS,
            error: null,
            base_url: hsUrl,
        };

        // Step 5: Try to pull out the identity server configuration
        let isUrl = "";
        if (wellknown.raw["m.identity_server"]) {
            // We prepare a failing identity server response to save lines later
            // in this branch. Note that we also fail the homeserver check in the
            // object because according to the spec we're supposed to FAIL_ERROR
            // if *anything* goes wrong with the IS validation, including invalid
            // format. This means we're supposed to stop discovery completely.
            const failingClientConfig = {
                "m.homeserver": {
                    state: AutoDiscovery.FAIL_ERROR,
                    error: "Invalid identity server discovery response",

                    // We'll provide the base_url that was previously valid for
                    // debugging purposes.
                    base_url: clientConfig["m.homeserver"].base_url,
                },
                "m.identity_server": {
                    state: AutoDiscovery.FAIL_ERROR,
                    error: "Invalid identity server discovery response",
                    base_url: null,
                },
            };

            // Step 5a: Make sure the URL is valid *looking*. We'll make sure it
            // points to an identity server in Step 5b.
            isUrl = this._sanitizeWellKnownUrl(
                wellknown.raw["m.identity_server"]["base_url"],
            );
            if (!isUrl) {
                logger.error("Invalid base_url for m.identity_server");
                failingClientConfig["m.identity_server"].error =
                    "Invalid base_url for m.identity_server";
                return Promise.resolve(failingClientConfig);
            }

            // Step 5b: Verify there is an identity server listening on the provided
            // URL.
            const isResponse = await this._fetchWellKnownObject(
                `${isUrl}/_matrix/identity/api/v1`,
            );
            if (!isResponse || !isResponse.raw || isResponse.action !== "SUCCESS") {
                logger.error("Invalid /api/v1 response");
                failingClientConfig["m.identity_server"].error =
                    "Identity server URL does not appear to be a valid identity server";
                return Promise.resolve(failingClientConfig);
            }
        }

        // Step 6: Now that the identity server is valid, or never existed,
        // populate the IS section.
        if (isUrl && isUrl.length > 0) {
            clientConfig["m.identity_server"] = {
                state: AutoDiscovery.SUCCESS,
                error: null,
                base_url: isUrl,
            };
        }

        // Step 7: Copy any other keys directly into the clientConfig. This is for
        // things like custom configuration of services.
        Object.keys(wellknown.raw)
            .filter((k) => k !== "m.homeserver" && k !== "m.identity_server")
            .map((k) => clientConfig[k] = wellknown.raw[k]);

        // Step 8: Give the config to the caller (finally)
        return Promise.resolve(clientConfig);
    }

    /**
     * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and
     * is suitable for the requirements laid out by .well-known auto discovery.
     * If valid, the URL will also be stripped of any trailing slashes.
     * @param {string} url The potentially invalid URL to sanitize.
     * @return {string|boolean} The sanitized URL or a falsey value if the URL is invalid.
     * @private
     */
    static _sanitizeWellKnownUrl(url) {
        if (!url) return false;

        try {
            // We have to try and parse the URL using the NodeJS URL
            // library if we're on NodeJS and use the browser's URL
            // library when we're in a browser. To accomplish this, we
            // try the NodeJS version first and fall back to the browser.
            let parsed = null;
            try {
                if (NodeURL) parsed = new NodeURL(url);
                else parsed = new URL(url);
            } catch (e) {
                parsed = new URL(url);
            }

            if (!parsed || !parsed.hostname) return false;
            if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;

            const port = parsed.port ? `:${parsed.port}` : "";
            const path = parsed.pathname ? parsed.pathname : "";
            let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;
            if (saferUrl.endsWith("/")) {
                saferUrl = saferUrl.substring(0, saferUrl.length - 1);
            }
            return saferUrl;
        } catch (e) {
            logger.error(e);
            return false;
        }
    }

    /**
     * Fetches a JSON object from a given URL, as expected by all .well-known
     * related lookups. If the server gives a 404 then the `action` will be
     * IGNORE. If the server returns something that isn't JSON, the `action`
     * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.
     *
     * The returned object will be a result of the call in object form with
     * the following properties:
     *   raw: The JSON object returned by the server.
     *   action: One of SUCCESS, IGNORE, or FAIL_PROMPT.
     *   reason: Relatively human readable description of what went wrong.
     *   error: The actual Error, if one exists.
     * @param {string} url The URL to fetch a JSON object from.
     * @return {Promise<object>} Resolves to the returned state.
     * @private
     */
    static async _fetchWellKnownObject(url) {
        return new Promise(function(resolve, reject) {
            const request = require("./matrix").getRequest();
            if (!request) throw new Error("No request library available");
            request(
                { method: "GET", uri: url },
                (err, response, body) => {
                    if (err || response.statusCode < 200 || response.statusCode >= 300) {
                        let action = "FAIL_PROMPT";
                        let reason = (err ? err.message : null) || "General failure";
                        if (response.statusCode === 404) {
                            action = "IGNORE";
                            reason = "No .well-known JSON file found";
                        }
                        resolve({raw: {}, action: action, reason: reason, error: err});
                        return;
                    }

                    try {
                        resolve({raw: JSON.parse(body), action: "SUCCESS"});
                    } catch (e) {
                        let reason = "General failure";
                        if (e.name === "SyntaxError") reason = "Invalid JSON";
                        resolve({
                            raw: {},
                            action: "FAIL_PROMPT",
                            reason: reason, error: e,
                        });
                    }
                },
            );
        });
    }
}
<commit_msg>Support being fed a .well-known config object for validation<commit_after>/*
Copyright 2018 New Vector Ltd

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

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

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

/** @module auto-discovery */

import Promise from 'bluebird';
const logger = require("./logger");
import { URL as NodeURL } from "url";

// Dev note: Auto discovery is part of the spec.
// See: https://matrix.org/docs/spec/client_server/r0.4.0.html#server-discovery

/**
 * Description for what an automatically discovered client configuration
 * would look like. Although this is a class, it is recommended that it
 * be treated as an interface definition rather than as a class.
 *
 * Additional properties than those defined here may be present, and
 * should follow the Java package naming convention.
 */
class DiscoveredClientConfig { // eslint-disable-line no-unused-vars
    // Dev note: this is basically a copy/paste of the .well-known response
    // object as defined in the spec. It does have additional information,
    // however. Overall, this exists to serve as a place for documentation
    // and not functionality.
    // See https://matrix.org/docs/spec/client_server/r0.4.0.html#get-well-known-matrix-client

    constructor() {
        /**
         * The homeserver configuration the client should use. This will
         * always be present on the object.
         * @type {{state: string, base_url: string}} The configuration.
         */
        this["m.homeserver"] = {
            /**
             * The lookup result state. If this is anything other than
             * AutoDiscovery.SUCCESS then base_url may be falsey. Additionally,
             * if this is not AutoDiscovery.SUCCESS then the client should
             * assume the other properties in the client config (such as
             * the identity server configuration) are not valid.
             */
            state: AutoDiscovery.PROMPT,

            /**
             * If the state is AutoDiscovery.FAIL_ERROR or .FAIL_PROMPT
             * then this will contain a human-readable (English) message
             * for what went wrong. If the state is none of those previously
             * mentioned, this will be falsey.
             */
            error: "Something went wrong",

            /**
             * The base URL clients should use to talk to the homeserver,
             * particularly for the login process. May be falsey if the
             * state is not AutoDiscovery.SUCCESS.
             */
            base_url: "https://matrix.org",
        };

        /**
         * The identity server configuration the client should use. This
         * will always be present on teh object.
         * @type {{state: string, base_url: string}} The configuration.
         */
        this["m.identity_server"] = {
            /**
             * The lookup result state. If this is anything other than
             * AutoDiscovery.SUCCESS then base_url may be falsey.
             */
            state: AutoDiscovery.PROMPT,

            /**
             * The base URL clients should use for interacting with the
             * identity server. May be falsey if the state is not
             * AutoDiscovery.SUCCESS.
             */
            base_url: "https://vector.im",
        };
    }
}

/**
 * Utilities for automatically discovery resources, such as homeservers
 * for users to log in to.
 */
export class AutoDiscovery {
    // Dev note: the constants defined here are related to but not
    // exactly the same as those in the spec. This is to hopefully
    // translate the meaning of the states in the spec, but also
    // support our own if needed.

    /**
     * The auto discovery failed. The client is expected to communicate
     * the error to the user and refuse logging in.
     * @return {string}
     * @constructor
     */
    static get FAIL_ERROR() { return "FAIL_ERROR"; }

    /**
     * The auto discovery failed, however the client may still recover
     * from the problem. The client is recommended to that the same
     * action it would for PROMPT while also warning the user about
     * what went wrong. The client may also treat this the same as
     * a FAIL_ERROR state.
     * @return {string}
     * @constructor
     */
    static get FAIL_PROMPT() { return "FAIL_PROMPT"; }

    /**
     * The auto discovery didn't fail but did not find anything of
     * interest. The client is expected to prompt the user for more
     * information, or fail if it prefers.
     * @return {string}
     * @constructor
     */
    static get PROMPT() { return "PROMPT"; }

    /**
     * The auto discovery was successful.
     * @return {string}
     * @constructor
     */
    static get SUCCESS() { return "SUCCESS"; }

    /**
     * Validates and verifies client configuration information for purposes
     * of logging in. Such information includes the homeserver URL
     * and identity server URL the client would want. Additional details
     * may also be included, and will be transparently brought into the
     * response object unaltered.
     * @param {string} wellknown The configuration object itself, as returned
     * by the .well-known auto-discovery endpoint.
     * @return {Promise<DiscoveredClientConfig>} Resolves to the verified
     * configuration, which may include error states. Rejects on unexpected
     * failure, not when verification fails.
     */
    static async fromDiscoveryConfig(wellknown) {
        // Step 1 is to get the config, which is provided to us here.

        // We default to an error state to make the first few checks easier to
        // write. We'll update the properties of this object over the duration
        // of this function.
        const clientConfig = {
            "m.homeserver": {
                state: AutoDiscovery.FAIL_ERROR,
                error: "Invalid homeserver discovery response",
                base_url: null,
            },
            "m.identity_server": {
                // Technically, we don't have a problem with the identity server
                // config at this point.
                state: AutoDiscovery.PROMPT,
                error: null,
                base_url: null,
            },
        };

        if (!wellknown ||
            !wellknown["m.homeserver"] ||
            !wellknown["m.homeserver"]["base_url"]) {
            logger.error("No m.homeserver key/base_url in config");

            clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
            clientConfig["m.homeserver"].error = "Invalid base_url for m.homeserver";

            return Promise.resolve(clientConfig);
        }

        // Step 2: Make sure the homeserver URL is valid *looking*. We'll make
        // sure it points to a homeserver in Step 3.
        const hsUrl = this._sanitizeWellKnownUrl(
            wellknown["m.homeserver"]["base_url"],
        );
        if (!hsUrl) {
            logger.error("Invalid base_url for m.homeserver");
            clientConfig["m.homeserver"].error = "Invalid base_url for m.homeserver";
            return Promise.resolve(clientConfig);
        }

        // Step 3: Make sure the homeserver URL points to a homeserver.
        const hsVersions = await this._fetchWellKnownObject(
            `${hsUrl}/_matrix/client/versions`,
        );
        if (!hsVersions || !hsVersions.raw["versions"]) {
            logger.error("Invalid /versions response");
            clientConfig["m.homeserver"].error =
                "Homeserver URL does not appear to be a valid Matrix homeserver";
            return Promise.resolve(clientConfig);
        }

        // Step 4: Now that the homeserver looks valid, update our client config.
        clientConfig["m.homeserver"] = {
            state: AutoDiscovery.SUCCESS,
            error: null,
            base_url: hsUrl,
        };

        // Step 5: Try to pull out the identity server configuration
        let isUrl = "";
        if (wellknown["m.identity_server"]) {
            // We prepare a failing identity server response to save lines later
            // in this branch. Note that we also fail the homeserver check in the
            // object because according to the spec we're supposed to FAIL_ERROR
            // if *anything* goes wrong with the IS validation, including invalid
            // format. This means we're supposed to stop discovery completely.
            const failingClientConfig = {
                "m.homeserver": {
                    state: AutoDiscovery.FAIL_ERROR,
                    error: "Invalid identity server discovery response",

                    // We'll provide the base_url that was previously valid for
                    // debugging purposes.
                    base_url: clientConfig["m.homeserver"].base_url,
                },
                "m.identity_server": {
                    state: AutoDiscovery.FAIL_ERROR,
                    error: "Invalid identity server discovery response",
                    base_url: null,
                },
            };

            // Step 5a: Make sure the URL is valid *looking*. We'll make sure it
            // points to an identity server in Step 5b.
            isUrl = this._sanitizeWellKnownUrl(
                wellknown["m.identity_server"]["base_url"],
            );
            if (!isUrl) {
                logger.error("Invalid base_url for m.identity_server");
                failingClientConfig["m.identity_server"].error =
                    "Invalid base_url for m.identity_server";
                return Promise.resolve(failingClientConfig);
            }

            // Step 5b: Verify there is an identity server listening on the provided
            // URL.
            const isResponse = await this._fetchWellKnownObject(
                `${isUrl}/_matrix/identity/api/v1`,
            );
            if (!isResponse || !isResponse.raw || isResponse.action !== "SUCCESS") {
                logger.error("Invalid /api/v1 response");
                failingClientConfig["m.identity_server"].error =
                    "Identity server URL does not appear to be a valid identity server";
                return Promise.resolve(failingClientConfig);
            }
        }

        // Step 6: Now that the identity server is valid, or never existed,
        // populate the IS section.
        if (isUrl && isUrl.length > 0) {
            clientConfig["m.identity_server"] = {
                state: AutoDiscovery.SUCCESS,
                error: null,
                base_url: isUrl,
            };
        }

        // Step 7: Copy any other keys directly into the clientConfig. This is for
        // things like custom configuration of services.
        Object.keys(wellknown)
            .map((k) => {
                if (k === "m.homeserver" || k === "m.identity_server") {
                    // Only copy selected parts of the config to avoid overwriting
                    // important information.
                    const notProps = ["error", "state", "base_url"];
                    for (const prop of Object.keys(wellknown[k])) {
                        if (notProps.includes(prop)) continue;
                        clientConfig[k][prop] = wellknown[k][prop];
                    }
                } else {
                    // Just copy the whole thing over otherwise
                    clientConfig[k] = wellknown[k];
                }
            });

        // Step 8: Give the config to the caller (finally)
        return Promise.resolve(clientConfig);
    }

    /**
     * Attempts to automatically discover client configuration information
     * prior to logging in. Such information includes the homeserver URL
     * and identity server URL the client would want. Additional details
     * may also be discovered, and will be transparently included in the
     * response object unaltered.
     * @param {string} domain The homeserver domain to perform discovery
     * on. For example, "matrix.org".
     * @return {Promise<DiscoveredClientConfig>} Resolves to the discovered
     * configuration, which may include error states. Rejects on unexpected
     * failure, not when discovery fails.
     */
    static async findClientConfig(domain) {
        if (!domain || typeof(domain) !== "string" || domain.length === 0) {
            throw new Error("'domain' must be a string of non-zero length");
        }

        // We use a .well-known lookup for all cases. According to the spec, we
        // can do other discovery mechanisms if we want such as custom lookups
        // however we won't bother with that here (mostly because the spec only
        // supports .well-known right now).
        //
        // By using .well-known, we need to ensure we at least pull out a URL
        // for the homeserver. We don't really need an identity server configuration
        // but will return one anyways (with state PROMPT) to make development
        // easier for clients. If we can't get a homeserver URL, all bets are
        // off on the rest of the config and we'll assume it is invalid too.

        // We default to an error state to make the first few checks easier to
        // write. We'll update the properties of this object over the duration
        // of this function.
        const clientConfig = {
            "m.homeserver": {
                state: AutoDiscovery.FAIL_ERROR,
                error: "Invalid homeserver discovery response",
                base_url: null,
            },
            "m.identity_server": {
                // Technically, we don't have a problem with the identity server
                // config at this point.
                state: AutoDiscovery.PROMPT,
                error: null,
                base_url: null,
            },
        };

        // Step 1: Actually request the .well-known JSON file and make sure it
        // at least has a homeserver definition.
        const wellknown = await this._fetchWellKnownObject(
            `https://${domain}/.well-known/matrix/client`,
        );
        if (!wellknown || wellknown.action !== "SUCCESS") {
            logger.error("No m.homeserver key in well-known response");
            if (wellknown.reason) logger.error(wellknown.reason);
            if (wellknown.action === "IGNORE") {
                clientConfig["m.homeserver"] = {
                    state: AutoDiscovery.PROMPT,
                    error: null,
                    base_url: null,
                };
            } else {
                // this can only ever be FAIL_PROMPT at this point.
                clientConfig["m.homeserver"].state = AutoDiscovery.FAIL_PROMPT;
                clientConfig["m.homeserver"].error =
                    "Failed to get autodiscovery configuration from server";
            }
            return Promise.resolve(clientConfig);
        }

        // Step 2: Validate and parse the config
        return AutoDiscovery.fromDiscoveryConfig(wellknown.raw);
    }

    /**
     * Sanitizes a given URL to ensure it is either an HTTP or HTTP URL and
     * is suitable for the requirements laid out by .well-known auto discovery.
     * If valid, the URL will also be stripped of any trailing slashes.
     * @param {string} url The potentially invalid URL to sanitize.
     * @return {string|boolean} The sanitized URL or a falsey value if the URL is invalid.
     * @private
     */
    static _sanitizeWellKnownUrl(url) {
        if (!url) return false;

        try {
            // We have to try and parse the URL using the NodeJS URL
            // library if we're on NodeJS and use the browser's URL
            // library when we're in a browser. To accomplish this, we
            // try the NodeJS version first and fall back to the browser.
            let parsed = null;
            try {
                if (NodeURL) parsed = new NodeURL(url);
                else parsed = new URL(url);
            } catch (e) {
                parsed = new URL(url);
            }

            if (!parsed || !parsed.hostname) return false;
            if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;

            const port = parsed.port ? `:${parsed.port}` : "";
            const path = parsed.pathname ? parsed.pathname : "";
            let saferUrl = `${parsed.protocol}//${parsed.hostname}${port}${path}`;
            if (saferUrl.endsWith("/")) {
                saferUrl = saferUrl.substring(0, saferUrl.length - 1);
            }
            return saferUrl;
        } catch (e) {
            logger.error(e);
            return false;
        }
    }

    /**
     * Fetches a JSON object from a given URL, as expected by all .well-known
     * related lookups. If the server gives a 404 then the `action` will be
     * IGNORE. If the server returns something that isn't JSON, the `action`
     * will be FAIL_PROMPT. For any other failure the `action` will be FAIL_PROMPT.
     *
     * The returned object will be a result of the call in object form with
     * the following properties:
     *   raw: The JSON object returned by the server.
     *   action: One of SUCCESS, IGNORE, or FAIL_PROMPT.
     *   reason: Relatively human readable description of what went wrong.
     *   error: The actual Error, if one exists.
     * @param {string} url The URL to fetch a JSON object from.
     * @return {Promise<object>} Resolves to the returned state.
     * @private
     */
    static async _fetchWellKnownObject(url) {
        return new Promise(function(resolve, reject) {
            const request = require("./matrix").getRequest();
            if (!request) throw new Error("No request library available");
            request(
                { method: "GET", uri: url },
                (err, response, body) => {
                    if (err || response.statusCode < 200 || response.statusCode >= 300) {
                        let action = "FAIL_PROMPT";
                        let reason = (err ? err.message : null) || "General failure";
                        if (response.statusCode === 404) {
                            action = "IGNORE";
                            reason = "No .well-known JSON file found";
                        }
                        resolve({raw: {}, action: action, reason: reason, error: err});
                        return;
                    }

                    try {
                        resolve({raw: JSON.parse(body), action: "SUCCESS"});
                    } catch (e) {
                        let reason = "General failure";
                        if (e.name === "SyntaxError") reason = "Invalid JSON";
                        resolve({
                            raw: {},
                            action: "FAIL_PROMPT",
                            reason: reason, error: e,
                        });
                    }
                },
            );
        });
    }
}
<|endoftext|>


<commit_before>'use strict';

var sharp  = require('sharp');
var env    = require('../config/environment_vars');
var map    = require('map-stream');

module.exports = function () {

  return map( function (image, callback) {
    var normalizedFormat, r;

    // pass through if there is an error
    if (image.isError()) {
      return callback(null, image);
    }

    // let this pass through if we are requesting the metadata as JSON
    if (image.modifiers.action === 'json'){
      image.log.log('normalize: json metadata call');
      return callback(null, image);
    }

    switch (image.format) {
      case 'tiff':
        normalizedFormat = 'png';
        break;
      case 'gif':
        normalizedFormat = 'png';
        break;
      default:
        normalizedFormat = null;
        break;
    }

    if (normalizedFormat === null) {
      image.log.log('normalize: no normalize');
      return callback(null, image);
    }

    image.log.time('normalize:' + normalizedFormat);

    r = sharp(image.contents);

    r.toFormat(normalizedFormat);

    // write out the normalized image to buffer and pass it on
    r.toBuffer( function (err, buffer) {
      if (err) {
        image.log.error('normalize error', err);
        image.error = new Error(err);
      }
      else {
        image.contents = buffer;
      }

      image.log.timeEnd('normalize:' + normalizedFormat);
      callback(null, image);
    });
  });

};
<commit_msg>Use bold format for "no normalize" log message<commit_after>'use strict';

var sharp  = require('sharp');
var env    = require('../config/environment_vars');
var map    = require('map-stream');

module.exports = function () {

  return map( function (image, callback) {
    var normalizedFormat, r;

    // pass through if there is an error
    if (image.isError()) {
      return callback(null, image);
    }

    // let this pass through if we are requesting the metadata as JSON
    if (image.modifiers.action === 'json'){
      image.log.log('normalize: json metadata call');
      return callback(null, image);
    }

    switch (image.format) {
      case 'tiff':
        normalizedFormat = 'png';
        break;
      case 'gif':
        normalizedFormat = 'png';
        break;
      default:
        normalizedFormat = null;
        break;
    }

    if (normalizedFormat === null) {
      image.log.log('normalize:', image.log.colors.bold('no normalize'));
      return callback(null, image);
    }

    image.log.time('normalize:' + normalizedFormat);

    r = sharp(image.contents);

    r.toFormat(normalizedFormat);

    // write out the normalized image to buffer and pass it on
    r.toBuffer( function (err, buffer) {
      if (err) {
        image.log.error('normalize error', err);
        image.error = new Error(err);
      }
      else {
        image.contents = buffer;
      }

      image.log.timeEnd('normalize:' + normalizedFormat);
      callback(null, image);
    });
  });

};
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');
var expect = require('chai').expect;
var Grid = require('../app/scripts/models/grid');
var Player = require('../app/scripts/models/player');
var Chip = require('../app/scripts/models/chip');

describe('grid', function () {

  it('should initialize', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    expect(grid.columnCount).to.equal(9);
    expect(grid.rowCount).to.equal(8);
    expect(grid.columns).to.have.length(9);
    grid.columns.forEach(function (column) {
      expect(column).to.have.length(0);
    });
  });

  it('should know when it is full', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    var player = new Player({color: 'red', name: 'Bob'});
    _.times(9, function (c) {
      _.times(8, function () {
        grid.columns[c].push(new Chip({player: player}));
      });
    });
    expect(grid.checkIfFull()).to.be.true;
  });

  it('should know when it is not full', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    var player = new Player({color: 'red', name: 'Bob'});
    _.times(9, function (c) {
      _.times(7, function () {
        grid.columns[c].push(new Chip({player: player}));
      });
    });
    expect(grid.checkIfFull()).to.be.false;
  });

  it('should reset', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    var player = new Player({color: 'red', name: 'Bob'});
    _.times(9, function (c) {
      _.times(6, function () {
        grid.columns[c].push(new Chip({player: player}));
      });
    });
    grid.resetGrid();
    grid.columns.forEach(function (column) {
      expect(column).to.have.length(0);
    });
  });

  it('should place chip and set its column/row', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 6
    });
    var player = new Player({color: 'blue'});
    grid.placeChip({chip: new Chip({player: player}), column: 2});
    grid.placeChip({chip: new Chip({player: player}), column: 2});
    expect(grid.columns[2][0]).to.be.an.instanceof(Chip);
    expect(grid.columns[2][0]).to.have.property('column', 2);
    expect(grid.columns[2][0]).to.have.property('row', 0);
    expect(grid.columns[2][1]).to.be.an.instanceof(Chip);
    expect(grid.columns[2][1]).to.have.property('column', 2);
    expect(grid.columns[2][1]).to.have.property('row', 1);
  });

});
<commit_msg>Flip parameter order in Grid.placeChip test calls<commit_after>'use strict';

var _ = require('underscore');
var expect = require('chai').expect;
var Grid = require('../app/scripts/models/grid');
var Player = require('../app/scripts/models/player');
var Chip = require('../app/scripts/models/chip');

describe('grid', function () {

  it('should initialize', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    expect(grid.columnCount).to.equal(9);
    expect(grid.rowCount).to.equal(8);
    expect(grid.columns).to.have.length(9);
    grid.columns.forEach(function (column) {
      expect(column).to.have.length(0);
    });
  });

  it('should know when it is full', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    var player = new Player({color: 'red', name: 'Bob'});
    _.times(9, function (c) {
      _.times(8, function () {
        grid.columns[c].push(new Chip({player: player}));
      });
    });
    expect(grid.checkIfFull()).to.be.true;
  });

  it('should know when it is not full', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    var player = new Player({color: 'red', name: 'Bob'});
    _.times(9, function (c) {
      _.times(7, function () {
        grid.columns[c].push(new Chip({player: player}));
      });
    });
    expect(grid.checkIfFull()).to.be.false;
  });

  it('should reset', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 8
    });
    var player = new Player({color: 'red', name: 'Bob'});
    _.times(9, function (c) {
      _.times(6, function () {
        grid.columns[c].push(new Chip({player: player}));
      });
    });
    grid.resetGrid();
    grid.columns.forEach(function (column) {
      expect(column).to.have.length(0);
    });
  });

  it('should place chip and set its column/row', function () {
    var grid = new Grid({
      columnCount: 9,
      rowCount: 6
    });
    var player = new Player({color: 'blue'});
    grid.placeChip({column: 2, chip: new Chip({player: player})});
    grid.placeChip({column: 2, chip: new Chip({player: player})});
    expect(grid.columns[2][0]).to.be.an.instanceof(Chip);
    expect(grid.columns[2][0]).to.have.property('column', 2);
    expect(grid.columns[2][0]).to.have.property('row', 0);
    expect(grid.columns[2][1]).to.be.an.instanceof(Chip);
    expect(grid.columns[2][1]).to.have.property('column', 2);
    expect(grid.columns[2][1]).to.have.property('row', 1);
  });

});
<|endoftext|>


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

  // gets the rendered style for an element
  $$.styfn.getRenderedStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;
      var cy = this._private.cy;
      var zoom = cy.zoom();

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          var val = styleProp.unitless ? styleProp.strValue : (styleProp.pxValue * zoom) + 'px';
          rstyle[ prop.name ] = val;
          rstyle[ $$.util.dash2camel(prop.name) ] = val;
        }
      }

      return rstyle;
    }
  };

  // gets the raw style for an element
  $$.styfn.getRawStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          rstyle[ prop.name ] = styleProp.strValue;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp.strValue;
        }
      }

      return rstyle;
    }
  };

  // gets the value style for an element (useful for things like animations)
  $$.styfn.getValueStyle = function( ele ){
    var rstyle = {};
    var style;
    var isEle = $$.is.element(ele);

    if( isEle ){
      style = ele._private.style;
    } else {
      style = ele; // just passed the style itself
    }

    if( style ){
      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ] || style[ $$.util.dash2camel(prop.name) ];

        if( styleProp !== undefined && !$$.is.plainObject( styleProp ) ){ // then make a prop of it
          styleProp = this.parse(prop.name, styleProp);
        }

        if( styleProp ){
          rstyle[ prop.name ] = styleProp;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp;
        }
      }
    }

    return rstyle;
  };

  $$.styfn.getPropsList = function( propsObj ){
    var rstyle = [];
    var style = propsObj;
    var props = $$.style.properties;

    if( style ){
      for( var name in style ){
        var val = style[name];
        var prop = props[name] || props[ $$.util.camel2dash(name) ];
        var styleProp = this.parse( prop.name, val );

        rstyle.push( styleProp );
      }
    }

    return rstyle;
  };

})( cytoscape );
<commit_msg> Transitions can exponentially speed up with style property caching #1057<commit_after>;(function($$){ 'use strict';

  // gets the rendered style for an element
  $$.styfn.getRenderedStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;
      var cy = this._private.cy;
      var zoom = cy.zoom();

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          var val = styleProp.unitless ? styleProp.strValue : (styleProp.pxValue * zoom) + 'px';
          rstyle[ prop.name ] = val;
          rstyle[ $$.util.dash2camel(prop.name) ] = val;
        }
      }

      return rstyle;
    }
  };

  // gets the raw style for an element
  $$.styfn.getRawStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          rstyle[ prop.name ] = styleProp.strValue;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp.strValue;
        }
      }

      return rstyle;
    }
  };

  // gets the value style for an element (useful for things like animations)
  $$.styfn.getValueStyle = function( ele ){
    var rstyle = {};
    var style;
    var isEle = $$.is.element(ele);

    if( isEle ){
      style = ele._private.style;
    } else {
      style = ele; // just passed the style itself
    }

    if( style ){
      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ] || style[ $$.util.dash2camel(prop.name) ];

        if( styleProp !== undefined ){ // then make a prop of it
          if( $$.is.plainObject( styleProp ) ){
            styleProp = this.parse( prop.name, styleProp.strValue );
          } else {
            styleProp = this.parse( prop.name, styleProp );
          }
        }

        if( styleProp ){
          rstyle[ prop.name ] = styleProp;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp;
        }
      }
    }

    return rstyle;
  };

  $$.styfn.getPropsList = function( propsObj ){
    var rstyle = [];
    var style = propsObj;
    var props = $$.style.properties;

    if( style ){
      for( var name in style ){
        var val = style[name];
        var prop = props[name] || props[ $$.util.camel2dash(name) ];
        var styleProp = this.parse( prop.name, val );

        rstyle.push( styleProp );
      }
    }

    return rstyle;
  };

})( cytoscape );
<|endoftext|>


<commit_before>const chai = require('chai')
const expect = chai.expect
const path = require('path')
const fs = require('fs')
const os = require('os')
const YAML = require('yamljs')
const Promise = require('bluebird')
const pkg = require('../package')

describe('grql', function() {
  let config, grql, sampleServer

  this.timeout(10000)

  before(() => {
    process.env['NODE_ENV'] = 'test'
    config = require('../lib/config')
    config.configFile = path.join(os.tmpdir(), `.${pkg.name}.yml`)
    grql = require('../lib/grql')
    sampleServer = require('./sample-server')
  })

  after(() => Promise.resolve()
    .then(() => {
      if (!config.configFile) {
        return
      }
      return Promise.fromCallback(cb => fs.unlink(config.configFile, cb))
    })
  )

  it('should return an error if no argument', () => grql()
    .then(
      result => {
        throw new Error('should no return a result')
      },
      err => {
        expect(err).to.be.an('error')
        expect(err).to.have.property('message', grql.__('Error : missing argument'))
      }
    )
  )

  it('should show help', () => grql('--help')
    .then(result => {
      expect(result).to.have.property('stderr').that.is.a('string')
    })
  )

  describe('sample server', () => {

    before(() => sampleServer.start()
      .then(() => {
        const port = sampleServer.getPort()
        return grql(
          '-e', 'test',
          '-b', `http://localhost:${port}/graphql`,
          '-s'
        )
      })
    )

    after(() => sampleServer.stop())

    it('should return schema', () => grql('--schema')
      .then(result => {
        expect(result).to.have.property('stdout')
        const out = JSON.parse(result.stdout)
        expect(Object.keys(out)).to.eql(['queryType',
          'mutationType',
          'subscriptionType',
          'types',
          'directives'
        ])
      })
    )

    it('should return hello', () => grql('{ hello }')
      .then(result => {
        expect(result).to.have.property('stdout')
        const out = JSON.parse(result.stdout)
        expect(out).to.eql({hello: 'world'})
      })
    )

    it('should return hello in yaml format', () => grql('-y', '{ hello }')
      .then(result => {
        expect(result).to.have.property('stdout')
        const out = YAML.parse(result.stdout)
        expect(out).to.eql({hello: 'world'})
      })
    )

  })

})
<commit_msg>tests<commit_after>const chai = require('chai')
const expect = chai.expect
const path = require('path')
const fs = require('fs')
const os = require('os')
const YAML = require('yamljs')
const Promise = require('bluebird')
const pkg = require('../package')

describe('grql', function() {
  let config, grql, sampleServer

  this.timeout(10000)

  before(() => {
    process.env['NODE_ENV'] = 'test'
    config = require('../lib/config')
    config.configFile = path.join(os.tmpdir(), `.${pkg.name}.yml`)
    grql = require('../lib/grql')
    sampleServer = require('./sample-server')
  })

  after(() => Promise.resolve()
    .then(() => {
      if (!config.configFile) {
        return
      }
      return Promise.fromCallback(cb => fs.unlink(config.configFile, cb))
    })
  )

  it('should return an error if no argument', () => grql()
    .then(
      result => {
        throw new Error('should no return a result')
      },
      err => {
        expect(err).to.be.an('error')
        expect(err).to.have.property('message', grql.__('Error : missing argument'))
      }
    )
  )

  it('should show help', () => grql('--nocolor', '--help')
    .then(result => {
      expect(result).to.have.property('stderr').that.is.a('string')
    })
  )

  describe('sample server', () => {

    before(() => sampleServer.start()
      .then(() => {
        const port = sampleServer.getPort()
        return grql(
          '--nocolor',
          '-e', 'test',
          '-b', `http://localhost:${port}/graphql`,
          '-s'
        )
      })
    )

    after(() => sampleServer.stop())

    it('should return schema', () => grql('--nocolor', '--schema')
      .then(result => {
        expect(result).to.have.property('stdout')
        const out = JSON.parse(result.stdout)
        expect(Object.keys(out)).to.eql(['queryType',
          'mutationType',
          'subscriptionType',
          'types',
          'directives'
        ])
      })
    )

    it('should return hello', () => grql('--nocolor', '{ hello }')
      .then(result => {
        expect(result).to.have.property('stdout')
        const out = JSON.parse(result.stdout)
        expect(out).to.eql({hello: 'world'})
      })
    )

    it('should return hello in yaml format', () => grql('--nocolor', '-y', '{ hello }')
      .then(result => {
        expect(result).to.have.property('stdout')
        const out = YAML.parse(result.stdout)
        expect(out).to.eql({hello: 'world'})
      })
    )

  })

})
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    assert = require('yeoman-generator').assert,
    helpers = require('yeoman-generator').test;

describe('jekyll-ghpages:gulp', function() {
  before(function(done) {
    helpers.run(path.join(__dirname, '../generators/gulp'))
      .on('end', done);
  });

  it('creates files', function() {
    assert.file([
      'gulpfile.js',
    ]);
  });

  describe('user', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          gh_page_type: 'user',
         })
        .on('end', done);
    });

    it('sets the deploy branch to master', function() {
      assert.fileContent('gulpfile.js', /var deploy_branch = 'master'/);
    });
  });

  describe('project/org', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          gh_page_type: 'project',
         })
        .on('end', done);
    });

    it('sets the deploy branch to master', function() {
      assert.fileContent('gulpfile.js', /var deploy_branch = 'gh-pages'/);
    });
  });

});
<commit_msg>Test desciption fix<commit_after>'use strict';

var path = require('path'),
    assert = require('yeoman-generator').assert,
    helpers = require('yeoman-generator').test;

describe('jekyll-ghpages:gulp', function() {
  before(function(done) {
    helpers.run(path.join(__dirname, '../generators/gulp'))
      .on('end', done);
  });

  it('creates files', function() {
    assert.file([
      'gulpfile.js',
    ]);
  });

  describe('user', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          gh_page_type: 'user',
         })
        .on('end', done);
    });

    it('sets the deploy branch to master', function() {
      assert.fileContent('gulpfile.js', /var deploy_branch = 'master'/);
    });
  });

  describe('project/org', function() {
    before(function(done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          gh_page_type: 'project',
         })
        .on('end', done);
    });

    it('sets the deploy branch to gh-pages', function() {
      assert.fileContent('gulpfile.js', /var deploy_branch = 'gh-pages'/);
    });
  });

});
<|endoftext|>


<commit_before>'use strict';

import assert from 'assert';
import { periodic } from 'most';
import hold from '../src/hold';

describe('hold', () => {
    it('should return stream of same type', () => {
        class Stream {
            constructor() {
                this.source = {};
            }
        }

        const s = hold(new Stream());
        assert(s instanceof Stream);
    });

    it('should deliver most recent event to new observer', () => {
        const s = hold(periodic(10, 1).scan((z, x) => z+x, 0));
        //return s.take(1).observe(x => console.log(x));
        return s.take(1).flatMap(_ => s.take(3))
            .reduce((a, x) => a.concat(x), [])
            .then(a => assert.deepEqual([0,1,2], a));
    });
});
<commit_msg>Clean up test<commit_after>'use strict';

import { describe, it } from 'mocha';
import assert from 'assert';
import { periodic } from 'most';
import hold from '../src/hold';

describe('hold', () => {
    it('should return stream of same type', () => {
        class Stream {
            constructor() {
                this.source = {};
            }
        }

        const s = hold(new Stream());
        assert(s instanceof Stream);
    });

    it('should deliver most recent event to new observer', () => {
        const s = hold(periodic(10, 1).scan((z, x) => z+x, 0));
        return s.take(1).flatMap(_ => s.take(3))
            .reduce((a, x) => a.concat(x), [])
            .then(a => assert.deepEqual([0,1,2], a));
    });
});
<|endoftext|>