<commit_before>const { gql } = require("apollo-server-express");
const ObjectId = require("mongodb").ObjectId;

const WorkExperienceType = "work";
const InterviewExperienceType = "interview";
const InternExperienceType = "intern";

const Type = gql`
    interface Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean
    }

    type WorkExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "work experience specific fields"
        data_time: YearMonth
        week_work_time: Int
        recommend_to_others: String
    }

    type WorkExperienceStatistics {
        count: Int!
        recommend_to_others: YesNoOrUnknownCount!
    }

    type InterviewExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "interview experience specific fields"
        interview_time: YearMonth!
        interview_result: String!
        overall_rating: Int!
        interview_qas: [InterviewQuestion!]
        interview_sensitive_questions: [String!]
    }

    type InterviewExperienceStatistics {
        count: Int!
        overall_rating: Float!
    }

    type InternExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "intern experience specific fields"
        starting_year: Int
        overall_rating: Float
    }

    enum ExperienceType {
        work
        interview
        intern
    }

    type Section {
        subtitle: String
        content: String
    }

    type InterviewQuestion {
        question: String
        answer: String
    }
`;

const Query = gql`
    extend type Query {
        "取得單篇經驗分享"
        experience(id: ID!): Experience
        popular_experiences(
            returnNumber: Int = 3
            sampleNumber: Int = 20
        ): [Experience!]!
    }
`;

const Mutation = `
`;

const ExperienceLikedResolver = async (experience, args, { manager, user }) => {
    if (!user) {
        return null;
    }

    const like = await manager.ExperienceLikeModel.getLikeByExperienceAndUser(
        experience._id,
        user
    );

    if (like) {
        return true;
    }
    return false;
};

const resolvers = {
    Experience: {
        __resolveType(experience) {
            if (experience.type === WorkExperienceType) {
                return "WorkExperience";
            }
            if (experience.type === InterviewExperienceType) {
                return "InterviewExperience";
            }
            if (experience.type === InternExperienceType) {
                return "InternExperience";
            }
            return null;
        },
    },
    WorkExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    InterviewExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    InternExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
        region: experience => experience.region || "",
    },
    Query: {
        async experience(_, { id }, ctx) {
            const collection = ctx.db.collection("experiences");

            const result = await collection.findOne({
                _id: ObjectId(id),
                status: "published",
                "archive.is_archived": false,
            });

            if (!result) {
                return null;
            } else {
                return result;
            }
        },

        async popular_experiences(_, args, ctx) {
            const collection = ctx.db.collection("experiences");
            const { returnNumber, sampleNumber } = args;

            const thirtyDays = 30 * 24 * 60 * 60 * 1000;

            const result = await collection
                .aggregate([
                    {
                        $match: {
                            created_at: {
                                $gte: new Date(new Date() - thirtyDays),
                            },
                        },
                    },
                    {
                        $addFields: {
                            contentsLength: {
                                $strLenCP: {
                                    $reduce: {
                                        input: "$sections",
                                        initialValue: "1",
                                        in: {
                                            $concat: [
                                                "$$value",
                                                "$$this.content",
                                            ],
                                        },
                                    },
                                },
                            },
                        },
                    },
                    {
                        $sort: {
                            contentsLength: -1,
                        },
                    },
                    {
                        $limit: sampleNumber,
                    },
                    {
                        $sample: {
                            size: returnNumber,
                        },
                    },
                ])
                .toArray();

            return result;
        },
    },
};

const types = [Type, Query, Mutation];

module.exports = {
    resolvers,
    types,
};
<commit_msg>Fix experience fetch logic<commit_after>const { gql, UserInputError } = require("apollo-server-express");
const ObjectId = require("mongodb").ObjectId;
const { requiredNumberInRange } = require("../libs/validation");

const WorkExperienceType = "work";
const InterviewExperienceType = "interview";
const InternExperienceType = "intern";

const Type = gql`
    interface Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean
    }

    type WorkExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "work experience specific fields"
        data_time: YearMonth
        week_work_time: Int
        recommend_to_others: String
    }

    type WorkExperienceStatistics {
        count: Int!
        recommend_to_others: YesNoOrUnknownCount!
    }

    type InterviewExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "interview experience specific fields"
        interview_time: YearMonth!
        interview_result: String!
        overall_rating: Int!
        interview_qas: [InterviewQuestion!]
        interview_sensitive_questions: [String!]
    }

    type InterviewExperienceStatistics {
        count: Int!
        overall_rating: Float!
    }

    type InternExperience implements Experience {
        id: ID!
        type: ExperienceType!
        company: Company!
        job_title: JobTitle!
        region: String!
        experience_in_year: Int
        education: String
        salary: Salary
        title: String
        sections: [Section!]!
        created_at: Date!
        reply_count: Int!
        report_count: Int!
        like_count: Int!
        status: PublishStatus!
        archive: Archive!

        "使用者是否按贊 (null 代表未傳入驗證資訊)"
        liked: Boolean

        "intern experience specific fields"
        starting_year: Int
        overall_rating: Float
    }

    enum ExperienceType {
        work
        interview
        intern
    }

    type Section {
        subtitle: String
        content: String
    }

    type InterviewQuestion {
        question: String
        answer: String
    }
`;

const Query = gql`
    extend type Query {
        "取得單篇經驗分享"
        experience(id: ID!): Experience
        popular_experiences(
            "返回的資料筆數，須 <= 20"
            returnNumber: Int = 3
            sampleNumber: Int = 20
        ): [Experience!]!
    }
`;

const Mutation = `
`;

const ExperienceLikedResolver = async (experience, args, { manager, user }) => {
    if (!user) {
        return null;
    }

    const like = await manager.ExperienceLikeModel.getLikeByExperienceAndUser(
        experience._id,
        user
    );

    if (like) {
        return true;
    }
    return false;
};

const resolvers = {
    Experience: {
        __resolveType(experience) {
            if (experience.type === WorkExperienceType) {
                return "WorkExperience";
            }
            if (experience.type === InterviewExperienceType) {
                return "InterviewExperience";
            }
            if (experience.type === InternExperienceType) {
                return "InternExperience";
            }
            return null;
        },
    },
    WorkExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    InterviewExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
    },
    InternExperience: {
        id: experience => experience._id,
        job_title: experience => ({
            name: experience.job_title,
        }),
        liked: ExperienceLikedResolver,
        region: experience => experience.region || "",
    },
    Query: {
        async experience(_, { id }, ctx) {
            const collection = ctx.db.collection("experiences");

            const result = await collection.findOne({
                _id: ObjectId(id),
                status: "published",
                "archive.is_archived": false,
            });

            if (!result) {
                return null;
            } else {
                return result;
            }
        },

        async popular_experiences(_, { returnNumber, sampleNumber }, ctx) {
            if (!requiredNumberInRange(returnNumber, 0, 20)) {
                throw new UserInputError("returnNumber 必須是 0 ~ 20");
            }

            const collection = ctx.db.collection("experiences");

            const thirtyDays = 30 * 24 * 60 * 60 * 1000;

            const result = await collection
                .aggregate([
                    {
                        $match: {
                            created_at: {
                                $gte: new Date(new Date() - thirtyDays),
                            },
                            status: "published",
                            "archive.is_archived": false,
                        },
                    },
                    {
                        $addFields: {
                            contentsLength: {
                                $strLenCP: {
                                    $reduce: {
                                        input: "$sections",
                                        initialValue: "1",
                                        in: {
                                            $concat: [
                                                "$$value",
                                                "$$this.content",
                                            ],
                                        },
                                    },
                                },
                            },
                        },
                    },
                    {
                        $sort: {
                            contentsLength: -1,
                        },
                    },
                    {
                        $limit: sampleNumber,
                    },
                    {
                        $sample: {
                            size: returnNumber,
                        },
                    },
                ])
                .toArray();

            return result;
        },
    },
};

const types = [Type, Query, Mutation];

module.exports = {
    resolvers,
    types,
};
<|endoftext|>


<commit_before>(function(){

	function mockGetDestinationsFromDB() {
		return [
			mockCreateDestination('Dusseldorf', 51.227098,6.774337, ""),
			mockCreateDestination('Cologne', 50.936796,6.960998, "khtwHsbjh@juw@smc@"),
			mockCreateDestination('Bacharach', 50.056478,7.769684, "_r{uHgqni@~|jDg}|C"),
			mockCreateDestination('Braubach', 50.277054,7.644371, "cxopHiemn@}z@cAmm@zDcMP}PjLga@ji@mRv_@g}AzzBed@|x@ka@fn@aaA}gAsS}ZwWiC{P~LwJ`OcCb^_JhRqQfBkVmEuJhDoOb^cNtf@gRja@il@ha@iTvXiTh|AUh`@cCxh@mMf}@sH`l@cNjb@qQxYuWdAwWyJi_@eAkn@hRsUdP}]fo@e]b{@{h@zZcf@|ZaWps@{RflAmBtu@kK~[sUrH{RmEmMoUsJkR{Ekq@k@a]pFs`BhKg}@gGgjB_W_k@{]_No^eAia@vXiVd_@wLjSoF~LqFiC")
		];
	}

	function mockCreateDestination(title, lat, lng, pathTo) {
		return {
			title: title,
			lat: lat,
			lng: lng,
			pathTo: pathTo
		};
	}

	var Destinations = function() {
			var self = this;

			this.allDestinations = function() {
				return mockGetDestinationsFromDB();
			};
	};

	module.exports = new Destinations();
})();<commit_msg>getting destinations from db<commit_after>(function(){
	var mongo = require('mongodb').MongoClient;
	var testDestinations;

	mongo.connect('mongodb://127.0.0.1:27017/TripTracker', function(err, db) {
	    if(err) throw err

			var collection = db.collection('destinations');

			// Locate all the entries using find
			collection.find().toArray(function(err, results) {
					testDestinations = results;
					// Let's close the db
					db.close();
       });
	});

//	function mockGetDestinationsFromDB() {
//		return [
//			mockCreateDestination('Dusseldorf', 51.227098,6.774337, ""),
//			mockCreateDestination('Cologne', 50.936796,6.960998, "khtwHsbjh@juw@smc@"),
//			mockCreateDestination('Bacharach', 50.056478,7.769684, "_r{uHgqni@~|jDg}|C"),
//			mockCreateDestination('Braubach', 50.277054,7.644371, "cxopHiemn@}z@cAmm@zDcMP}PjLga@ji@mRv_@g}AzzBed@|x@ka@fn@aaA}gAsS}ZwWiC{P~LwJ`OcCb^_JhRqQfBkVmEuJhDoOb^cNtf@gRja@il@ha@iTvXiTh|AUh`@cCxh@mMf}@sH`l@cNjb@qQxYuWdAwWyJi_@eAkn@hRsUdP}]fo@e]b{@{h@zZcf@|ZaWps@{RflAmBtu@kK~[sUrH{RmEmMoUsJkR{Ekq@k@a]pFs`BhKg}@gGgjB_W_k@{]_No^eAia@vXiVd_@wLjSoF~LqFiC")
//		];
//	}
//
//	function mockCreateDestination(title, lat, lng, pathTo) {
//		return {
//			title: title,
//			lat: lat,
//			lng: lng,
//			pathTo: pathTo
//		};
//	}

	var Destinations = function() {
			var self = this;

			this.allDestinations = function() {
				return testDestinations;
			};
	};

	module.exports = new Destinations();
})();<|endoftext|>


<commit_before>// END of ParseUri
// BEGIN modified netlog.js example by PhantomJS
// Source: https://github.com/ariya/phantomjs/blob/master/examples/netlog.js
// Source of PhantomJS: https://github.com/ariya/phantomjs
// Original Code distributed under the BSD License

var page = require('webpage').create(),
    system = require('system'),
    address, set = {};
try {

	if (system.args.length === 1) {
	    console.log('Usage: netdomain.js <some URL>');
	    phantom.exit(1);
	} else {
	    address = system.args[1];

	    page.onResourceReceived = function (res) {
	        var data = JSON.stringify(res.url, undefined, 4).split("/")[2];
		if (~data.indexOf(".")) {  // Check if String contains "." (if not, it is a false positive)
		    if (data.substring(0,4) == "www.") { // Remove www., if it is there
			data = data.substring(4);
		    }
		    set[data] = true; // Save data
		}
	    };
	    page.onError = function(err) {
	    };

	    page.open(address, function (status) {
	        if (status !== 'success') {
	            console.log('FAIL to load the address');
		    phantom.exit(1);
	        }
		console.log(Object.keys(set).toString());
	        phantom.exit();
	    });
	}
	// END Modified netlog.js example
}
catch(err) {
	console.log(Object.keys(set).toString());
	phantom.exit();
}
<commit_msg>Added phantom.onError to prevent some more error messages.<commit_after>// END of ParseUri
// BEGIN modified netlog.js example by PhantomJS
// Source: https://github.com/ariya/phantomjs/blob/master/examples/netlog.js
// Source of PhantomJS: https://github.com/ariya/phantomjs
// Original Code distributed under the BSD License

var page = require('webpage').create(),
    system = require('system'),
    address, set = {};
try {

	if (system.args.length === 1) {
	    console.log('Usage: netdomain.js <some URL>');
	    phantom.exit(1);
	} else {
	    address = system.args[1];

	    page.onResourceReceived = function (res) {
	        var data = JSON.stringify(res.url, undefined, 4).split("/")[2];
		if (~data.indexOf(".")) {  // Check if String contains "." (if not, it is a false positive)
		    if (data.substring(0,4) == "www.") { // Remove www., if it is there
			data = data.substring(4);
		    }
		    set[data] = true; // Save data
		}
	    };
	    page.onError = function(err) {
	    };
	    phantom.onError = function(err) {
	    };

	    page.open(address, function (status) {
	        if (status !== 'success') {
	            console.log('FAIL to load the address');
		    phantom.exit(1);
	        }
		console.log(Object.keys(set).toString());
	        phantom.exit();
	    });
	}
	// END Modified netlog.js example
}
catch(err) {
	console.log(Object.keys(set).toString());
	phantom.exit();
}
<|endoftext|>


<commit_before>/**
 * Public API connector
 * @param {string} token
 * @constructor
 *
 * @since 1.0.0
 */
function Connector(token){
  this.token = token;
  this.apiPath = 'https://lpw-public-api.herokuapp.com'
}

/**
 * Sends request to propertyObjects controller with different options
 * @param {object} options
 * @param {function} onLoadCallback
 * @param {function} onErrorCallback
 *
 * @since 1.0.0
 */
Connector.prototype.getProperties = function(options, onLoadCallback, onErrorCallback){
  var url     = this.apiPath + '/property_objects',
      request = new XMLHttpRequest();

  if(typeof options === 'string' && options.length > 0){
    url = url + '?' + options
  }

  request.open('GET', url, true);
  request.setRequestHeader('Authorization', 'Token token=' + this.token);
  request.onload = onLoadCallback.bind(this, request);
  request.onerror = onErrorCallback.bind(this, request);
  request.send(null);
};

/**
 * Sends request to propertyObjects controller only with id parameter
 * @param {number} id
 * @param {function} onLoadCallback
 * @param {function} onErrorCallback
 *
 * @since 1.0.0
 */
Connector.prototype.getPropertyById = function(id, onLoadCallback, onErrorCallback){
  var url     = this.apiPath + '/property_objects/?id=' + id,
      request = new XMLHttpRequest();

  request.open('GET', url, true);
  request.setRequestHeader('Authorization', 'Token token=' + this.token);
  request.onload = onLoadCallback.bind(this, request);
  request.onerror = onErrorCallback.bind(this, request);
  request.send(null);
};<commit_msg>refactor(connector): changed names of methods<commit_after>/**
 * Public API connector
 * @param {string} token
 * @constructor
 *
 * @since 1.0.0
 */
function Connector(token){
  this.token = token;
  this.apiPath = 'https://lpw-public-api.herokuapp.com'
}

/**
 * Sends request to propertyObjects controller with different options
 * @param {object} options
 * @param {function} onLoadCallback
 * @param {function} onErrorCallback
 *
 * @since 1.0.0
 */
Connector.prototype.readProperties = function(options, onLoadCallback, onErrorCallback){
  var url     = this.apiPath + '/property_objects',
      request = new XMLHttpRequest();

  if(typeof options === 'string' && options.length > 0){
    url = url + '?' + options
  }

  request.open('GET', url, true);
  request.setRequestHeader('Authorization', 'Token token=' + this.token);
  request.onload = onLoadCallback.bind(this, request);
  request.onerror = onErrorCallback.bind(this, request);
  request.send(null);
};

/**
 * Sends request to propertyObjects controller only with id parameter
 * @param {number} id
 * @param {function} onLoadCallback
 * @param {function} onErrorCallback
 *
 * @since 1.0.0
 */
Connector.prototype.readPropertyById = function(id, onLoadCallback, onErrorCallback){
  var url     = this.apiPath + '/property_objects/?id=' + id,
      request = new XMLHttpRequest();

  request.open('GET', url, true);
  request.setRequestHeader('Authorization', 'Token token=' + this.token);
  request.onload = onLoadCallback.bind(this, request);
  request.onerror = onErrorCallback.bind(this, request);
  request.send(null);
};<|endoftext|>


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

  angular.module('app', [
    'app.config',
    'app.core',
    'app.feature',
    'ngMaterial'
  ]);

  angular.module('app').config([
    '$logProvider', 'LOG', '$locationProvider',
    function($logProvider, log, $locationProvider) {
      // Enable or disable debug logging
      $logProvider.debugEnabled(log.ENABLE_DEBUG);

      $locationProvider.html5Mode(false);
    }
  ]);

  // CONFIG SETTINGS
  angular.module('app.config', [])
    // Log settings
    .constant('LOG', {
      ENABLE_DEBUG: true
    })
    .constant('WEATHER_SETTINGS', {
      OPEN_WEATHER_MAP: {
        BASE_URI: 'http://api.openweathermap.org/data/2.5',
        API_KEY: '<api-key>',
        CITY_ID: '2925550',
        LANGUAGE_ID: 'de',
        UNITS: 'metric'
      }
    });
})();
<commit_msg>Apply custom dark theming with a black background and white foreground<commit_after>(function() {
  'use strict';

  angular.module('app', [
    'app.config',
    'app.core',
    'app.feature',
    'ngMaterial'
  ]);

  angular.module('app').config([
    '$logProvider', 'LOG', '$locationProvider', '$mdThemingProvider',
    function($logProvider, log, $locationProvider, $mdThemingProvider) {
      // Enable or disable debug logging
      $logProvider.debugEnabled(log.ENABLE_DEBUG);

      $locationProvider.html5Mode(false);
      var mmBlack = $mdThemingProvider.extendPalette('grey', {
        '50': '000000',
        '100': '000000',
        '200': '000000',
        '300': '000000',
        '400': '000000',
        '500': '000000',
        '600': '000000',
        '700': '000000',
        '800': '000000',
        '900': '000000',
        'A100': '000000',
        'A200': '000000',
        'A400': '000000',
        'A700': '000000'
      });

      $mdThemingProvider.definePalette('mm-black', mmBlack);

      $mdThemingProvider.theme('default')
        .dark()
        .backgroundPalette('mm-black');
    }
  ]);

  // CONFIG SETTINGS
  angular.module('app.config', [])
    // Log settings
    .constant('LOG', {
      ENABLE_DEBUG: true
    })
    .constant('WEATHER_SETTINGS', {
      OPEN_WEATHER_MAP: {
        BASE_URI: 'http://api.openweathermap.org/data/2.5',
        API_KEY: '<api-key>',
        CITY_ID: '2925550',
        LANGUAGE_ID: 'de',
        UNITS: 'metric'
      }
    });
})();
<|endoftext|>


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

  function personaProvider($windowProvider) {

    var $window = $windowProvider.$get(),
      options = {
        baseUrl: 'localhost',
        audience: $window.location.href,
        tokenName: 'token'
      };
    this.config = function (data) {
      options = angular.extend(options,data);
    };

    function Persona($rootScope, $http) {
      var service = {};
      service.login = function (assertion) {
        var param = {
          assertion: assertion,
          audience: options.audience
        };
        $http.post(options.baseUrl + '/login', param).success(function (data) {
          service.loggedUser = data.user;
          $window.localStorage.setItem(options.tokenName, data.token);
        }).error(function (err) {
          $rootScope.$broadcast('login:error', err);
        });
      };

      service.logout = function () {
        $window.localStorage.removeItem(options.tokenName);
        service.loggedUser = null;
      };

      $window.navigator.id.watch({
        loggedInUser: service.loggedUser,
        onlogin: service.login,
        onlogout: service.logout
      });
      return service;
    }

    this.$get = Persona;

  }

  angular.module('angular-persona-jwt.services',[])
    .provider('persona', personaProvider);

})(angular);

<commit_msg>fix some build issues<commit_after>(function(angular){
  'use strict';

  function personaProvider($windowProvider) {

    var $window = $windowProvider.$get(),
      options = {
        baseUrl: 'localhost',
        audience: $window.location.href,
        tokenName: 'token'
      };
    this.config = function (data) {
      options = angular.extend(options,data);
    };

    function Persona($rootScope, $http) {
      var service = {};

      service.loggedUser = {};

      service.login = function (assertion) {
        var param = {
          assertion: assertion,
          audience: options.audience
        };
        $http.post(options.baseUrl + '/login', param).success(function (data) {
          service.loggedUser = data.user;
          $window.localStorage.setItem(options.tokenName, data.token);
        }).error(function (err) {
          $rootScope.$broadcast('login:error', err);
        });
      };

      service.logout = function () {
        $window.localStorage.removeItem(options.tokenName);
        service.loggedUser = null;
      };

      $window.navigator.id.watch({
        loggedInUser: service.loggedUser,
        onlogin: service.login,
        onlogout: service.logout
      });
      return service;
    }

    this.$get = Persona;

  }

  angular.module('angular-persona-jwt.services',[])
    .provider('persona', personaProvider);

})(angular);

<|endoftext|>


<commit_before>import BaseShape from './base-shape';
import ns from '../core/namespace';

/**
 * A shape to display labelled crosshairs or similar positional
 * crosshairs/focus overlay.
 *
 * [example usage](./examples/layer-crosshairs.html)
 */
export default class Crosshairs extends BaseShape {
  getClassName() { return 'crosshairs'; }

  _getAccessorList() {
    return { cx: 0, cy: 0 };
  }

  _getDefaults() {
    return {
      color: '#000000',
      opacity: 1
    };
  }

  render(renderingContext) {
    if (this.$el) { return this.$el; }
    this.$el = document.createElementNS(ns, 'path');
    this.$el.setAttributeNS(null, 'shape-rendering', 'crispEdges');
    this.$el.style.stroke = this.params.color;
    return this.$el;
  }

  update(renderingContext, datum) {

    const cx = this.cx(datum);
    const cy = this.cy(datum);
    const x = Math.round(renderingContext.timeToPixel(cx)) + 0.5;
    const y = Math.round(renderingContext.valueToPixel(cy)) + 0.5;

    const minX = Math.floor(renderingContext.minX);
    const maxX = Math.ceil(renderingContext.maxX);
    const h = renderingContext.height;

    this.$el.setAttributeNS(null, 'd',
                            `M${x},${0}L${x},${h}M${minX},${y}L${maxX},${y}`)
  }

  /**
   * The crosshairs cannot be selected.
   * @return {Boolean} false
   */
  inArea() { return false; }
}
<commit_msg>Semicolon!<commit_after>import BaseShape from './base-shape';
import ns from '../core/namespace';

/**
 * A shape to display labelled crosshairs or similar positional
 * crosshairs/focus overlay.
 *
 * [example usage](./examples/layer-crosshairs.html)
 */
export default class Crosshairs extends BaseShape {
  getClassName() { return 'crosshairs'; }

  _getAccessorList() {
    return { cx: 0, cy: 0 };
  }

  _getDefaults() {
    return {
      color: '#000000',
      opacity: 1
    };
  }

  render(renderingContext) {
    if (this.$el) { return this.$el; }
    this.$el = document.createElementNS(ns, 'path');
    this.$el.setAttributeNS(null, 'shape-rendering', 'crispEdges');
    this.$el.style.stroke = this.params.color;
    return this.$el;
  }

  update(renderingContext, datum) {

    const cx = this.cx(datum);
    const cy = this.cy(datum);
    const x = Math.round(renderingContext.timeToPixel(cx)) + 0.5;
    const y = Math.round(renderingContext.valueToPixel(cy)) + 0.5;

    const minX = Math.floor(renderingContext.minX);
    const maxX = Math.ceil(renderingContext.maxX);
    const h = renderingContext.height;

    this.$el.setAttributeNS(null, 'd',
                            `M${x},${0}L${x},${h}M${minX},${y}L${maxX},${y}`);
  }

  /**
   * The crosshairs cannot be selected.
   * @return {Boolean} false
   */
  inArea() { return false; }
}
<|endoftext|>


<commit_before>/* @flow */

var Prefixer = require('./prefixer');
var checkProps = require('./check-props');
var getState = require('./get-state');
var getStateKey = require('./get-state-key');
var mergeStyles = require('./merge-styles');
var resolveInteractionStyles = require('./resolve-interaction-styles');
var resolveMediaQueries = require('./resolve-media-queries');

var ExecutionEnvironment = require('exenv');
var React = require('react');

// babel-eslint 3.1.7 fails here for some reason, error:
//   0:0  error  Cannot call method 'isSequenceExpression' of undefined
//
// declare class RadiumComponent extends ReactComponent {
//   _lastMouseDown: number,
//   _radiumMediaQueryListenersByQuery: Object<string, {remove: () => void}>,
//   _radiumMouseUpListener: {remove: () => void},
// }

var _setStyleState = function (component, key, stateKey, value) {
  var existing = component._lastRadiumState ||
    component.state && component.state._radiumStyleState || {};

  var state = { _radiumStyleState: {...existing} };
  state._radiumStyleState[key] = {...state._radiumStyleState[key]};
  state._radiumStyleState[key][stateKey] = value;

  component._lastRadiumState = state._radiumStyleState;
  component.setState(state);
};

// Wrapper around React.cloneElement. To avoid processing the same element
// twice, whenever we clone an element add a special non-enumerable prop to
// make sure we don't process this element again.
var _cloneElement = function (renderedElement, newProps, newChildren) {
  // Only add flag if this is a normal DOM element
  if (typeof renderedElement.type === 'string') {
    newProps = {...newProps, _radiumDidResolveStyles: true};
  }

  return React.cloneElement(renderedElement, newProps, newChildren);
};

//
// The nucleus of Radium. resolveStyles is called on the rendered elements
// before they are returned in render. It iterates over the elements and
// children, rewriting props to add event handlers required to capture user
// interactions (e.g. mouse over). It also replaces the style prop because it
// adds in the various interaction styles (e.g. :hover).
//
var resolveStyles = function (
  component: any, // ReactComponent, flow+eslint complaining
  renderedElement: any, // ReactElement
  config: Object = {},
  existingKeyMap?: {[key: string]: boolean}
): any { // ReactElement
  existingKeyMap = existingKeyMap || {};

  if (
    !renderedElement ||
    // Bail if we've already processed this element. This ensures that only the
    // owner of an element processes that element, since the owner's render
    // function will be called first (which will always be the case, since you
    // can't know what else to render until you render the parent component).
    (renderedElement.props && renderedElement.props._radiumDidResolveStyles)
  ) {
    return renderedElement;
  }

  // Recurse over children first in case we bail early. Note that children only
  // include those rendered in `this` component. Child nodes in other components
  // will not be here, so each component needs to use Radium.
  var oldChildren = renderedElement.props.children;
  var newChildren = oldChildren;
  if (oldChildren) {
    var childrenType = typeof oldChildren;
    if (childrenType === 'string' || childrenType === 'number') {
      // Don't do anything with a single primitive child
      newChildren = oldChildren;
    } else if (childrenType === 'function') {
      // Wrap the function, resolving styles on the result
      newChildren = function () {
        var result = oldChildren.apply(this, arguments);
        if (React.isValidElement(result)) {
          return resolveStyles(component, result, config, existingKeyMap);
        }
        return result;
      };
    } else if (React.Children.count(oldChildren) === 1 && oldChildren.type) {
      // If a React Element is an only child, don't wrap it in an array for
      // React.Children.map() for React.Children.only() compatibility.
      var onlyChild = React.Children.only(oldChildren);
      newChildren = resolveStyles(component, onlyChild, config, existingKeyMap);
    } else {
      newChildren = React.Children.map(
        oldChildren,
        function (child) {
          if (React.isValidElement(child)) {
            return resolveStyles(component, child, config, existingKeyMap);
          }

          return child;
        }
      );
    }
  }

  var props = renderedElement.props;
  var newProps = {};

  // Recurse over props, just like children
  Object.keys(props).forEach(prop => {
    // We already recurse over children above
    if (prop === 'children') {
      return;
    }

    var propValue = props[prop];
    if (React.isValidElement(propValue)) {
      newProps[prop] = resolveStyles(
        component,
        propValue,
        config,
        existingKeyMap
      );
    }
  });

  var hasResolvedProps = Object.keys(newProps).length > 0;

  // Bail early if element is not a simple ReactDOMElement or has no style
  if (
    !React.isValidElement(renderedElement) ||
    typeof renderedElement.type !== 'string' ||
    !props.style
  ) {
    if (oldChildren === newChildren && !hasResolvedProps) {
      return renderedElement;
    }

    return _cloneElement(
      renderedElement,
      hasResolvedProps ? newProps : {},
      newChildren
    );
  }

  // We need a unique key to correlate state changes due to user interaction
  // with the rendered element, so we know to apply the proper interactive
  // styles.
  var originalKey = renderedElement.ref || renderedElement.key;
  var key = getStateKey(originalKey);

  var alreadyGotKey = false;
  var getKey = function () {
    if (alreadyGotKey) {
      return key;
    }

    alreadyGotKey = true;

    if (existingKeyMap[key]) {
      throw new Error(
        'Radium requires each element with interactive styles to have a unique ' +
        'key, set using either the ref or key prop. ' +
        (originalKey ?
          'Key "' + originalKey + '" is a duplicate.' :
          'Multiple elements have no key specified.')
      );
    }

    existingKeyMap[key] = true;

    return key;
  };

  var checkPropsPlugin = function ({component, style}) {
    checkProps(component, style);
    return {style};
  };

  // Convenient syntax for multiple styles: `style={[style1, style2, etc]}`
  // Ignores non-objects, so you can do `this.state.isCool && styles.cool`.
  var mergeArray = function ({style, mergeStyles}) {
    var newStyle = Array.isArray(style) ? mergeStyles(style) : style;
    return {style: newStyle};
  };

  var prefix = function ({component, style}) {
    var newStyle = Prefixer.getPrefixedStyle(component, style);
    return {style: newStyle};
  };

  var plugins = [
    mergeArray,
    checkPropsPlugin,
    resolveMediaQueries,
    resolveInteractionStyles,
    prefix,
    checkPropsPlugin,
  ];

  var currentStyle = props.style;
  plugins.forEach(plugin => {
    var result = plugin({
      ExecutionEnvironment,
      component,
      config,
      getState: stateKey => getState(component.state, getKey(), stateKey),
      mergeStyles,
      props,
      setState: (stateKey, value, elementKey) =>
        _setStyleState(component, elementKey || getKey(), stateKey, value),
      style: currentStyle
    });

    currentStyle = result.style;

    newProps = {...newProps, ...result.props};

    if (result.componentFields) {
      Object.keys(result.componentFields).forEach(newComponentFieldName => {
        component[newComponentFieldName] =
          result.componentFields[newComponentFieldName];
      });
    }
  });

  newProps.style = currentStyle;

  return _cloneElement(renderedElement, newProps, newChildren);
};

module.exports = resolveStyles;
<commit_msg>Factor out getKey<commit_after>/* @flow */

var Prefixer = require('./prefixer');
var checkProps = require('./check-props');
var getState = require('./get-state');
var getStateKey = require('./get-state-key');
var mergeStyles = require('./merge-styles');
var resolveInteractionStyles = require('./resolve-interaction-styles');
var resolveMediaQueries = require('./resolve-media-queries');

var ExecutionEnvironment = require('exenv');
var React = require('react');

// babel-eslint 3.1.7 fails here for some reason, error:
//   0:0  error  Cannot call method 'isSequenceExpression' of undefined
//
// declare class RadiumComponent extends ReactComponent {
//   _lastMouseDown: number,
//   _radiumMediaQueryListenersByQuery: Object<string, {remove: () => void}>,
//   _radiumMouseUpListener: {remove: () => void},
// }

var _setStyleState = function (component, key, stateKey, value) {
  var existing = component._lastRadiumState ||
    component.state && component.state._radiumStyleState || {};

  var state = { _radiumStyleState: {...existing} };
  state._radiumStyleState[key] = {...state._radiumStyleState[key]};
  state._radiumStyleState[key][stateKey] = value;

  component._lastRadiumState = state._radiumStyleState;
  component.setState(state);
};

// Wrapper around React.cloneElement. To avoid processing the same element
// twice, whenever we clone an element add a special non-enumerable prop to
// make sure we don't process this element again.
var _cloneElement = function (renderedElement, newProps, newChildren) {
  // Only add flag if this is a normal DOM element
  if (typeof renderedElement.type === 'string') {
    newProps = {...newProps, _radiumDidResolveStyles: true};
  }

  return React.cloneElement(renderedElement, newProps, newChildren);
};

var _buildGetKey = function (renderedElement, existingKeyMap) {
  // We need a unique key to correlate state changes due to user interaction
  // with the rendered element, so we know to apply the proper interactive
  // styles.
  var originalKey = renderedElement.ref || renderedElement.key;
  var key = getStateKey(originalKey);

  var alreadyGotKey = false;
  var getKey = function () {
    if (alreadyGotKey) {
      return key;
    }

    alreadyGotKey = true;

    if (existingKeyMap[key]) {
      throw new Error(
        'Radium requires each element with interactive styles to have a unique ' +
        'key, set using either the ref or key prop. ' +
        (originalKey ?
          'Key "' + originalKey + '" is a duplicate.' :
          'Multiple elements have no key specified.')
      );
    }

    existingKeyMap[key] = true;

    return key;
  };

  return getKey;
};

//
// The nucleus of Radium. resolveStyles is called on the rendered elements
// before they are returned in render. It iterates over the elements and
// children, rewriting props to add event handlers required to capture user
// interactions (e.g. mouse over). It also replaces the style prop because it
// adds in the various interaction styles (e.g. :hover).
//
var resolveStyles = function (
  component: any, // ReactComponent, flow+eslint complaining
  renderedElement: any, // ReactElement
  config: Object = {},
  existingKeyMap?: {[key: string]: boolean}
): any { // ReactElement
  existingKeyMap = existingKeyMap || {};

  if (
    !renderedElement ||
    // Bail if we've already processed this element. This ensures that only the
    // owner of an element processes that element, since the owner's render
    // function will be called first (which will always be the case, since you
    // can't know what else to render until you render the parent component).
    (renderedElement.props && renderedElement.props._radiumDidResolveStyles)
  ) {
    return renderedElement;
  }

  // Recurse over children first in case we bail early. Note that children only
  // include those rendered in `this` component. Child nodes in other components
  // will not be here, so each component needs to use Radium.
  var oldChildren = renderedElement.props.children;
  var newChildren = oldChildren;
  if (oldChildren) {
    var childrenType = typeof oldChildren;
    if (childrenType === 'string' || childrenType === 'number') {
      // Don't do anything with a single primitive child
      newChildren = oldChildren;
    } else if (childrenType === 'function') {
      // Wrap the function, resolving styles on the result
      newChildren = function () {
        var result = oldChildren.apply(this, arguments);
        if (React.isValidElement(result)) {
          return resolveStyles(component, result, config, existingKeyMap);
        }
        return result;
      };
    } else if (React.Children.count(oldChildren) === 1 && oldChildren.type) {
      // If a React Element is an only child, don't wrap it in an array for
      // React.Children.map() for React.Children.only() compatibility.
      var onlyChild = React.Children.only(oldChildren);
      newChildren = resolveStyles(component, onlyChild, config, existingKeyMap);
    } else {
      newChildren = React.Children.map(
        oldChildren,
        function (child) {
          if (React.isValidElement(child)) {
            return resolveStyles(component, child, config, existingKeyMap);
          }

          return child;
        }
      );
    }
  }

  var props = renderedElement.props;
  var newProps = {};

  // Recurse over props, just like children
  Object.keys(props).forEach(prop => {
    // We already recurse over children above
    if (prop === 'children') {
      return;
    }

    var propValue = props[prop];
    if (React.isValidElement(propValue)) {
      newProps[prop] = resolveStyles(
        component,
        propValue,
        config,
        existingKeyMap
      );
    }
  });

  var hasResolvedProps = Object.keys(newProps).length > 0;

  // Bail early if element is not a simple ReactDOMElement or has no style
  if (
    !React.isValidElement(renderedElement) ||
    typeof renderedElement.type !== 'string' ||
    !props.style
  ) {
    if (oldChildren === newChildren && !hasResolvedProps) {
      return renderedElement;
    }

    return _cloneElement(
      renderedElement,
      hasResolvedProps ? newProps : {},
      newChildren
    );
  }

  var checkPropsPlugin = function ({component, style}) {
    checkProps(component, style);
    return {style};
  };

  // Convenient syntax for multiple styles: `style={[style1, style2, etc]}`
  // Ignores non-objects, so you can do `this.state.isCool && styles.cool`.
  var mergeArray = function ({style, mergeStyles}) {
    var newStyle = Array.isArray(style) ? mergeStyles(style) : style;
    return {style: newStyle};
  };

  var prefix = function ({component, style}) {
    var newStyle = Prefixer.getPrefixedStyle(component, style);
    return {style: newStyle};
  };

  var plugins = [
    mergeArray,
    checkPropsPlugin,
    resolveMediaQueries,
    resolveInteractionStyles,
    prefix,
    checkPropsPlugin,
  ];

  var getKey = _buildGetKey(renderedElement, existingKeyMap);
  var currentStyle = props.style;
  plugins.forEach(plugin => {
    var result = plugin({
      ExecutionEnvironment,
      component,
      config,
      getState: stateKey => getState(component.state, getKey(), stateKey),
      mergeStyles,
      props,
      setState: (stateKey, value, elementKey) =>
        _setStyleState(component, elementKey || getKey(), stateKey, value),
      style: currentStyle
    });

    currentStyle = result.style;

    newProps = {...newProps, ...result.props};

    if (result.componentFields) {
      Object.keys(result.componentFields).forEach(newComponentFieldName => {
        component[newComponentFieldName] =
          result.componentFields[newComponentFieldName];
      });
    }
  });

  newProps.style = currentStyle;

  return _cloneElement(renderedElement, newProps, newChildren);
};

module.exports = resolveStyles;
<|endoftext|>


<commit_before>const gameController = require('./gameContainer.js');
let game = gameController.getGame();

exports.init = (msg) =>{
	if(!game[msg.guild.id]){
		game[msg.guild.id] = {};
		updateGameContainer(game);
	}
};

exports.createNew = (msg, args) => {
	updateGameObject();
	let sessionName = args.join(' ');

	if(game[msg.guild.id][sessionName]){
		msg.channel.sendMessage('Sorry can\'t do. This name is taken.');
	}
	else if(sessionName){
		startPreparingGame(msg, args, sessionName);
	}
	else{
		msg.channel.sendMessage(
			'Improper command.\n'+
			'Command should look like: `GC: create [name]`'
		);
	}
};

exports.begin = (msg, args) => {
	updateGameObject();
	let sessionName = args.join(' ');

	if(!canBegin(msg, sessionName)){
		return;
	};

	msg.channel.sendMessage(msg.author + ' has started the game');
	game[msg.guild.id][sessionName].isInProgress = true;

	updateGameContainer(game);

	function canBegin(msg, sessionName){
		if(!sessionName){
			msg.channel.sendMessage('You need to provide name of the session you want to start');
			return false;
		}
		if(game[msg.guild.id][sessionName].players[msg.author.id].master != true){
			msg.channel.sendMessage('You are not the session owner');
			return false;
		}
		return true;
	}
};

exports.leave = (msg, args) => {
	updateGameObject();
	let sessionName = args.join(' ');
	let session;

	if(args){
		session = game[msg.guild.id][sessionName];
	}

	if(!canLeave(msg)){
		return;
	}

	session.playersJoined--;
	msg.channel.sendMessage('Player ' + msg.author + ' left the session.');

	deletePlayer(msg, session, sessionName);

	updateGameContainer(game);

	function deletePlayer(msg, session, sessionName){
		if(session.playersJoined == 0){
			msg.channel.sendMessage('The game has been disbanded');
			delete game[msg.guild.id][sessionName];
		}
		else if(session.players[msg.author.id].master){
			session.players[Object.keys(session.players)[1]].master = true;
			msg.channel.sendMessage(`<@!${Object.keys(session.players)[1]}> is the new master`);
			delete session.players[msg.author.id];
			game[msg.guild.id][sessionName] = session;
		}
	}

	function isSessionEmpty(msg){
		if(session.playersJoined == 0){
			msg.channel.sendMessage('The game has been disbanded');
			delete game[msg.guild.id][sessionName];
			return;
		}
	}

	function canLeave(msg){
		if(!sessionName){
			msg.channel.sendMessage('You need to provide name of the session you want to leave');
			return false;
		}
		if(!session){
			msg.channel.sendMessage('There is no session with this name');
			return false;
		}
		if(!session.players.hasOwnProperty(msg.author.id)){
			msg.channel.sendMessage('You are not in this session');
			return false;
		}
		return true;
	}
};

exports.join = (msg, args, master) => {
	updateGameObject();
	let sessionName = args.join(' ');
	let session;

	if(args) session = game[msg.guild.id][sessionName];

	if(!canJoin(msg)){
		return;
	}

	session.players[msg.author.id] = {master: master || false};
	session.playersJoined++;
	msg.channel.sendMessage('Player ' + msg.author + ' connected.');

	game[msg.guild.id][sessionName] = session;

	updateGameContainer(game);

	function canJoin(msg){
		if(!sessionName){
			msg.channel.sendMessage('You need to provide name of the session you want to join');
			return false;
		}
		if(!session){
			msg.channel.sendMessage('There is no session with this name');
			return false;
		}
		if(session.players.hasOwnProperty(msg.author.id)){
			msg.channel.sendMessage('You already are in this session');
			return false;
		}
		return true;
	}
};

function startPreparingGame(msg, args, sessionName){
	game[msg.guild.id][sessionName] = Session();
	let session = game[msg.guild.id][sessionName];

	msg.channel.sendMessage('Preparing session: ' + sessionName);

	exports.join(msg, args, true);
}

function startSession(msg){
	msg.channel.sendMessage('Session started!');
}

function Session(){
	let ob = {};
	ob.isInProgress = false;
	ob.playersJoined = 0;
	ob.players = {};

	return ob;
}

function updateGameContainer(game){
	gameController.setGame(game);
}

function updateGameObject(){
	game = gameController.getGame();
}

module.exports = exports;<commit_msg>cleaning up sessionHandler<commit_after>const gameController = require('./gameContainer.js');
let game = gameController.getGame();

exports.init = (msg) =>{
	if(!game[msg.guild.id]){
		game[msg.guild.id] = {};
		updateGameContainer(game);
	}
};

exports.createNew = (msg, args) => {
	updateGameObject();
	let sessionName = args.join(' ');

	if(game[msg.guild.id][sessionName]){
		msg.channel.sendMessage('Sorry can\'t do. This name is taken.');
	}
	else if(sessionName){
		startPreparingGame(msg, args, sessionName);
	}
	else{
		msg.channel.sendMessage(
			'Improper command.\n'+
			'Command should look like: `GC: create [name]`'
		);
	}
};

exports.begin = (msg, args) => {
	updateGameObject();
	let sessionName = args.join(' ');

	if(!canBegin(msg, sessionName)){
		return;
	};

	msg.channel.sendMessage(msg.author + ' has started the game');
	game[msg.guild.id][sessionName].isInProgress = true;

	updateGameContainer(game);

	function canBegin(msg, sessionName){
		if(!sessionName){
			msg.channel.sendMessage('You need to provide name of the session you want to start');
			return false;
		}
		if(game[msg.guild.id][sessionName].players[msg.author.id].master != true){
			msg.channel.sendMessage('You are not the session owner');
			return false;
		}
		return true;
	}
};

exports.leave = (msg, args) => {
	updateGameObject();
	let sessionName = args.join(' ');
	let session;

	if(args){
		session = game[msg.guild.id][sessionName];
	}

	if(!canLeave(msg)){
		return;
	}

	session.playersJoined--;
	msg.channel.sendMessage('Player ' + msg.author + ' left the session.');

	deletePlayer(msg, session, sessionName);

	updateGameContainer(game);

	function deletePlayer(msg, session, sessionName){
		if(session.playersJoined == 0){
			msg.channel.sendMessage('The game has been disbanded');
			delete game[msg.guild.id][sessionName];
		}
		else if(session.players[msg.author.id].master){
			session.players[Object.keys(session.players)[1]].master = true;
			msg.channel.sendMessage(`<@!${Object.keys(session.players)[1]}> is the new master`);
			delete session.players[msg.author.id];
			game[msg.guild.id][sessionName] = session;
		}
	}

	function canLeave(msg){
		if(!sessionName){
			msg.channel.sendMessage('You need to provide name of the session you want to leave');
			return false;
		}
		if(!session){
			msg.channel.sendMessage('There is no session with this name');
			return false;
		}
		if(!session.players.hasOwnProperty(msg.author.id)){
			msg.channel.sendMessage('You are not in this session');
			return false;
		}
		return true;
	}
};

exports.join = (msg, args, master) => {
	updateGameObject();
	let sessionName = args.join(' ');
	let session;

	if(args) session = game[msg.guild.id][sessionName];

	if(!canJoin(msg)){
		return;
	}

	session.players[msg.author.id] = {master: master || false};
	session.playersJoined++;
	msg.channel.sendMessage('Player ' + msg.author + ' connected.');

	game[msg.guild.id][sessionName] = session;

	updateGameContainer(game);

	function canJoin(msg){
		if(!sessionName){
			msg.channel.sendMessage('You need to provide name of the session you want to join');
			return false;
		}
		if(!session){
			msg.channel.sendMessage('There is no session with this name');
			return false;
		}
		if(session.players.hasOwnProperty(msg.author.id)){
			msg.channel.sendMessage('You already are in this session');
			return false;
		}
		return true;
	}
};

function startPreparingGame(msg, args, sessionName){
	game[msg.guild.id][sessionName] = Session();
	let session = game[msg.guild.id][sessionName];

	msg.channel.sendMessage('Preparing session: ' + sessionName);

	exports.join(msg, args, true);
}

function Session(){
	let ob = {};
	ob.isInProgress = false;
	ob.playersJoined = 0;
	ob.players = {};

	return ob;
}

function updateGameContainer(game){
	gameController.setGame(game);
}

function updateGameObject(){
	game = gameController.getGame();
}

module.exports = exports;<|endoftext|>


<commit_before>/* Tests the streaming xhr without stubbing anything. Really just a test that
*  we've got the interface of the in-browser XHR object pinned down  */

(function(){

   AsyncTestCase("testStreamingXhr", {

      testCanAjaxInASmallKnownFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // in practice, since we're running on an internal network and this is a small file,
            // we'll probably only get one callback
            streamingXhr.fetch('/test/test/json/smallestPossible.json', callbacks.add(function(nextDrip){
               combinedResult += nextDrip;
            }));
         });

         queue.call("check we got the json back", function(){
            assertEquals('{}', combinedResult);
         });
      },

      testCanAjaxInAVeryLargeFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr.fetch('/test/test/json/tenThousandRecords.json', function(nextDrip){
               console.log('got a bit of json');
               combinedResult += nextDrip;
            },
            // callback for when the stream is complete. we register this just so that jstd knows
            // when to move onto the next queuer
            callbacks.add(function(){}));
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            var parsedResult = JSON.parse(combinedResult);

            // should have 10,000 records:
            assertEquals(10000, parsedResult.result.length);
         });
      }
   });

})();<commit_msg>speed up async test failures<commit_after>/* Tests the streaming xhr without stubbing anything. Really just a test that
*  we've got the interface of the in-browser XHR object pinned down  */

(function(){

   AsyncTestCase("testStreamingXhr", {

      // shorten the waiting time before a test fails. Default 30s is too long:
      setUp: function(){
         jstestdriver.plugins.async.CallbackPool.TIMEOUT = 2000; //2seconds
      },

      testCanAjaxInASmallKnownFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // in practice, since we're running on an internal network and this is a small file,
            // we'll probably only get one callback
            streamingXhr.fetch('/test/test/json/smallestPossible.json', callbacks.add(function(nextDrip){
               combinedResult += nextDrip;
            }));
         });

         queue.call("check we got the json back", function(){
            assertEquals('{}', combinedResult);
         });
      },

      testCanAjaxInAVeryLargeFile: function(queue) {

         var combinedResult = '';

         queue.call("ask the streaming xhr to fetch", function(callbacks){

            // since this is a large file, even serving locally we're going to get multiple callbacks:
            streamingXhr.fetch('/test/test/json/tenThousandRecords.json', function(nextDrip){
               console.log('got a bit of json');
               combinedResult += nextDrip;
            },
            // callback for when the stream is complete. we register this just so that jstd knows
            // when to move onto the next queuer
            callbacks.add(function(){}));
         });

         queue.call("check we got the correct json back", function(){

            // should have given valid json;
            var parsedResult = JSON.parse(combinedResult);

            // should have 10,000 records:
            assertEquals(10000, parsedResult.result.length);
         });
      }
   });

})();<|endoftext|>


<commit_before>const vmSystemOperationsTest = require('ethereum-tests').vmtests.vmSystemOperationsTest,
  async = require('async'),
  VM = require('../../../lib/vm'),
  rlp = require('rlp'),
  Account = require('../../../lib/account.js'),
  bignum = require('bignum'),
  assert = require('assert'),
  testUtils = require('../../testUtils'),
  utils = require('../../../lib/utils.js'),
  Trie = require('merkle-patricia-tree');

// for SUICIDE tests, this is temporarily added to avoid negative balances
const TMP_BAL_AVOID_NEG = '13333337';

describe.only('[Common]: vmSystemOperationsTest', function() {
  var tests = Object.keys(vmSystemOperationsTest);
  // TODO add tests
  tests = ['CallToNameRegistrator0'];
  tests.forEach(function(testKey) {
    var state = new Trie();
    var testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      // vm.onStep = function(info, done) {
      //   console.log('vm', bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

      //   var stream = vm.trie.createReadStream();
      //   stream.on("data", function(data) {
      //     var account = new Account(data.value);
      //     console.log("key: " + data.key.toString("hex"));
      //     //console.log(data.value.toString('hex'));
      //     console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
      //   });

      //   stream.on('end', done);

      //   // info.stack.reverse();
      //   // info.stack.forEach(function (item) {
      //   //   console.log('vm', '    ' + item.toString('hex'));
      //   // });
      //   // info.stack.reverse();

      // };

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err);

        // console.log('gas: ', results.gasUsed.toNumber(), 'exp: ',  testData.exec.gas - testData.gas)
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          function(cb) {
            var stream = state.createReadStream();
            stream.on("data", function(data) {
              var account = new Account(data.value);
              console.log("key: " + data.key.toString("hex"));
              //console.log(data.value.toString('hex'));
              console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
            });

            stream.on('end', cb);
          },

//           function(cb) {
//             // cb()
//             // return

//             account = results.account;
//             acctData = testData.post[testData.exec.address];
//             testUtils.verifyAccountPostConditions(state, account, acctData, cb);
//           },

          function() {
            // validate the postcondition of other accounts
            // delete testData.post[testData.exec.address];
            var keysOfPost = Object.keys(testData.post);
            async.eachSeries(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);

                account = new Account(raw);
                acctData = testData.post[key];
                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe.skip('.', function() {
    var testKey = 'CallToNameRegistrator0',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          function(cb) {
            cb();

            // state.get(new Buffer(testData.exec.address, 'hex'), function(err, raw) {
            //   assert(!err);
            //   assert(!raw, 'contract should have been deleted by SUICIDE');
            //   cb();
            // });
          },
          function() {
            var keysOfPost = Object.keys(testData.post);
            async.each(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);
                var account = new Account(raw),
                  acctData = testData.post[key];
                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe('.', function() {
    var testKey = 'suicide0',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(testData.pre[testData.exec.caller].balance)
            .add(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var suicideTo = results.vm.suicideTo.toString('hex'),
          keysOfPost = Object.keys(testData.post);
        assert.strictEqual(keysOfPost.length, 1, '#post mismatch');
        assert.strictEqual(suicideTo, keysOfPost[0], 'suicideTo mismatch');

        state.get(new Buffer(suicideTo, 'hex'), function(err, acct) {
          assert(!err);
          var account = new Account(acct),
            acctData = testData.post[suicideTo];
          account.balance = bignum.fromBuffer(account.balance).sub(TMP_BAL_AVOID_NEG).toBuffer();

          testUtils.verifyAccountPostConditions(state, account, acctData, done);
        });
      });
    });
  });

  describe('.', function() {
    var testKey = 'suicideNotExistingAccount',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(testData.pre[testData.exec.caller].balance)
            .add(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          function(cb) {
            state.get(new Buffer(testData.exec.address, 'hex'), function(err, raw) {
              assert(!err);
              assert(!raw, 'contract should have been deleted by SUICIDE');
              cb();
            });
          },
          function() {
            var keysOfPost = Object.keys(testData.post),
              suicideCreated = testData.exec.code.substr(4, 20 * 2);
            assert(keysOfPost.indexOf(suicideCreated) !== -1, 'suicideCreated not in post');

            async.each(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);
                var account = new Account(raw),
                  acctData = testData.post[key];

console.log('@@@@@@@@ key: ', key)
                if (key === testData.exec.caller) {
                  account.balance = bignum.fromBuffer(account.balance).sub(TMP_BAL_AVOID_NEG).toBuffer();
                } else if (key === suicideCreated) {
                  console.log('@@@@@@@@ val: ', testData.exec.value)
                  account.balance = bignum.fromBuffer(account.balance).sub(testData.exec.value).toBuffer();
                }

                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe.skip('.', function() {
    var testKey = 'suicideSendEtherToMe',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var suicideTo = results.vm.suicideTo.toString('hex'),
          keysOfPost = Object.keys(testData.post);
        assert.strictEqual(keysOfPost.length, 1, '#post mismatch');
        assert.notStrictEqual(suicideTo, keysOfPost[0], 'suicideTo should not exist');

        async.series([
          function(cb) {
            state.get(new Buffer(suicideTo, 'hex'), function(err, acct) {
              assert(!err);
              assert(!acct, 'suicide account should be gone');
              cb();
            });
          },
          function() {
            state.get(new Buffer(keysOfPost[0], 'hex'), function(err, acct) {
              assert(!err);
              var account = new Account(acct),
                acctData = testData.post[keysOfPost[0]];
              testUtils.verifyAccountPostConditions(state, account, acctData, done);
            });
          }
        ], done);
      });
    });
  });
});
<commit_msg>suicideNotExistingAccount passes<commit_after>const vmSystemOperationsTest = require('ethereum-tests').vmtests.vmSystemOperationsTest,
  async = require('async'),
  VM = require('../../../lib/vm'),
  rlp = require('rlp'),
  Account = require('../../../lib/account.js'),
  bignum = require('bignum'),
  assert = require('assert'),
  testUtils = require('../../testUtils'),
  utils = require('../../../lib/utils.js'),
  Trie = require('merkle-patricia-tree');

// for SUICIDE tests, this is temporarily added to avoid negative balances
const TMP_BAL_AVOID_NEG = '13333337';

describe.only('[Common]: vmSystemOperationsTest', function() {
  var tests = Object.keys(vmSystemOperationsTest);
  // TODO add tests
  tests = ['CallToNameRegistrator0'];
  tests.forEach(function(testKey) {
    var state = new Trie();
    var testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      // vm.onStep = function(info, done) {
      //   console.log('vm', bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

      //   var stream = vm.trie.createReadStream();
      //   stream.on("data", function(data) {
      //     var account = new Account(data.value);
      //     console.log("key: " + data.key.toString("hex"));
      //     //console.log(data.value.toString('hex'));
      //     console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
      //   });

      //   stream.on('end', done);

      //   // info.stack.reverse();
      //   // info.stack.forEach(function (item) {
      //   //   console.log('vm', '    ' + item.toString('hex'));
      //   // });
      //   // info.stack.reverse();

      // };

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err);

        // console.log('gas: ', results.gasUsed.toNumber(), 'exp: ',  testData.exec.gas - testData.gas)
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          function(cb) {
            var stream = state.createReadStream();
            stream.on("data", function(data) {
              var account = new Account(data.value);
              console.log("key: " + data.key.toString("hex"));
              //console.log(data.value.toString('hex'));
              console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
            });

            stream.on('end', cb);
          },

//           function(cb) {
//             // cb()
//             // return

//             account = results.account;
//             acctData = testData.post[testData.exec.address];
//             testUtils.verifyAccountPostConditions(state, account, acctData, cb);
//           },

          function() {
            // validate the postcondition of other accounts
            // delete testData.post[testData.exec.address];
            var keysOfPost = Object.keys(testData.post);
            async.eachSeries(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);

                account = new Account(raw);
                acctData = testData.post[key];
                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe.skip('.', function() {
    var testKey = 'CallToNameRegistrator0',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          function(cb) {
            cb();

            // state.get(new Buffer(testData.exec.address, 'hex'), function(err, raw) {
            //   assert(!err);
            //   assert(!raw, 'contract should have been deleted by SUICIDE');
            //   cb();
            // });
          },
          function() {
            var keysOfPost = Object.keys(testData.post);
            async.each(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);
                var account = new Account(raw),
                  acctData = testData.post[key];
                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe('.', function() {
    var testKey = 'suicide0',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(testData.pre[testData.exec.caller].balance)
            .add(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var suicideTo = results.vm.suicideTo.toString('hex'),
          keysOfPost = Object.keys(testData.post);
        assert.strictEqual(keysOfPost.length, 1, '#post mismatch');
        assert.strictEqual(suicideTo, keysOfPost[0], 'suicideTo mismatch');

        state.get(new Buffer(suicideTo, 'hex'), function(err, acct) {
          assert(!err);
          var account = new Account(acct),
            acctData = testData.post[suicideTo];
          account.balance = bignum.fromBuffer(account.balance).sub(TMP_BAL_AVOID_NEG).toBuffer();

          testUtils.verifyAccountPostConditions(state, account, acctData, done);
        });
      });
    });
  });

  describe('.', function() {
    var testKey = 'suicideNotExistingAccount',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(testData.pre[testData.exec.caller].balance)
            .add(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          function(cb) {
            state.get(new Buffer(testData.exec.address, 'hex'), function(err, raw) {
              assert(!err);
              assert(!raw, 'contract should have been deleted by SUICIDE');
              cb();
            });
          },
          function() {
            var keysOfPost = Object.keys(testData.post),
              suicideCreated = testData.exec.code.substr(4, 20 * 2);
            assert(keysOfPost.length === 2, 'post should only have caller and suicideCreated')
            assert(keysOfPost.indexOf(suicideCreated) !== -1, 'suicideCreated not in post');

            async.each(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);
                var account = new Account(raw),
                  acctData = testData.post[key];

                if (key === testData.exec.caller) {
console.log('@@@@@@@@ bal: ', bignum.fromBuffer(account.balance))

                  account.balance = bignum.fromBuffer(account.balance)
                    .add(testData.exec.value)
                    .sub(TMP_BAL_AVOID_NEG).toBuffer();
                } else if (key === suicideCreated) {
                  // console.log('@@@@@@@@ val: ', testData.exec.value)
                  account.balance = bignum.fromBuffer(account.balance).sub(testData.exec.value).toBuffer();
                }

                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe.skip('.', function() {
    var testKey = 'suicideSendEtherToMe',
      state = new Trie(),
      testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var suicideTo = results.vm.suicideTo.toString('hex'),
          keysOfPost = Object.keys(testData.post);
        assert.strictEqual(keysOfPost.length, 1, '#post mismatch');
        assert.notStrictEqual(suicideTo, keysOfPost[0], 'suicideTo should not exist');

        async.series([
          function(cb) {
            state.get(new Buffer(suicideTo, 'hex'), function(err, acct) {
              assert(!err);
              assert(!acct, 'suicide account should be gone');
              cb();
            });
          },
          function() {
            state.get(new Buffer(keysOfPost[0], 'hex'), function(err, acct) {
              assert(!err);
              var account = new Account(acct),
                acctData = testData.post[keysOfPost[0]];
              testUtils.verifyAccountPostConditions(state, account, acctData, done);
            });
          }
        ], done);
      });
    });
  });
});
<|endoftext|>


<commit_before>import RecipeModal from 'components/RecipeModal';

import { Modal } from 'react-bootstrap';

import CreateModeModal from 'components/RecipeModal/CreateModeModal';
import ReadModeModal from 'components/RecipeModal/ReadModeModal';
import UpdateModeModal from 'components/RecipeModal/UpdateModeModal';
import DeleteModeModal from 'components/RecipeModal/DeleteModeModal';

describe('<RecipeModal />', () => {
  let props, wrapper, testRecipe;

  const buildWrapper = (isHidden, recipe, recipeId, mode) => {
    props = {
      isHidden,
      recipe,
      recipeId,
      mode,
      onCreate: spy(),
      onUpdate: spy(),
      onDelete: spy(),
      onHide: spy(),
      switchModal: spy()
    };

    wrapper = shallow(<RecipeModal {...props} />);
  }

  beforeEach(() => {
    buildWrapper(false, null, null, 'create');
  })

  it('should be a Bootstrap Modal with required attributes', () => {
    expect(wrapper).to.have.type(Modal);

    expect(wrapper).to.have.prop('show').equal(true);
    expect(wrapper).to.have.prop('onHide').equal(props.onHide);
  });

  context('Init Mode', () => {
    beforeEach(() => {
      buildWrapper(true, null, null, '');
    });

    it('should render blank Modal', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);
    });
  });

  context('Create Mode', () => {
    beforeEach(() => {
      buildWrapper(false, null, null, 'create');
    });

    it('should ONLY contain <CreateModeModal /> with required props', () => {
      expect(wrapper).to.have.exactly(1).descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);

      expect(wrapper.find(CreateModeModal)).to.have.prop('onCreate').equal(props.onCreate);
      expect(wrapper.find(CreateModeModal)).to.have.prop('onCancel').equal(props.onHide);
    });
  });

  context('Read Mode', () => {
    beforeEach(() => {
      testRecipe = { test: 'test '};

      buildWrapper(false, testRecipe, 2, 'read');
    });

    it('should ONLY contain <ReadModeModal /> with required props', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.have.exactly(1).descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);

      expect(wrapper.find(ReadModeModal)).to.have.prop('recipeId').equal(props.recipeId);
      expect(wrapper.find(ReadModeModal)).to.have.prop('recipe').equal(props.recipe);
      expect(wrapper.find(ReadModeModal)).to.have.prop('onHide').equal(props.onHide);
      expect(wrapper.find(ReadModeModal)).to.have.prop('switchModal').equal(props.switchModal);
    });

  });

  context('Update Mode', () => {
    beforeEach(() => {
      testRecipe = { test: 'test '};

      buildWrapper(false, testRecipe, 2, 'update');
    });

    it('should ONLY contain <UpdateModeModal />', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.have.exactly(1).descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);

      expect(wrapper.find(UpdateModeModal)).to.have.prop('recipeId').equal(props.recipeId);
      expect(wrapper.find(UpdateModeModal)).to.have.prop('recipe').equal(props.recipe);
      expect(wrapper.find(UpdateModeModal)).to.have.prop('onSave').equal(props.onUpdate);
      expect(wrapper.find(UpdateModeModal)).to.have.prop('switchModal').equal(props.switchModal);
    });
  });

  context('Delete Mode', () => {
    beforeEach(() => {
      testRecipe = { test: 'test '};

      buildWrapper(false, testRecipe, 2, 'delete');
    });

    it('should ONLY contain <DeleteModeModal />', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.have.exactly(1).descendants(DeleteModeModal);

      expect(wrapper.find(DeleteModeModal)).to.have.prop('recipeId').equal(props.recipeId);
      expect(wrapper.find(DeleteModeModal)).to.have.prop('recipe').equal(props.recipe);
      expect(wrapper.find(DeleteModeModal)).to.have.prop('onDelete').equal(props.onDelete);
      expect(wrapper.find(DeleteModeModal)).to.have.prop('onCancel').equal(props.onHide);
    });
  });
});
<commit_msg>Update props of DeleteModeModal in RecipeModal component<commit_after>import RecipeModal from 'components/RecipeModal';

import { Modal } from 'react-bootstrap';

import CreateModeModal from 'components/RecipeModal/CreateModeModal';
import ReadModeModal from 'components/RecipeModal/ReadModeModal';
import UpdateModeModal from 'components/RecipeModal/UpdateModeModal';
import DeleteModeModal from 'components/RecipeModal/DeleteModeModal';

describe('<RecipeModal />', () => {
  let props, wrapper, testRecipe;

  const buildWrapper = (isHidden, recipe, recipeId, mode) => {
    props = {
      isHidden,
      recipe,
      recipeId,
      mode,
      onCreate: spy(),
      onUpdate: spy(),
      onDelete: spy(),
      onHide: spy(),
      switchModal: spy()
    };

    wrapper = shallow(<RecipeModal {...props} />);
  }

  beforeEach(() => {
    buildWrapper(false, null, null, 'create');
  })

  it('should be a Bootstrap Modal with required attributes', () => {
    expect(wrapper).to.have.type(Modal);

    expect(wrapper).to.have.prop('show').equal(true);
    expect(wrapper).to.have.prop('onHide').equal(props.onHide);
  });

  context('Init Mode', () => {
    beforeEach(() => {
      buildWrapper(true, null, null, '');
    });

    it('should render blank Modal', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);
    });
  });

  context('Create Mode', () => {
    beforeEach(() => {
      buildWrapper(false, null, null, 'create');
    });

    it('should ONLY contain <CreateModeModal /> with required props', () => {
      expect(wrapper).to.have.exactly(1).descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);

      expect(wrapper.find(CreateModeModal)).to.have.prop('onCreate').equal(props.onCreate);
      expect(wrapper.find(CreateModeModal)).to.have.prop('onCancel').equal(props.onHide);
    });
  });

  context('Read Mode', () => {
    beforeEach(() => {
      testRecipe = { test: 'test '};

      buildWrapper(false, testRecipe, 2, 'read');
    });

    it('should ONLY contain <ReadModeModal /> with required props', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.have.exactly(1).descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);

      expect(wrapper.find(ReadModeModal)).to.have.prop('recipeId').equal(props.recipeId);
      expect(wrapper.find(ReadModeModal)).to.have.prop('recipe').equal(props.recipe);
      expect(wrapper.find(ReadModeModal)).to.have.prop('onHide').equal(props.onHide);
      expect(wrapper.find(ReadModeModal)).to.have.prop('switchModal').equal(props.switchModal);
    });

  });

  context('Update Mode', () => {
    beforeEach(() => {
      testRecipe = { test: 'test '};

      buildWrapper(false, testRecipe, 2, 'update');
    });

    it('should ONLY contain <UpdateModeModal />', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.have.exactly(1).descendants(UpdateModeModal);
      expect(wrapper).to.not.have.descendants(DeleteModeModal);

      expect(wrapper.find(UpdateModeModal)).to.have.prop('recipeId').equal(props.recipeId);
      expect(wrapper.find(UpdateModeModal)).to.have.prop('recipe').equal(props.recipe);
      expect(wrapper.find(UpdateModeModal)).to.have.prop('onSave').equal(props.onUpdate);
      expect(wrapper.find(UpdateModeModal)).to.have.prop('switchModal').equal(props.switchModal);
    });
  });

  context('Delete Mode', () => {
    beforeEach(() => {
      testRecipe = { test: 'test '};

      buildWrapper(false, testRecipe, 2, 'delete');
    });

    it('should ONLY contain <DeleteModeModal />', () => {
      expect(wrapper).to.not.have.descendants(CreateModeModal);
      expect(wrapper).to.not.have.descendants(ReadModeModal);
      expect(wrapper).to.not.have.descendants(UpdateModeModal);
      expect(wrapper).to.have.exactly(1).descendants(DeleteModeModal);

      expect(wrapper.find(DeleteModeModal)).to.have.prop('recipeId').equal(props.recipeId);
      expect(wrapper.find(DeleteModeModal)).to.have.prop('recipe').equal(props.recipe);
      expect(wrapper.find(DeleteModeModal)).to.have.prop('onDelete').equal(props.onDelete);
      expect(wrapper.find(DeleteModeModal)).to.have.prop('onCancel').equal(props.switchModal);
    });
  });
});
<|endoftext|>